forge/app/Models/SptVersion.php

80 lines
2.2 KiB
PHP
Raw Normal View History

2024-05-15 00:31:24 -04:00
<?php
namespace App\Models;
use App\Exceptions\InvalidVersionNumberException;
use App\Services\LatestSptVersionService;
2024-05-15 00:31:24 -04:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
2024-05-15 00:31:24 -04:00
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\App;
2024-05-15 00:31:24 -04:00
class SptVersion extends Model
{
use HasFactory, SoftDeletes;
/**
* Get the version with "SPT " prepended.
*/
public function getVersionFormattedAttribute(): string
{
return __('SPT ').$this->version;
}
2024-07-20 19:52:36 -04:00
/**
* The relationship between an SPT version and mod version.
*/
public function modVersions(): BelongsToMany
2024-05-15 00:31:24 -04:00
{
return $this->belongsToMany(ModVersion::class, 'mod_version_spt_version');
2024-05-15 00:31:24 -04:00
}
/**
* Determine if the version is the latest minor version.
*/
public function isLatestMinor(): bool
{
$latestSptVersionService = App::make(LatestSptVersionService::class);
$latestVersion = $latestSptVersionService->getLatestVersion();
if (! $latestVersion) {
return false;
}
try {
[$currentMajor, $currentMinor, $currentPatch] = $this->extractVersionParts($this->version);
[$latestMajor, $latestMinor, $latestPatch] = $this->extractVersionParts($latestVersion->version);
} catch (InvalidVersionNumberException $e) {
return false;
}
return $currentMajor == $latestMajor && $currentMinor === $latestMinor;
}
/**
* Extract the version components from a full version string.
*
* @throws InvalidVersionNumberException
*/
private function extractVersionParts(string $version): array
{
// Remove everything from the version string except the numbers and dots.
$version = preg_replace('/[^0-9.]/', '', $version);
// Validate that the version string is a valid semver.
if (! preg_match('/^\d+\.\d+\.\d+$/', $version)) {
throw new InvalidVersionNumberException;
}
$parts = explode('.', $version);
return [
(int) $parts[0],
(int) $parts[1],
(int) $parts[2],
];
}
2024-05-15 00:31:24 -04:00
}