forge/app/Models/SptVersion.php
Refringe 1783a683ed
Semvar & Automatic Resolution - Remix
- Updated the SptVersion and ModVersion dependancies to resolve *all* compatible versions and introduced new relationships to pull just the latest compatible version. Had to rewrite a *bunch*, but it should be much more capable now. It can be expensive to resolve these properties when iterated over, so *make sure they're eager loaded using the `with` method when you're building the queries*.
- Updated the mod listing Livewire component to save the filter options within the PHP session instead of in browser local storage. *Much* cleaner.
- Removed caching from homepage queries to see how they preform on production. Will add back later.
- Updated ModVersion factory to create SptVersions if there are none specified.
- Probably lots of other changes too... I need to make smaller commits. :(
2024-08-29 15:46:10 -04:00

80 lines
2.2 KiB
PHP

<?php
namespace App\Models;
use App\Exceptions\InvalidVersionNumberException;
use App\Services\LatestSptVersionService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\App;
class SptVersion extends Model
{
use HasFactory, SoftDeletes;
/**
* Get the version with "SPT " prepended.
*/
public function getVersionFormattedAttribute(): string
{
return __('SPT ').$this->version;
}
/**
* The relationship between an SPT version and mod version.
*/
public function modVersions(): BelongsToMany
{
return $this->belongsToMany(ModVersion::class, 'mod_version_spt_version');
}
/**
* 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],
];
}
}