chore: rector (#970)

This commit is contained in:
Kyrch
2025-10-01 17:18:31 -03:00
committed by GitHub
parent ac9b4be61b
commit ad899b7271
754 changed files with 1746 additions and 3674 deletions
+1 -1
View File
@@ -30,7 +30,7 @@ class DiscordMessageAction
if (Arr::has($fields, DiscordMessage::ATTRIBUTE_URL)) {
$url = Arr::get($fields, DiscordMessage::ATTRIBUTE_URL);
preg_match('/https:\/\/discord\.com\/channels\/(\d+)\/(\d+)\/(\d+)/', $url, $matches);
preg_match('/https:\/\/discord\.com\/channels\/(\d+)\/(\d+)\/(\d+)/', (string) $url, $matches);
$message
->setChannelId(strval($matches[2]))
+1 -1
View File
@@ -27,7 +27,7 @@ class UpdateUserPassword implements UpdatesUserPasswords
Validator::make($input, [
'current_password' => ['required', 'string'],
User::ATTRIBUTE_PASSWORD => Password::required(),
])->after(function (IlluminateValidator $validator) use ($user, $input) {
])->after(function (IlluminateValidator $validator) use ($user, $input): void {
if (! isset($input['current_password']) || ! Hash::check($input['current_password'], $user->password)) {
$validator->errors()
->add('current_password', __('The provided password does not match your current password.'));
@@ -30,7 +30,7 @@ class UpdateUserProfileInformation implements UpdatesUserProfileInformation
$email = Arr::get($validated, User::ATTRIBUTE_EMAIL);
if (Arr::has($validated, User::ATTRIBUTE_EMAIL) && $email !== $user->email) {
$validated = $validated + [User::ATTRIBUTE_EMAIL_VERIFIED_AT => null];
$validated += [User::ATTRIBUTE_EMAIL_VERIFIED_AT => null];
$user->update($validated);
+3 -2
View File
@@ -6,6 +6,7 @@ namespace App\Actions\Http\Api;
use App\Concerns\Actions\Http\Api\ConstrainsEagerLoads;
use App\Enums\Http\Api\Paging\PaginationStrategy;
use App\Http\Api\Criteria\Paging\Criteria;
use App\Http\Api\Filter\HasFilter;
use App\Http\Api\Query\Query;
use App\Http\Api\Schema\EloquentSchema;
@@ -53,7 +54,7 @@ class IndexAction
// paginate
$paginationCriteria = $query->getPagingCriteria(PaginationStrategy::OFFSET);
return $paginationCriteria !== null
return $paginationCriteria instanceof Criteria
? $paginationCriteria->paginate($builder)
: $builder->get();
}
@@ -65,7 +66,7 @@ class IndexAction
): Collection|Paginator {
$search = $this->getSearch();
if ($search !== null && $search->shouldSearch($query) && $schema instanceof EloquentSchema) {
if ($search instanceof Search && $search->shouldSearch($query) && $schema instanceof EloquentSchema) {
return $search->search($query, $schema, $paginationStrategy);
}
@@ -20,8 +20,6 @@ use Illuminate\Support\Facades\Log;
class StoreTrackAction
{
/**
* @param array $parameters
*
* @throws Exception
*/
public function store(Playlist $playlist, Builder $builder, array $parameters): PlaylistTrack
@@ -31,7 +29,7 @@ class StoreTrackAction
$previousHashid = Arr::pull($trackParameters, PlaylistTrack::RELATION_PREVIOUS);
$nextHashid = Arr::pull($trackParameters, PlaylistTrack::RELATION_NEXT);
$trackParameters = $trackParameters + [PlaylistTrack::ATTRIBUTE_PLAYLIST => $playlist->getKey()];
$trackParameters += [PlaylistTrack::ATTRIBUTE_PLAYLIST => $playlist->getKey()];
try {
DB::beginTransaction();
@@ -19,8 +19,6 @@ use Illuminate\Support\Facades\Log;
class UpdateTrackAction
{
/**
* @param array $parameters
*
* @throws Exception
*/
public function update(Playlist $playlist, PlaylistTrack $track, array $parameters): PlaylistTrack
-1
View File
@@ -14,7 +14,6 @@ class StoreAction
{
/**
* @param Builder<TModel> $builder
* @param array $parameters
* @return TModel
*/
public function store(Builder $builder, array $parameters): Model
-1
View File
@@ -13,7 +13,6 @@ class UpdateAction
{
/**
* @param TModel $model
* @param array $parameters
* @return TModel
*/
public function update(Model $model, array $parameters): Model
@@ -21,7 +21,6 @@ class StoreImageAction extends StoreAction
{
/**
* @param Builder<Image> $builder
* @param array $parameters
*/
public function store(Builder $builder, array $parameters): Image
{
+1 -1
View File
@@ -24,7 +24,7 @@ abstract class ResponseStreamAction extends StreamAction
$fs = Storage::disk($this->disk());
$response->setCallback(function () use ($fs) {
$response->setCallback(function () use ($fs): void {
$stream = $fs->readStream($this->streamable->path());
fpassthru($stream);
fclose($stream);
@@ -27,9 +27,6 @@ abstract class BackfillWikiAction
final public const RESOURCES = 'resources';
final public const IMAGES = 'images';
/**
* @param array $toBackfill
*/
public function __construct(protected BaseModel $model, protected array $toBackfill) {}
abstract public function handle(): ActionResult;
@@ -20,9 +20,6 @@ abstract class BaseExternalEntryUnclaimedAction
*/
protected ?array $data = null;
/**
* @param ExternalProfile|array $profile
*/
public function __construct(protected ExternalProfile|array $profile) {}
public function getUsername(): string
@@ -29,7 +29,7 @@ class AnilistExternalEntryClaimedAction extends BaseExternalEntryClaimedAction
}
if ($data = $this->data) {
$lists = Arr::where(Arr::get($data, 'MediaListCollection.lists'), fn ($value) => $value['isCustomList'] === false);
$lists = Arr::where(Arr::get($data, 'MediaListCollection.lists'), fn ($value): bool => $value['isCustomList'] === false);
foreach ($lists as $list) {
foreach (Arr::get($list, 'entries') as $entry) {
@@ -29,7 +29,7 @@ class AnilistExternalEntryUnclaimedAction extends BaseExternalEntryUnclaimedActi
}
$favorites = Arr::map(Arr::get($this->data, 'User.favourites.anime.nodes'), fn ($value) => $value['id']);
$lists = Arr::where(Arr::get($this->data, 'MediaListCollection.lists'), fn ($value) => $value['isCustomList'] === false);
$lists = Arr::where(Arr::get($this->data, 'MediaListCollection.lists'), fn ($value): bool => $value['isCustomList'] === false);
foreach ($lists as $list) {
foreach (Arr::get($list, 'entries') as $entry) {
@@ -25,7 +25,6 @@ class StoreExternalProfileClaimedAction
/**
* Get the first record or store external profile given determined external token.
*
* @param array $parameters
*
* @throws Exception
*/
@@ -38,9 +37,7 @@ class StoreExternalProfileClaimedAction
$userId = $action->getUserId();
$profile = $this->firstForUserIdOrCreate($userId, $site, $action, $parameters);
return $profile;
return $this->firstForUserIdOrCreate($userId, $site, $action, $parameters);
} catch (Exception $e) {
Log::error($e->getMessage());
@@ -50,8 +47,6 @@ class StoreExternalProfileClaimedAction
/**
* Get the first record or create the profile for a userId and site.
*
* @param array $parameters
*/
protected function firstForUserIdOrCreate(int $userId, ExternalProfileSite $site, BaseExternalEntryClaimedAction $action, array $parameters): ExternalProfile
{
@@ -22,7 +22,6 @@ class StoreExternalProfileUnclaimedAction
/**
* Get the first record or store an external profile and its entries given determined username.
*
* @param array $profileParameters
*
* @throws Exception
*/
@@ -43,9 +42,7 @@ class StoreExternalProfileUnclaimedAction
->first();
if ($findProfile instanceof ExternalProfile) {
if ($findProfile->isClaimed()) {
throw new Exception("The external profile '{$findProfile->getName()}' is already claimed.");
}
throw_if($findProfile->isClaimed(), new Exception("The external profile '{$findProfile->getName()}' is already claimed."));
DB::rollBack();
@@ -79,7 +76,6 @@ class StoreExternalProfileUnclaimedAction
/**
* Get the mapping for the entries class.
*
* @param ExternalProfile|array $profile
*
* @throws RuntimeException
*/
@@ -107,14 +107,12 @@ class SyncExternalProfileAction
protected function cacheResources(ExternalProfileSite $profileSite): void
{
// External resources are only added by mods so it doesn't change too often.
$this->resources = Cache::flexible("resources_{$profileSite->name}", [60, 300], function () use ($profileSite) {
return ExternalResource::query()
->where(ExternalResource::ATTRIBUTE_SITE, $profileSite->getResourceSite()->value)
->with([ExternalResource::RELATION_ANIME => fn ($query) => $query->select([Anime::TABLE.'.'.Anime::ATTRIBUTE_ID])])
->whereHas(ExternalResource::RELATION_ANIME)
->get()
->mapWithKeys(fn (ExternalResource $resource) => [$resource->external_id => $resource->anime->map(fn (Anime $anime) => $anime->getKey())]);
});
$this->resources = Cache::flexible("resources_{$profileSite->name}", [60, 300], fn () => ExternalResource::query()
->where(ExternalResource::ATTRIBUTE_SITE, $profileSite->getResourceSite()->value)
->with([ExternalResource::RELATION_ANIME => fn ($query) => $query->select([Anime::TABLE.'.'.Anime::ATTRIBUTE_ID])])
->whereHas(ExternalResource::RELATION_ANIME)
->get()
->mapWithKeys(fn (ExternalResource $resource): array => [$resource->external_id => $resource->anime->map(fn (Anime $anime) => $anime->getKey())]));
}
/**
@@ -12,7 +12,6 @@ abstract class BaseExternalTokenAction
/**
* Use the authorization code to get the tokens and store them.
*
* @param array $parameters
*
* @throws Exception
*/
@@ -20,7 +20,6 @@ class AnilistExternalTokenAction extends BaseExternalTokenAction
/**
* Use the authorization code to get the tokens and store them.
*
* @param array $parameters
*
* @throws Exception
*/
@@ -43,9 +42,7 @@ class AnilistExternalTokenAction extends BaseExternalTokenAction
$token = Arr::get($response, 'access_token');
if ($token === null) {
throw new Error('Failed to get token');
}
throw_if($token === null, new Error('Failed to get token'));
return ExternalToken::query()->create([
ExternalToken::ATTRIBUTE_ACCESS_TOKEN => Crypt::encrypt($token),
@@ -21,7 +21,6 @@ class MalExternalTokenAction extends BaseExternalTokenAction
/**
* Use the authorization code to get the tokens and store them.
*
* @param array $parameters
*
* @throws Exception
*/
@@ -48,9 +47,7 @@ class MalExternalTokenAction extends BaseExternalTokenAction
$token = Arr::get($response, 'access_token');
$refreshToken = Arr::get($response, 'refresh_token');
if ($token === null) {
throw new Error('Failed to get token');
}
throw_if($token === null, new Error('Failed to get token'));
} catch (Exception $e) {
Log::error($e->getMessage());
@@ -23,7 +23,6 @@ class ExternalTokenCallbackAction
/**
* We should store the token and the profile.
*
* @param array $parameters
*
* @throws Exception
*/
@@ -19,7 +19,7 @@ class FixPlaylistAction
$this->sendMessage("Fetching tracks for playlist ID: {$playlist->getKey()}...", $context, 'info');
/** @var Collection<int, PlaylistTrack> $tracks */
$tracks = PlaylistTrack::where(PlaylistTrack::ATTRIBUTE_PLAYLIST, $playlist->getKey())
$tracks = PlaylistTrack::query()->where(PlaylistTrack::ATTRIBUTE_PLAYLIST, $playlist->getKey())
->orderBy(PlaylistTrack::ATTRIBUTE_ID)
->get()
->keyBy(PlaylistTrack::ATTRIBUTE_ID);
@@ -55,13 +55,11 @@ class FixPlaylistAction
}
// Check if we have traversed all tracks; if not, some tracks are broken
if (count($orderedTracks) != count($tracks)) {
if (count($orderedTracks) !== count($tracks)) {
$this->sendMessage('Detected broken tracks, attempting to add them to the end of the list...', $context, 'warn');
// Find all tracks that were not visited (potentially broken)
$remainingTracks = $tracks->filter(function ($track) use ($visitedTracks) {
return ! isset($visitedTracks[$track->track_id]);
});
$remainingTracks = $tracks->reject(fn ($track): bool => isset($visitedTracks[$track->track_id]));
// Add remaining tracks to the end, preserving the existing order as much as possible
foreach ($remainingTracks as $remainingTrack) {
@@ -71,7 +69,7 @@ class FixPlaylistAction
// Update the previous_id and next_id for all tracks in the correct order
$this->sendMessage('Updating track links (previous_id and next_id)...', $context, 'info');
DB::transaction(function () use ($orderedTracks, $tracks, $playlist, $context) {
DB::transaction(function () use ($orderedTracks, $tracks, $playlist, $context): void {
$previous_id = null;
foreach ($orderedTracks as $index => $track_id) {
@@ -38,7 +38,6 @@ class ReportAction
* Create a report step to create a model.
*
* @param class-string<Model> $model
* @param array $fields
*/
public static function makeForCreate(string $model, array $fields): ReportStep
{
@@ -47,8 +46,6 @@ class ReportAction
/**
* Create a report step to edit a model.
*
* @param array $fields
*/
public static function makeForUpdate(Model $model, array $fields): ReportStep
{
@@ -67,7 +64,6 @@ class ReportAction
* Create a report step to attach a model to another in a many-to-many relationship.
*
* @param class-string<Pivot> $pivot
* @param array $fields
*/
public static function makeForAttach(Model $foreign, Model $related, string $pivot, array $fields): ReportStep
{
@@ -76,8 +72,6 @@ class ReportAction
/**
* Create a report step to detach a model from another in a many-to-many relationship.
*
* @param array $fields
*/
public static function makeForDetach(Model $foreign, Model $related, Pivot $pivot, array $fields): ReportStep
{
@@ -88,7 +82,6 @@ class ReportAction
* Create a report step for given action.
*
* @param class-string<Model>|Model $model
* @param array|null $fields
*/
protected static function makeFor(ReportActionType $action, Model|string $model, ?array $fields = null, ?Model $related = null, Pivot|string|null $pivot = null): ReportStep
{
@@ -105,8 +105,6 @@ class AnilistAnimeExternalApiAction extends ExternalApiAction implements Backfil
/**
* Get the available sites to backfill.
*
* @return array
*/
public function getResourcesMapping(): array
{
@@ -74,8 +74,6 @@ class JikanAnimeExternalApiAction extends ExternalApiAction implements BackfillR
/**
* Get the available sites to backfill.
*
* @return array
*/
public function getResourcesMapping(): array
{
@@ -47,8 +47,6 @@ class MalAnimeExternalApiAction extends ExternalApiAction implements BackfillStu
/**
* Get the mapped studios.
*
* @return array
*/
public function getStudios(): array
{
@@ -15,7 +15,6 @@ class AttachImageAction
use CanCreateImage;
/**
* @param array $fields
* @param ImageFacet[] $facets
*/
public function handle(BaseModel&HasImages $model, array $fields, array $facets): void
@@ -15,7 +15,6 @@ class AttachResourceAction
use CanCreateExternalResource;
/**
* @param array $fields
* @param ResourceSite[] $sites
*/
public function handle(BaseModel&HasResources $model, array $fields, array $sites): void
@@ -29,12 +29,9 @@ class BackfillAnimeAction extends BackfillWikiAction
use CanCreateAnimeSynonym;
use CanCreateStudio;
final public const STUDIOS = 'studios';
final public const SYNONYMS = 'synonyms';
final public const string STUDIOS = 'studios';
final public const string SYNONYMS = 'synonyms';
/**
* @param array $toBackfill
*/
public function __construct(protected Anime $anime, protected array $toBackfill)
{
parent::__construct($anime, $toBackfill);
@@ -51,7 +51,7 @@ class BackfillSongAction extends BackfillAction
$label = $matches[2][$key];
$resourceSite = $this->getMappingFromExternalSite($label);
if (! $resourceSite) {
if (! $resourceSite instanceof ResourceSite) {
Log::info("Skipping {$label} for Song {$this->getModel()->getName()}");
continue;
}
@@ -95,8 +95,6 @@ class BackfillSongAction extends BackfillAction
/**
* Get the relation to resources.
*
* @return BelongsToMany
*/
protected function relation(): BelongsToMany
{
@@ -16,9 +16,6 @@ use Illuminate\Support\Facades\Log;
class BackfillStudioAction extends BackfillWikiAction
{
/**
* @param array $toBackfill
*/
public function __construct(protected Studio $studio, protected array $toBackfill)
{
parent::__construct($studio, $toBackfill);
@@ -13,17 +13,12 @@ use Illuminate\Support\Arr;
abstract class ExternalApiAction
{
/**
* @var array|null
*/
public ?array $response = null;
abstract public function getSite(): ResourceSite;
/**
* Set the response after the request.
*
* @param BelongsToMany $resources
*/
abstract public function handle(BelongsToMany $resources): static;
@@ -116,7 +116,7 @@ class ManageSongPerformances
->whereNotIn(
Performance::ATTRIBUTE_ARTIST_ID,
Arr::map(
Arr::where($performancesToCreate, fn ($performance) => $performance[Performance::ATTRIBUTE_ARTIST_TYPE] === Relation::getMorphAlias(Membership::class)),
Arr::where($performancesToCreate, fn ($performance): bool => $performance[Performance::ATTRIBUTE_ARTIST_TYPE] === Relation::getMorphAlias(Membership::class)),
fn ($performanceMembership) => Arr::get($performanceMembership, Performance::ATTRIBUTE_ARTIST_ID)
)
);
@@ -130,7 +130,7 @@ class ManageSongPerformances
->whereNotIn(
Performance::ATTRIBUTE_ARTIST_ID,
Arr::map(
Arr::where($performancesToCreate, fn ($performance) => $performance[Performance::ATTRIBUTE_ARTIST_TYPE] === Relation::getMorphAlias(Artist::class)),
Arr::where($performancesToCreate, fn ($performance): bool => $performance[Performance::ATTRIBUTE_ARTIST_TYPE] === Relation::getMorphAlias(Artist::class)),
fn ($solo) => Arr::get($solo, Performance::ATTRIBUTE_ARTIST_ID)
)
);
@@ -63,7 +63,7 @@ class BackfillAudioAction extends BackfillAction
$audio = $this->getAudio();
if ($audio !== null) {
if ($audio instanceof Audio) {
$this->attachAudio($audio);
}
@@ -136,7 +136,7 @@ class BackfillAudioAction extends BackfillAction
}
// It's possible that the video is not attached to any themes, exit early.
if ($sourceVideo === null) {
if (! $sourceVideo instanceof Video) {
Log::error('Could not derive source video');
return null;
@@ -34,7 +34,7 @@ class ReconcileDumpRepositoriesAction extends ReconcileRepositoriesAction
*/
protected function diffCallbackForCreateDelete(): Closure
{
return fn (Dump $first, Dump $second) => [$first->path] <=> [$second->path];
return fn (Dump $first, Dump $second): int => [$first->path] <=> [$second->path];
}
/**
@@ -52,13 +52,11 @@ class ReconcileDumpRepositoriesAction extends ReconcileRepositoriesAction
*/
protected function diffCallbackForUpdate(): Closure
{
return fn () => 0;
return fn (): int => 0;
}
/**
* Get source model that has been updated for destination model.
*
* @param Collection $sourceModels
*/
protected function resolveUpdatedModel(Collection $sourceModels, Model $destinationModel): ?Model
{
@@ -67,10 +65,6 @@ class ReconcileDumpRepositoriesAction extends ReconcileRepositoriesAction
/**
* Get reconciliation results.
*
* @param Collection $created
* @param Collection $deleted
* @param Collection $updated
*/
protected function getResults(Collection $created, Collection $deleted, Collection $updated): ReconcileResults
{
@@ -70,9 +70,6 @@ abstract class ReconcileRepositoriesAction
* Create models that exist in source but not in destination.
*
* @param RepositoryInterface<TModel> $destination
* @param Collection $sourceModels
* @param Collection $destinationModels
* @return Collection
*/
protected function createModelsFromSource(
RepositoryInterface $destination,
@@ -81,16 +78,13 @@ abstract class ReconcileRepositoriesAction
): Collection {
$createModels = $sourceModels->diffUsing($destinationModels, $this->diffCallbackForCreateDelete());
return $createModels->each(fn (Model $createModel) => $destination->save($createModel));
return $createModels->each(fn (Model $createModel): bool => $destination->save($createModel));
}
/**
* Delete models that exist in destination but not in source.
*
* @param RepositoryInterface<TModel> $destination
* @param Collection $sourceModels
* @param Collection $destinationModels
* @return Collection
*/
protected function deleteModelsFromDestination(
RepositoryInterface $destination,
@@ -99,7 +93,7 @@ abstract class ReconcileRepositoriesAction
): Collection {
$deleteModels = $destinationModels->diffUsing($sourceModels, $this->diffCallbackForCreateDelete());
return $deleteModels->each(fn (Model $deleteModel) => $destination->delete($deleteModel));
return $deleteModels->each(fn (Model $deleteModel): bool => $destination->delete($deleteModel));
}
/**
@@ -116,8 +110,6 @@ abstract class ReconcileRepositoriesAction
/**
* Get source model that has been updated for destination model.
*
* @param Collection $sourceModels
*/
abstract protected function resolveUpdatedModel(Collection $sourceModels, Model $destinationModel): ?Model;
@@ -125,9 +117,6 @@ abstract class ReconcileRepositoriesAction
* Update destination models that have changed in source.
*
* @param RepositoryInterface<TModel> $destination
* @param Collection $sourceModels
* @param Collection $destinationModels
* @return Collection
*/
protected function updateDestinationModels(
RepositoryInterface $destination,
@@ -136,9 +125,9 @@ abstract class ReconcileRepositoriesAction
): Collection {
$updatedModels = $destinationModels->diffUsing($sourceModels, $this->diffCallbackForUpdate());
return $updatedModels->each(function (Model $updatedModel) use ($sourceModels, $destination) {
return $updatedModels->each(function (Model $updatedModel) use ($sourceModels, $destination): void {
$sourceModel = $this->resolveUpdatedModel($sourceModels, $updatedModel);
if ($sourceModel !== null) {
if ($sourceModel instanceof Model) {
$destination->update($updatedModel, $sourceModel->toArray());
}
});
@@ -146,10 +135,6 @@ abstract class ReconcileRepositoriesAction
/**
* Get reconciliation results.
*
* @param Collection $created
* @param Collection $deleted
* @param Collection $updated
*/
abstract protected function getResults(Collection $created, Collection $deleted, Collection $updated): ReconcileResults;
}
+8 -14
View File
@@ -18,11 +18,6 @@ use Illuminate\Support\Str;
*/
abstract class ReconcileResults extends ActionResult
{
/**
* @param Collection $created
* @param Collection $deleted
* @param Collection $updated
*/
public function __construct(
protected readonly Collection $created = new Collection(),
protected readonly Collection $deleted = new Collection(),
@@ -33,8 +28,6 @@ abstract class ReconcileResults extends ActionResult
/**
* Get created models.
*
* @return Collection
*/
public function getCreated(): Collection
{
@@ -43,8 +36,6 @@ abstract class ReconcileResults extends ActionResult
/**
* Get deleted models.
*
* @return Collection
*/
public function getDeleted(): Collection
{
@@ -53,8 +44,6 @@ abstract class ReconcileResults extends ActionResult
/**
* Get updated models.
*
* @return Collection
*/
public function getUpdated(): Collection
{
@@ -66,7 +55,14 @@ abstract class ReconcileResults extends ActionResult
*/
public function hasChanges(): bool
{
return $this->created->isNotEmpty() || $this->deleted->isNotEmpty() || $this->updated->isNotEmpty();
if ($this->created->isNotEmpty()) {
return true;
}
if ($this->deleted->isNotEmpty()) {
return true;
}
return $this->updated->isNotEmpty();
}
/**
@@ -120,8 +116,6 @@ abstract class ReconcileResults extends ActionResult
/**
* Get the user-friendly label for the model class name.
*
* @param int|array|Countable $models
*/
protected function label(int|array|Countable $models = 1): string
{
@@ -34,7 +34,7 @@ class ReconcileAudioRepositoriesAction extends ReconcileRepositoriesAction
*/
protected function diffCallbackForCreateDelete(): Closure
{
return fn (Audio $first, Audio $second) => $first->basename <=> $second->basename;
return fn (Audio $first, Audio $second): int => $first->basename <=> $second->basename;
}
/**
@@ -59,13 +59,11 @@ class ReconcileAudioRepositoriesAction extends ReconcileRepositoriesAction
*/
protected function diffCallbackForUpdate(): Closure
{
return fn (Audio $first, Audio $second) => [$first->basename, $first->path, $first->size] <=> [$second->basename, $second->path, $second->size];
return fn (Audio $first, Audio $second): int => [$first->basename, $first->path, $first->size] <=> [$second->basename, $second->path, $second->size];
}
/**
* Get source model that has been updated for destination model.
*
* @param Collection $sourceModels
*/
protected function resolveUpdatedModel(Collection $sourceModels, Model $destinationModel): ?Model
{
@@ -77,10 +75,6 @@ class ReconcileAudioRepositoriesAction extends ReconcileRepositoriesAction
/**
* Get reconciliation results.
*
* @param Collection $created
* @param Collection $deleted
* @param Collection $updated
*/
protected function getResults(Collection $created, Collection $deleted, Collection $updated): ReconcileResults
{
@@ -34,7 +34,7 @@ class ReconcileVideoRepositoriesAction extends ReconcileRepositoriesAction
*/
protected function diffCallbackForCreateDelete(): Closure
{
return fn (Video $first, Video $second) => $first->basename <=> $second->basename;
return fn (Video $first, Video $second): int => $first->basename <=> $second->basename;
}
/**
@@ -59,13 +59,11 @@ class ReconcileVideoRepositoriesAction extends ReconcileRepositoriesAction
*/
protected function diffCallbackForUpdate(): Closure
{
return fn (Video $first, Video $second) => [$first->basename, $first->path, $first->size] <=> [$second->basename, $second->path, $second->size];
return fn (Video $first, Video $second): int => [$first->basename, $first->path, $first->size] <=> [$second->basename, $second->path, $second->size];
}
/**
* Get source model that has been updated for destination model.
*
* @param Collection $sourceModels
*/
protected function resolveUpdatedModel(Collection $sourceModels, Model $destinationModel): ?Model
{
@@ -77,10 +75,6 @@ class ReconcileVideoRepositoriesAction extends ReconcileRepositoriesAction
/**
* Get reconciliation results.
*
* @param Collection $created
* @param Collection $deleted
* @param Collection $updated
*/
protected function getResults(Collection $created, Collection $deleted, Collection $updated): ReconcileResults
{
@@ -34,7 +34,7 @@ class ReconcileScriptRepositoriesAction extends ReconcileRepositoriesAction
*/
protected function diffCallbackForCreateDelete(): Closure
{
return fn (VideoScript $first, VideoScript $second) => [$first->path] <=> [$second->path];
return fn (VideoScript $first, VideoScript $second): int => [$first->path] <=> [$second->path];
}
/**
@@ -52,13 +52,11 @@ class ReconcileScriptRepositoriesAction extends ReconcileRepositoriesAction
*/
protected function diffCallbackForUpdate(): Closure
{
return fn () => 0;
return fn (): int => 0;
}
/**
* Get source model that has been updated for destination model.
*
* @param Collection $sourceModels
*/
protected function resolveUpdatedModel(Collection $sourceModels, Model $destinationModel): ?Model
{
@@ -67,10 +65,6 @@ class ReconcileScriptRepositoriesAction extends ReconcileRepositoriesAction
/**
* Get reconciliation results.
*
* @param Collection $created
* @param Collection $deleted
* @param Collection $updated
*/
protected function getResults(Collection $created, Collection $deleted, Collection $updated): ReconcileResults
{
@@ -45,7 +45,7 @@ abstract class DumpAction
$connection = DB::connection();
$dumper = $this->getDumper($connection);
if ($dumper === null) {
if (! $dumper instanceof DbDumper) {
return new ActionResult(
ActionStatus::FAILED,
"Unrecognized connection '{$connection->getName()}'"
@@ -110,9 +110,7 @@ abstract class DumpAction
*/
protected function prepareSqliteDumper(Connection $connection): Sqlite
{
if (version_compare($connection->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '3.32.0', '<')) {
throw new RuntimeException('DB connection does not support includeTables option');
}
throw_if(version_compare($connection->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '3.32.0', '<'), new RuntimeException('DB connection does not support includeTables option'));
$dumper = Sqlite::create();
@@ -266,8 +264,6 @@ abstract class DumpAction
/**
* The list of tables to include in the dump.
*
* @return array
*/
abstract protected function allowedTables(): array;
}
@@ -18,12 +18,10 @@ class DumpAdminAction extends DumpAction
{
use ReconcilesDumpRepositories;
final public const FILENAME_PREFIX = 'animethemes-db-dump-admin-';
final public const string FILENAME_PREFIX = 'animethemes-db-dump-admin-';
/**
* The list of tables to include in the dump.
*
* @return array
*/
protected function allowedTables(): array
{
@@ -17,12 +17,10 @@ class DumpAuthAction extends DumpAction
{
use ReconcilesDumpRepositories;
final public const FILENAME_PREFIX = 'animethemes-db-dump-auth-';
final public const string FILENAME_PREFIX = 'animethemes-db-dump-auth-';
/**
* The list of tables to include in the dump.
*
* @return array
*/
protected function allowedTables(): array
{
@@ -14,12 +14,10 @@ class DumpDiscordAction extends DumpAction
{
use ReconcilesDumpRepositories;
final public const FILENAME_PREFIX = 'animethemes-db-dump-discord-';
final public const string FILENAME_PREFIX = 'animethemes-db-dump-discord-';
/**
* The list of tables to include in the dump.
*
* @return array
*/
protected function allowedTables(): array
{
@@ -14,12 +14,10 @@ class DumpDocumentAction extends DumpAction
{
use ReconcilesDumpRepositories;
final public const FILENAME_PREFIX = 'animethemes-db-dump-document-';
final public const string FILENAME_PREFIX = 'animethemes-db-dump-document-';
/**
* The list of tables to include in the dump.
*
* @return array
*/
protected function allowedTables(): array
{
@@ -17,12 +17,10 @@ class DumpListAction extends DumpAction
{
use ReconcilesDumpRepositories;
final public const FILENAME_PREFIX = 'animethemes-db-dump-list-';
final public const string FILENAME_PREFIX = 'animethemes-db-dump-list-';
/**
* The list of tables to include in the dump.
*
* @return array
*/
protected function allowedTables(): array
{
@@ -18,12 +18,10 @@ class DumpUserAction extends DumpAction
{
use ReconcilesDumpRepositories;
final public const FILENAME_PREFIX = 'animethemes-db-dump-user-';
final public const string FILENAME_PREFIX = 'animethemes-db-dump-user-';
/**
* The list of tables to include in the dump.
*
* @return array
*/
protected function allowedTables(): array
{
@@ -36,12 +36,10 @@ class DumpWikiAction extends DumpAction
{
use ReconcilesDumpRepositories;
final public const FILENAME_PREFIX = 'animethemes-db-dump-wiki-';
final public const string FILENAME_PREFIX = 'animethemes-db-dump-wiki-';
/**
* The list of tables to include in the dump.
*
* @return array
*/
protected function allowedTables(): array
{
+4 -4
View File
@@ -21,7 +21,7 @@ readonly class DeleteResults implements StorageResults
public function toLog(): void
{
if (empty($this->deletions)) {
if ($this->deletions === []) {
Log::error('No deletions were attempted.');
}
foreach ($this->deletions as $fs => $result) {
@@ -33,7 +33,7 @@ readonly class DeleteResults implements StorageResults
public function toConsole(Command $command): void
{
if (empty($this->deletions)) {
if ($this->deletions === []) {
$command->error('No deletions were attempted.');
}
foreach ($this->deletions as $fs => $result) {
@@ -45,7 +45,7 @@ readonly class DeleteResults implements StorageResults
public function toActionResult(): ActionResult
{
if (empty($this->deletions)) {
if ($this->deletions === []) {
return new ActionResult(
ActionStatus::FAILED,
'No deletions were attempted. Please check that disks are configured.'
@@ -54,7 +54,7 @@ readonly class DeleteResults implements StorageResults
/** @var Collection $passed */
/** @var Collection $failed */
[$passed, $failed] = collect($this->deletions)->partition(fn (bool $result, string $fs) => $result);
[$passed, $failed] = collect($this->deletions)->partition(fn (bool $result, string $fs): bool => $result);
if ($failed->isNotEmpty()) {
return new ActionResult(
+4 -4
View File
@@ -26,7 +26,7 @@ readonly class MoveResults implements StorageResults
public function toLog(): void
{
if (empty($this->moves)) {
if ($this->moves === []) {
Log::error('No moves were attempted.');
}
foreach ($this->moves as $fs => $result) {
@@ -38,7 +38,7 @@ readonly class MoveResults implements StorageResults
public function toConsole(Command $command): void
{
if (empty($this->moves)) {
if ($this->moves === []) {
$command->error('No moves were attempted.');
}
foreach ($this->moves as $fs => $result) {
@@ -50,7 +50,7 @@ readonly class MoveResults implements StorageResults
public function toActionResult(): ActionResult
{
if (empty($this->moves)) {
if ($this->moves === []) {
return new ActionResult(
ActionStatus::FAILED,
'No moves were attempted. Please check that disks are configured.'
@@ -59,7 +59,7 @@ readonly class MoveResults implements StorageResults
/** @var Collection $passed */
/** @var Collection $failed */
[$passed, $failed] = collect($this->moves)->partition(fn (bool $result, string $fs) => $result);
[$passed, $failed] = collect($this->moves)->partition(fn (bool $result, string $fs): bool => $result);
if ($failed->isNotEmpty()) {
return new ActionResult(
+4 -4
View File
@@ -20,7 +20,7 @@ readonly class PruneResults implements StorageResults
public function toLog(): void
{
if (empty($this->prunings)) {
if ($this->prunings === []) {
Log::error('No prunings were attempted.');
}
foreach ($this->prunings as $path => $result) {
@@ -32,7 +32,7 @@ readonly class PruneResults implements StorageResults
public function toConsole(Command $command): void
{
if (empty($this->prunings)) {
if ($this->prunings === []) {
$command->error('No prunings were attempted.');
}
foreach ($this->prunings as $path => $result) {
@@ -44,7 +44,7 @@ readonly class PruneResults implements StorageResults
public function toActionResult(): ActionResult
{
if (empty($this->prunings)) {
if ($this->prunings === []) {
return new ActionResult(
ActionStatus::FAILED,
'No prunings were attempted.'
@@ -53,7 +53,7 @@ readonly class PruneResults implements StorageResults
/** @var Collection $passed */
/** @var Collection $failed */
[$passed, $failed] = collect($this->prunings)->partition(fn (bool $result, string $path) => $result);
[$passed, $failed] = collect($this->prunings)->partition(fn (bool $result, string $path): bool => $result);
if ($failed->isNotEmpty()) {
return new ActionResult(
+4 -4
View File
@@ -20,7 +20,7 @@ readonly class UploadResults implements StorageResults
public function toLog(): void
{
if (empty($this->uploads)) {
if ($this->uploads === []) {
Log::error('No uploads were attempted.');
}
foreach ($this->uploads as $fs => $result) {
@@ -32,7 +32,7 @@ readonly class UploadResults implements StorageResults
public function toConsole(Command $command): void
{
if (empty($this->uploads)) {
if ($this->uploads === []) {
$command->error('No uploads were attempted.');
}
foreach ($this->uploads as $fs => $result) {
@@ -44,7 +44,7 @@ readonly class UploadResults implements StorageResults
public function toActionResult(): ActionResult
{
if (empty($this->uploads)) {
if ($this->uploads === []) {
return new ActionResult(
ActionStatus::FAILED,
'No uploads were attempted. Please check that disks are configured.'
@@ -53,7 +53,7 @@ readonly class UploadResults implements StorageResults
/** @var Collection $failed */
/** @var Collection $passed */
[$failed, $passed] = collect($this->uploads)->partition(fn (string|false $result, string $fs) => $result === false);
[$failed, $passed] = collect($this->uploads)->partition(fn (string|false $result, string $fs): bool => $result === false);
if ($failed->isNotEmpty()) {
return new ActionResult(
@@ -22,8 +22,6 @@ class MoveAudioAction extends MoveAction
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -43,18 +43,13 @@ class UploadAudioAction extends UploadAction
Audio::ATTRIBUTE_SIZE => $this->file->getSize(),
];
return Audio::updateOrCreate(
[
Audio::ATTRIBUTE_BASENAME => $this->file->getClientOriginalName(),
],
$attributes
);
return Audio::query()->updateOrCreate([
Audio::ATTRIBUTE_BASENAME => $this->file->getClientOriginalName(),
], $attributes);
}
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -22,8 +22,6 @@ class MoveImageAction extends MoveAction
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -13,15 +13,11 @@ class UploadedFileAction
{
/**
* The stream, chapter and format data as inspected by ffprobe.
*
* @var array
*/
public array $ffprobeData = [];
/**
* The loudness stats of the input file as parsed by the ffmpeg audio filter.
*
* @var array
*/
public array $loudnessStats = [];
@@ -44,8 +40,6 @@ class UploadedFileAction
/**
* Set the loudness stats for the uploaded file.
*
* @return array
*/
public function setLoudnessStats(): array
{
@@ -62,8 +56,6 @@ class UploadedFileAction
/**
* Get submission streams.
*
* @return array
*/
public function streams(): array
{
@@ -72,8 +64,6 @@ class UploadedFileAction
/**
* Get submission format.
*
* @return array
*/
public function format(): array
{
@@ -82,8 +72,6 @@ class UploadedFileAction
/**
* Get submission chapters.
*
* @return array
*/
public function chapters(): array
{
@@ -101,8 +89,6 @@ class UploadedFileAction
/**
* For WebMs, tags will be contained in the format object.
* For Audios, tags will be contained in the stream object.
*
* @return array
*/
public function tags(): array
{
@@ -115,7 +101,7 @@ class UploadedFileAction
$audio = Arr::first(
$this->streams(),
fn (array $stream) => Arr::get($stream, 'codec_type') === 'audio'
fn (array $stream): bool => Arr::get($stream, 'codec_type') === 'audio'
);
$tags = Arr::get($audio, 'tags', []);
@@ -125,8 +111,6 @@ class UploadedFileAction
/**
* Get the submission loudness stats.
*
* @return array
*/
public function loudness(): array
{
@@ -21,8 +21,6 @@ class DeleteVideoAction extends DeleteAction
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -22,8 +22,6 @@ class MoveVideoAction extends MoveAction
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -22,8 +22,6 @@ class DeleteScriptAction extends DeleteAction
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -22,8 +22,6 @@ class MoveScriptAction extends MoveAction
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -47,22 +47,17 @@ class UploadScriptAction extends UploadAction
VideoScript::ATTRIBUTE_PATH => $path,
];
if ($this->video !== null) {
if ($this->video instanceof Video) {
$attributes[VideoScript::ATTRIBUTE_VIDEO] = $this->video->getKey();
}
return VideoScript::updateOrCreate(
[
VideoScript::ATTRIBUTE_PATH => $path,
],
$attributes
);
return VideoScript::query()->updateOrCreate([
VideoScript::ATTRIBUTE_PATH => $path,
], $attributes);
}
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -29,9 +29,6 @@ use Illuminate\Support\Str;
class UploadVideoAction extends UploadAction
{
/**
* @param array $attributes
*/
public function __construct(
UploadedFile $file,
string $path,
@@ -116,12 +113,9 @@ class UploadVideoAction extends UploadAction
$attributes[Video::ATTRIBUTE_SOURCE] = $source instanceof BackedEnum ? $source->value : $source;
}
return Video::updateOrCreate(
[
Video::ATTRIBUTE_BASENAME => $this->file->getClientOriginalName(),
],
$attributes
);
return Video::query()->updateOrCreate([
Video::ATTRIBUTE_BASENAME => $this->file->getClientOriginalName(),
], $attributes);
}
/**
@@ -129,7 +123,7 @@ class UploadVideoAction extends UploadAction
*/
protected function attachEntry(Video $video): void
{
if ($this->entry !== null && $video->wasRecentlyCreated) {
if ($this->entry instanceof AnimeThemeEntry && $video->wasRecentlyCreated) {
$video->animethemeentries()->attach($this->entry);
}
}
@@ -139,7 +133,7 @@ class UploadVideoAction extends UploadAction
*/
protected function uploadScript(Video $video): void
{
if ($this->script !== null) {
if ($this->script instanceof UploadedFile) {
$uploadScript = new UploadScriptAction($this->script, $this->path, $video);
$scriptResult = $uploadScript->handle();
@@ -153,7 +147,7 @@ class UploadVideoAction extends UploadAction
*/
protected function addToPlaylist(Video $video): void
{
if ($encoder = $this->encoder) {
if (($encoder = $this->encoder) instanceof User) {
$playlist = Playlist::query()->firstOrCreate([
Playlist::ATTRIBUTE_NAME => 'Encodes',
Playlist::ATTRIBUTE_USER => $encoder->getKey(),
@@ -179,8 +173,6 @@ class UploadVideoAction extends UploadAction
/**
* The list of disk names.
*
* @return array
*/
public function disks(): array
{
@@ -57,15 +57,13 @@ trait ConstrainsEagerLoads
$relationType = $relation->getBaseType();
$eagerLoadRelations[$path] = function (RelationLaravel $relationLaravel) use ($relationSelection, $relationArgs, $relationType) {
$eagerLoadRelations[$path] = function (RelationLaravel $relationLaravel) use ($relationSelection, $relationArgs, $relationType): void {
if ($relationLaravel instanceof MorphTo) {
$this->processMorphToRelation($relationSelection, $relationType, $relationLaravel);
} elseif ($relationType instanceof BaseUnion) {
$this->processUnion($relationSelection, $relationLaravel, $relationType);
} else {
if ($relationType instanceof BaseUnion) {
$this->processUnion($relationSelection, $relationLaravel, $relationType);
} else {
$this->processGenericRelation($relationLaravel, $relationArgs, $relationSelection, $relationType);
}
$this->processGenericRelation($relationLaravel, $relationArgs, $relationSelection, $relationType);
}
};
}
@@ -87,7 +85,7 @@ trait ConstrainsEagerLoads
foreach ($types as $type) {
$typeSelection = Arr::get($unions, "{$type->getName()}.selectionSet");
$morphConstrains[$type->model()] = function (Builder $query) use ($typeSelection, $type) {
$morphConstrains[$type->model()] = function (Builder $query) use ($typeSelection, $type): void {
$this->processEagerLoadForType($query, $typeSelection, $type);
};
}
@@ -98,7 +96,7 @@ trait ConstrainsEagerLoads
/**
* Process a union relation by applying the eager loads for each type in the union.
*/
private function processUnion(array $selection, RelationLaravel $relation, BaseUnion $union)
private function processUnion(array $selection, RelationLaravel $relation, BaseUnion $union): void
{
$query = $relation->getQuery();
@@ -118,7 +116,7 @@ trait ConstrainsEagerLoads
/**
* Process a generic relation by applying filters, sorting and eager loads.
*/
private function processGenericRelation(RelationLaravel $relation, array $args, array $selection, BaseType $type)
private function processGenericRelation(RelationLaravel $relation, array $args, array $selection, BaseType $type): void
{
$query = $relation->getQuery();
@@ -18,9 +18,7 @@ trait PaginatesModels
$page = Arr::get($args, 'page');
$maxCount = Config::get('graphql.pagination_values.max_count');
if ($maxCount !== null && $first > $maxCount) {
throw new ClientValidationException("Maximum first value is {$maxCount}. Got {$first}. Fetch in smaller chuncks.");
}
throw_if($maxCount !== null && $first > $maxCount, new ClientValidationException("Maximum first value is {$maxCount}. Got {$first}. Fetch in smaller chuncks."));
return $builder->paginate($first, page: $page);
}
+5 -11
View File
@@ -60,12 +60,10 @@ trait SortsModels
$relation = Arr::get($resolver, SortableColumns::RESOLVER_RELATION);
if ($sortType === SortType::AGGREGATE) {
if ($relation === null) {
throw new InvalidArgumentException("The 'relation' argument is required for the {$column} column with aggregate sort type.");
}
throw_if($relation === null, new InvalidArgumentException("The 'relation' argument is required for the {$column} column with aggregate sort type."));
$builder->withAggregate([
"$relation as {$relation}_value" => function ($query) use ($direction) {
"$relation as {$relation}_value" => function ($query) use ($direction): void {
$query->orderBy('value', $direction);
},
], 'value');
@@ -74,12 +72,10 @@ trait SortsModels
}
if ($sortType === SortType::RELATION) {
if ($relation === null) {
throw new InvalidArgumentException("The 'relation' argument is required for the {$column} column with aggregate sort type.");
}
throw_if($relation === null, new InvalidArgumentException("The 'relation' argument is required for the {$column} column with aggregate sort type."));
$builder->withAggregate([
"$relation as {$relation}_$column" => function ($query) use ($column, $direction) {
"$relation as {$relation}_$column" => function ($query) use ($column, $direction): void {
$query->orderBy($column, $direction);
},
], $column);
@@ -88,9 +84,7 @@ trait SortsModels
}
if ($sortType === SortType::COUNT_RELATION) {
if ($relation === null) {
throw new InvalidArgumentException("The 'relation' argument is required for the {$column} column with relation sort type.");
}
throw_if($relation === null, new InvalidArgumentException("The 'relation' argument is required for the {$column} column with relation sort type."));
$builder->withCount($relation)->orderBy("{$relation}_count", $direction);
}
@@ -16,8 +16,8 @@ trait AggregatesFields
public function withAggregates(Builder $builder, Query $query, Schema $schema): Builder
{
collect($schema->fields())
->filter(fn (Field $field) => $field instanceof AggregateField && $field->shouldAggregate($query))
->each(fn (AggregateField $selectedAggregate) => $selectedAggregate->with($query, $builder));
->filter(fn (Field $field): bool => $field instanceof AggregateField && $field->shouldAggregate($query))
->each(fn (AggregateField $selectedAggregate): Builder => $selectedAggregate->with($query, $builder));
return $builder;
}
@@ -25,8 +25,8 @@ trait AggregatesFields
public function loadAggregates(Model $model, Query $query, Schema $schema): Model
{
collect($schema->fields())
->filter(fn (Field $field) => $field instanceof AggregateField && $field->shouldAggregate($query))
->each(fn (AggregateField $selectedAggregate) => $selectedAggregate->load($query, $model));
->filter(fn (Field $field): bool => $field instanceof AggregateField && $field->shouldAggregate($query))
->each(fn (AggregateField $selectedAggregate): Model => $selectedAggregate->load($query, $model));
return $model;
}
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Concerns\Actions\Http\Api;
use App\Http\Api\Criteria\Include\Criteria;
use App\Http\Api\Query\Query;
use App\Http\Api\Schema\Schema;
use App\Http\Api\Scope\ScopeParser;
@@ -19,26 +20,22 @@ trait ConstrainsEagerLoads
/**
* Constrain eager loads by binding callbacks that filter on the relations.
*
* @return array
*/
protected function constrainEagerLoads(Query $query, Schema $schema): array
{
$constrainedEagerLoads = [];
$includeCriteria = $query->getIncludeCriteria($schema->type());
if ($includeCriteria === null) {
if (! $includeCriteria instanceof Criteria) {
return $constrainedEagerLoads;
}
foreach ($includeCriteria->getPaths() as $allowedIncludePath) {
$relationSchema = $schema->relation($allowedIncludePath);
if ($relationSchema === null) {
throw new RuntimeException("Unknown relation '$allowedIncludePath' for type '{$schema->type()}'.");
}
throw_if(! $relationSchema instanceof Schema, new RuntimeException("Unknown relation '$allowedIncludePath' for type '{$schema->type()}'."));
$scope = ScopeParser::parse($allowedIncludePath);
$constrainedEagerLoads[$allowedIncludePath] = function (Relation $relation) use ($query, $scope, $relationSchema) {
$constrainedEagerLoads[$allowedIncludePath] = function (Relation $relation) use ($query, $scope, $relationSchema): void {
$relationBuilder = $relation->getQuery();
$this->select($relationBuilder, $query, $relationSchema);
@@ -15,8 +15,8 @@ trait SelectsFields
public function select(Builder $builder, Query $query, Schema $schema): Builder
{
$selectedFields = collect($schema->fields())
->filter(fn (Field $field) => $field instanceof SelectableField && $field->shouldSelect($query, $schema))
->map(fn (Field $field) => $field->getColumn());
->filter(fn (Field $field): bool => $field instanceof SelectableField && $field->shouldSelect($query, $schema))
->map(fn (Field $field): ?string => $field->getColumn());
$builder->select($builder->qualifyColumns($selectedFields->all()));
@@ -24,9 +24,6 @@ trait HasAttributeUpdateEmbedFields
$this->addEmbedFields($original, $model, $changedAttributes);
}
/**
* @return Collection
*/
protected function getChangedAttributes(Model $model): Collection
{
return collect($model->getChanges())
@@ -45,9 +42,6 @@ trait HasAttributeUpdateEmbedFields
return $model->getAttribute($attribute);
}
/**
* @param Collection $changedAttributes
*/
protected function addEmbedFields(Model $original, Model $changed, Collection $changedAttributes): void
{
foreach ($changedAttributes as $attribute) {
+3 -3
View File
@@ -34,13 +34,13 @@ trait CoercesInstances
$enum = Arr::first(
static::cases(),
fn (self $enum) => $enum->value === $enumNameOrValue
fn (self $enum): bool => $enum->value === $enumNameOrValue
);
if (is_string($enumNameOrValue) && $enum === null) {
$enum = Arr::first(
return Arr::first(
static::cases(),
fn (self $enum) => Str::lower($enum->name) === $enumNameOrValue
fn (self $enum): bool => Str::lower($enum->name) === $enumNameOrValue
);
}
+2 -4
View File
@@ -49,7 +49,7 @@ trait LocalizesName
protected function getLocalizationKey(): string
{
return Str::of('enums.')
->append(get_class($this))
->append($this::class)
->append('.')
->append($this->name)
->__toString();
@@ -57,8 +57,6 @@ trait LocalizesName
/**
* Get the enum as an array formatted for a select.
*
* @return array
*/
public static function asSelectArray(?string $locale = null): array
{
@@ -76,7 +74,7 @@ trait LocalizesName
{
return Arr::first(
static::cases(),
fn (self $enum) => Str::lower($enum->localize($locale)) === Str::lower($localizedName)
fn (self $enum): bool => Str::lower($enum->localize($locale)) === Str::lower($localizedName)
);
}
}
@@ -66,14 +66,11 @@ trait HasActionLogs
public function finishedLog(): void
{
if ($actionLog = $this->actionLog) {
if (! $this->isFailedLog()) {
$actionLog->finished();
// Filament notifications
if ($this instanceof Action) {
$this->success();
}
if (($actionLog = $this->actionLog) && ! $this->isFailedLog()) {
$actionLog->finished();
// Filament notifications
if ($this instanceof Action) {
$this->success();
}
}
}
@@ -9,9 +9,6 @@ use Illuminate\Database\Eloquent\Relations\MorphMany;
trait ModelHasActionLogs
{
/**
* @return MorphMany
*/
public function actionlogs(): MorphMany
{
return $this->morphMany(ActionLog::class, 'actionable');
@@ -10,8 +10,6 @@ trait HasColorOrEmoji
{
/**
* Get the enum as an array formatted for a select, but styled.
*
* @return array
*/
public static function asSelectArrayStyled(?bool $hasColor = true, ?bool $hasEmoji = true, ?string $locale = null): array
{
-1
View File
@@ -12,7 +12,6 @@ trait HasTabs
* Get the tabs for an array key-mapped.
*
* @param class-string<BaseTab>[] $tabClasses
* @return array
*/
public function toArray(array $tabClasses = []): array
{
+10 -10
View File
@@ -25,12 +25,12 @@ trait ResolvesArguments
public function args(): array
{
return collect($this->arguments())
->mapWithKeys(fn (Argument $argument) => [
->mapWithKeys(fn (Argument $argument): array => [
$argument->name => [
'name' => $argument->name,
'type' => $argument->getType(),
...(! is_null($argument->getDefaultValue()) ? ['defaultValue' => $argument->getDefaultValue()] : []),
...(is_null($argument->getDefaultValue()) ? [] : ['defaultValue' => $argument->getDefaultValue()]),
],
])
->toArray();
@@ -45,10 +45,10 @@ trait ResolvesArguments
protected function resolveFilterArguments(array $fields): array
{
return collect($fields)
->filter(fn (Field $field) => $field instanceof FilterableField)
->filter(fn (Field $field): bool => $field instanceof FilterableField)
->map(
fn (FilterableField $field) => collect($field->getFilters())
->map(fn (Filter $filter) => $filter->argument())
->map(fn (Filter $filter): Argument => $filter->argument())
->toArray()
)
->flatten()
@@ -64,9 +64,9 @@ trait ResolvesArguments
protected function resolveCreateMutationArguments(array $fields): array
{
return collect($fields)
->filter(fn (Field $field) => $field instanceof CreatableField)
->filter(fn (Field $field): bool => $field instanceof CreatableField)
->map(
fn (Field $field) => new Argument($field->getColumn(), $field->baseType())
fn (Field $field): Argument => new Argument($field->getColumn(), $field->baseType())
->required($field instanceof RequiredOnCreation)
)
->flatten()
@@ -82,9 +82,9 @@ trait ResolvesArguments
protected function resolveUpdateMutationArguments(array $fields): array
{
return collect($fields)
->filter(fn (Field $field) => $field instanceof UpdatableField)
->filter(fn (Field $field): bool => $field instanceof UpdatableField)
->map(
fn (Field $field) => new Argument($field->getColumn(), $field->baseType())
fn (Field $field): Argument => new Argument($field->getColumn(), $field->baseType())
->required($field instanceof RequiredOnUpdate)
)
->flatten()
@@ -98,8 +98,8 @@ trait ResolvesArguments
protected function resolveBindArguments(array $fields, bool $shouldRequire = true): array
{
return collect($fields)
->filter(fn (Field $field) => $field instanceof BindableField)
->map(fn (Field&BindableField $field) => new BindableArgument($field, $shouldRequire))
->filter(fn (Field $field): bool => $field instanceof BindableField)
->map(fn (Field&BindableField $field): BindableArgument => new BindableArgument($field, $shouldRequire))
->toArray();
}
}
@@ -23,7 +23,7 @@ trait ValidatesFields
{
return $this->restrictAllowedValues(
Str::of(FieldParser::param())->append('.')->append($schema->type())->__toString(),
Arr::map($schema->fields(), fn (FieldInterface $field) => $field->getKey())
Arr::map($schema->fields(), fn (FieldInterface $field): string => $field->getKey())
);
}
}
@@ -101,7 +101,7 @@ trait ValidatesFilters
$validator->sometimes(
$formattedParameter,
$filter->getRules(),
fn (Fluent $fluent) => Arr::has($fluent->toArray(), $formattedParameter) && ! Str::of(Arr::get($fluent->toArray(), $formattedParameter))->contains(Criteria::VALUE_SEPARATOR)
fn (Fluent $fluent): bool => Arr::has($fluent->toArray(), $formattedParameter) && ! Str::of(Arr::get($fluent->toArray(), $formattedParameter))->contains(Criteria::VALUE_SEPARATOR)
);
}
}
@@ -133,7 +133,7 @@ trait ValidatesFilters
$validator->sometimes(
$formattedParameter,
$multiValueRules,
fn (Fluent $fluent) => Arr::has($fluent->toArray(), $formattedParameter) && Str::of(Arr::get($fluent->toArray(), $formattedParameter))->contains(Criteria::VALUE_SEPARATOR)
fn (Fluent $fluent): bool => Arr::has($fluent->toArray(), $formattedParameter) && Str::of(Arr::get($fluent->toArray(), $formattedParameter))->contains(Criteria::VALUE_SEPARATOR)
);
}
}
@@ -152,7 +152,7 @@ trait ValidatesFilters
$validator->sometimes(
$formattedParameter,
['prohibited'],
fn (Fluent $fluent) => Arr::has($fluent->toArray(), $formattedParameter) && Str::of(Arr::get($fluent->toArray(), $formattedParameter))->contains(Criteria::VALUE_SEPARATOR)
fn (Fluent $fluent): bool => Arr::has($fluent->toArray(), $formattedParameter) && Str::of(Arr::get($fluent->toArray(), $formattedParameter))->contains(Criteria::VALUE_SEPARATOR)
);
}
}
@@ -21,7 +21,7 @@ trait ValidatesIncludes
{
return $this->restrictAllowedValues(
$param,
Arr::map($schema->allowedIncludes(), fn (AllowedInclude $include) => $include->path())
Arr::map($schema->allowedIncludes(), fn (AllowedInclude $include): string => $include->path())
);
}
}
@@ -37,7 +37,6 @@ trait ValidatesParameters
* Restrict the allowed values for the parameter.
*
* @param Arrayable<int, string>|array<int, string>|string $values
* @param array $customRules
* @return array<string, array>
*/
protected function restrictAllowedValues(string $param, Arrayable|array|string $values, array $customRules = []): array
@@ -73,7 +72,6 @@ trait ValidatesParameters
/**
* Optional parameter.
*
* @param array $customRules
* @return array<string, array>
*/
protected function optional(string $param, array $customRules = []): array
@@ -89,7 +87,6 @@ trait ValidatesParameters
/**
* Require the parameter.
*
* @param array $customRules
* @return array<string, array>
*/
protected function require(string $param, array $customRules = []): array
@@ -37,10 +37,8 @@ trait CanCreateExternalResource
$resource = ExternalResource::query()
->where(ExternalResource::ATTRIBUTE_SITE, $site->value)
->where(function (Builder $query) use ($url) {
return $query->where(ExternalResource::ATTRIBUTE_LINK, $url)
->orWhere(ExternalResource::ATTRIBUTE_LINK, $url.'/');
})
->where(fn (Builder $query) => $query->where(ExternalResource::ATTRIBUTE_LINK, $url)
->orWhere(ExternalResource::ATTRIBUTE_LINK, $url.'/'))
->first();
if ($resource === null) {
@@ -29,9 +29,6 @@ trait InteractsWithLikes
->delete();
}
/**
* @return MorphMany
*/
public function likes(): MorphMany
{
return $this->morphMany(Like::class, Like::RELATION_LIKEABLE);
-3
View File
@@ -9,9 +9,6 @@ use Illuminate\Database\Eloquent\Relations\MorphMany;
trait Reportable
{
/**
* @return MorphMany
*/
public function reportsteps(): MorphMany
{
return $this->morphMany(ReportStep::class, ReportStep::RELATION_ACTIONABLE);
-3
View File
@@ -45,9 +45,6 @@ trait SoftDeletes
return $result;
}
/**
* @return Builder
*/
public function prunable(): Builder
{
return static::onlyTrashed()->where(
@@ -13,17 +13,11 @@ use Illuminate\Support\Facades\App;
trait ReconcilesDumpRepositories
{
/**
* @param array $data
*/
protected function getSourceRepository(array $data = []): ?RepositoryInterface
{
return App::make(DumpSourceRepository::class);
}
/**
* @param array $data
*/
protected function getDestinationRepository(array $data = []): ?RepositoryInterface
{
return App::make(DumpDestinationRepository::class);
@@ -13,8 +13,6 @@ use Exception;
trait ReconcilesRepositories
{
/**
* @param array $data
*
* @throws Exception
*/
protected function reconcileRepositories(array $data = []): ActionResult
@@ -44,20 +42,12 @@ trait ReconcilesRepositories
abstract protected function reconcileAction(): ReconcileRepositoriesAction;
/**
* @param array $data
*/
abstract protected function getSourceRepository(array $data = []): ?RepositoryInterface;
/**
* @param array $data
*/
abstract protected function getDestinationRepository(array $data = []): ?RepositoryInterface;
/**
* Apply filters to repositories before reconciliation.
*
* @param array $data
*/
protected function handleFilters(
RepositoryInterface $sourceRepository,
@@ -13,17 +13,11 @@ use Illuminate\Support\Facades\App;
trait ReconcilesAudioRepositories
{
/**
* @param array $data
*/
protected function getSourceRepository(array $data = []): ?RepositoryInterface
{
return App::make(AudioSourceRepository::class);
}
/**
* @param array $data
*/
protected function getDestinationRepository(array $data = []): ?RepositoryInterface
{
return App::make(AudioDestinationRepository::class);
@@ -13,17 +13,11 @@ use Illuminate\Support\Facades\App;
trait ReconcilesVideoRepositories
{
/**
* @param array $data
*/
protected function getSourceRepository(array $data = []): ?RepositoryInterface
{
return App::make(VideoSourceRepository::class);
}
/**
* @param array $data
*/
protected function getDestinationRepository(array $data = []): ?RepositoryInterface
{
return App::make(VideoDestinationRepository::class);
@@ -13,17 +13,11 @@ use Illuminate\Support\Facades\App;
trait ReconcilesScriptRepositories
{
/**
* @param array $data
*/
protected function getSourceRepository(array $data = []): ?RepositoryInterface
{
return App::make(ScriptSourceRepository::class);
}
/**
* @param array $data
*/
protected function getDestinationRepository(array $data = []): ?RepositoryInterface
{
return App::make(ScriptDestinationRepository::class);
@@ -21,7 +21,7 @@ class PlaylistFixCommand extends BaseCommand
$playlistId = $this->argument('playlistId');
/** @var Playlist|null $playlist */
$playlist = Playlist::find($playlistId);
$playlist = Playlist::query()->find($playlistId);
if (! $playlist) {
$this->error("Playlist with id $playlistId not found.");
@@ -17,8 +17,6 @@ abstract class StorageReconcileCommand extends ReconcileCommand implements Inter
{
/**
* Apply filters to repositories before reconciliation.
*
* @param array $data
*/
protected function handleFilters(
RepositoryInterface $sourceRepository,
+2 -2
View File
@@ -6,7 +6,7 @@ namespace App\Constants\Config;
class ApiConstants
{
final public const PATH_QUALIFIED = 'api.path';
final public const string PATH_QUALIFIED = 'api.path';
final public const URL_QUALIFIED = 'api.url';
final public const string URL_QUALIFIED = 'api.url';
}
+6 -6
View File
@@ -6,15 +6,15 @@ namespace App\Constants\Config;
class AudioConstants
{
final public const DEFAULT_DISK_QUALIFIED = 'audio.default_disk';
final public const string DEFAULT_DISK_QUALIFIED = 'audio.default_disk';
final public const DISKS_QUALIFIED = 'audio.disks';
final public const string DISKS_QUALIFIED = 'audio.disks';
final public const NGINX_REDIRECT_QUALIFIED = 'audio.nginx_redirect';
final public const string NGINX_REDIRECT_QUALIFIED = 'audio.nginx_redirect';
final public const PATH_QUALIFIED = 'audio.path';
final public const string PATH_QUALIFIED = 'audio.path';
final public const STREAMING_METHOD_QUALIFIED = 'audio.streaming_method';
final public const string STREAMING_METHOD_QUALIFIED = 'audio.streaming_method';
final public const URL_QUALIFIED = 'audio.url';
final public const string URL_QUALIFIED = 'audio.url';
}
+3 -3
View File
@@ -6,9 +6,9 @@ namespace App\Constants\Config;
class DumpConstants
{
final public const DISK_QUALIFIED = 'dump.disk';
final public const string DISK_QUALIFIED = 'dump.disk';
final public const PATH_QUALIFIED = 'dump.path';
final public const string PATH_QUALIFIED = 'dump.path';
final public const URL_QUALIFIED = 'dump.url';
final public const string URL_QUALIFIED = 'dump.url';
}
@@ -6,5 +6,5 @@ namespace App\Constants\Config;
class ExternalProfileConstants
{
final public const MAX_PROFILES_QUALIFIED = 'externalprofile.user_max_profiles';
final public const string MAX_PROFILES_QUALIFIED = 'externalprofile.user_max_profiles';
}
+1 -1
View File
@@ -6,5 +6,5 @@ namespace App\Constants\Config;
class ImageConstants
{
final public const DISKS_QUALIFIED = 'image.disk';
final public const string DISKS_QUALIFIED = 'image.disk';
}
+2 -2
View File
@@ -6,7 +6,7 @@ namespace App\Constants\Config;
class PlaylistConstants
{
final public const MAX_PLAYLISTS_QUALIFIED = 'playlist.user_max_playlists';
final public const string MAX_PLAYLISTS_QUALIFIED = 'playlist.user_max_playlists';
final public const MAX_TRACKS_QUALIFIED = 'playlist.playlist_max_tracks';
final public const string MAX_TRACKS_QUALIFIED = 'playlist.playlist_max_tracks';
}
+1 -1
View File
@@ -6,5 +6,5 @@ namespace App\Constants\Config;
class ReportConstants
{
final public const MAX_REPORTS_QUALIFIED = 'report.user_max_reports';
final public const string MAX_REPORTS_QUALIFIED = 'report.user_max_reports';
}
+10 -10
View File
@@ -6,17 +6,17 @@ namespace App\Constants\Config;
class ServiceConstants
{
final public const ADMIN_DISCORD_CHANNEL_QUALIFIED = 'services.discord.admin_discord_channel';
final public const DB_UPDATES_DISCORD_CHANNEL_QUALIFIED = 'services.discord.db_updates_discord_channel';
final public const SUBMISSIONS_DISCORD_CHANNEL_QUALIFIED = 'services.discord.submissions_discord_channel';
final public const string ADMIN_DISCORD_CHANNEL_QUALIFIED = 'services.discord.admin_discord_channel';
final public const string DB_UPDATES_DISCORD_CHANNEL_QUALIFIED = 'services.discord.db_updates_discord_channel';
final public const string SUBMISSIONS_DISCORD_CHANNEL_QUALIFIED = 'services.discord.submissions_discord_channel';
final public const OPENAI_BEARER_TOKEN = 'services.openai.token';
final public const string OPENAI_BEARER_TOKEN = 'services.openai.token';
final public const ANILIST_CLIENT_ID = 'services.anilist.client_id';
final public const ANILIST_CLIENT_SECRET = 'services.anilist.client_secret';
final public const ANILIST_REDIRECT_URI = 'services.anilist.redirect_uri';
final public const string ANILIST_CLIENT_ID = 'services.anilist.client_id';
final public const string ANILIST_CLIENT_SECRET = 'services.anilist.client_secret';
final public const string ANILIST_REDIRECT_URI = 'services.anilist.redirect_uri';
final public const MAL_CLIENT_ID = 'services.mal.client_id';
final public const MAL_CLIENT_SECRET = 'services.mal.client_secret';
final public const MAL_REDIRECT_URI = 'services.mal.redirect_uri';
final public const string MAL_CLIENT_ID = 'services.mal.client_id';
final public const string MAL_CLIENT_SECRET = 'services.mal.client_secret';
final public const string MAL_REDIRECT_URI = 'services.mal.redirect_uri';
}
+1 -1
View File
@@ -6,5 +6,5 @@ namespace App\Constants\Config;
class ValidationConstants
{
final public const MODERATION_SERVICE_QUALIFIED = 'validation.moderation_service';
final public const string MODERATION_SERVICE_QUALIFIED = 'validation.moderation_service';
}

Some files were not shown because too many files have changed in this diff Show More