Repository navigation
Expand file tree
/
Copy pathCreatePostMutation.php
More file actions
69 lines (57 loc) · 1.88 KB
/
Copy pathCreatePostMutation.php
File metadata and controls
69 lines (57 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
declare(strict_types=1);
namespace App\GraphQL\Mutations;
use App\Enums\PostStatus;
use App\Models\Post;
use Ayimdomnic\Laragraph\Facades\Laragraph;
use Ayimdomnic\Laragraph\Support\Mutation;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Illuminate\Support\Facades\Gate;
/**
* `createPost(input: PostInput!)` — an input type, dot-notation validation
* rules, a policy check, and a queued subscription broadcast.
*/
class CreatePostMutation extends Mutation
{
public function type(): Type
{
return Type::nonNull(Laragraph::type('Post'));
}
public function args(): array
{
return ['input' => ['type' => Type::nonNull(Laragraph::type('PostInput'))]];
}
public function authorize(mixed $root, array $args, mixed $context, ResolveInfo $info): bool
{
return Gate::allows('create', Post::class);
}
public function rules(array $args = []): array
{
return [
'input.title' => ['required', 'string', 'min:3', 'max:200'],
'input.body' => ['required', 'string', 'min:10'],
];
}
public function attributes(): array
{
return ['input.title' => 'title', 'input.body' => 'body'];
}
public function resolve(mixed $root, array $args, mixed $context, ResolveInfo $info): mixed
{
$user = $context->user();
$publish = (bool) $args['input']['publish'];
$post = Post::create([
'title' => $args['input']['title'],
'body' => $args['input']['body'],
'status' => $publish ? PostStatus::Published : PostStatus::Draft,
'published_at' => $publish ? now() : null,
'user_id' => $user->id,
'organization_id' => $user->organization_id,
]);
if ($publish) {
PublishPostMutation::notifySubscribers($post);
}
return $post;
}
}