Files
animethemes-server/app/GraphQL/Schema/Mutations/Models/UpdateMutation.php
T
2026-03-09 10:41:34 -03:00

91 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\GraphQL\Schema\Mutations\Models;
use App\Contracts\GraphQL\Fields\UpdatableField;
use App\GraphQL\Argument\Argument;
use App\GraphQL\Schema\Fields\Field;
use App\GraphQL\Schema\Mutations\BaseMutation;
use App\GraphQL\Schema\Types\BaseType;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
use Rebing\GraphQL\Support\Facades\GraphQL;
abstract class UpdateMutation extends BaseMutation
{
/**
* @param class-string<Model> $model
*/
public function __construct(protected string $model)
{
parent::__construct();
}
public function name(): string
{
return 'Update'.Str::pascal(class_basename($this->model));
}
public function authorize($root, array $args, $ctx, ?ResolveInfo $resolveInfo = null, ?Closure $getSelectFields = null): bool
{
$model = Arr::pull($args, 'model');
$args = collect($args)
->filter(fn ($value): bool => $value instanceof Model)
->prepend($model)
->values()
->all();
return ($this->response = Gate::inspect('update', $args))->allowed();
}
/**
* Get the arguments for the create mutation.
*
* @return Argument[]
*/
public function arguments(): array
{
$arguments = [];
$baseType = $this->baseType();
if ($baseType instanceof BaseType) {
$arguments[] = $this->resolveBindArguments($baseType->fieldClasses());
$arguments[] = $this->resolveUpdateMutationArguments($baseType->fieldClasses());
}
return Arr::flatten($arguments);
}
/**
* @param array<string, mixed> $args
* @return array<string, array>
*/
public function rulesForValidation(array $args = []): array
{
$baseType = $this->baseType();
if ($baseType instanceof BaseType) {
return collect($baseType->fieldClasses())
->filter(fn (Field $field): bool => $field instanceof UpdatableField)
->mapWithKeys(fn (Field&UpdatableField $field): array => [$field->name() => $field->getUpdateRules($args)])
->all();
}
return [];
}
public function type(): Type
{
return Type::nonNull(GraphQL::type($this->baseType()->name()));
}
}