-
-
Notifications
You must be signed in to change notification settings - Fork 470
Expand file tree
/
Copy pathNestedBelongsTo.php
More file actions
77 lines (67 loc) · 2.65 KB
/
NestedBelongsTo.php
File metadata and controls
77 lines (67 loc) · 2.65 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
70
71
72
73
74
75
76
77
<?php declare(strict_types=1);
namespace Nuwave\Lighthouse\Execution\Arguments;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Nuwave\Lighthouse\Support\Contracts\ArgResolver;
class NestedBelongsTo implements ArgResolver
{
public function __construct(
/** @var \Illuminate\Database\Eloquent\Relations\BelongsTo<\Illuminate\Database\Eloquent\Model, \Illuminate\Database\Eloquent\Model> $relation */
protected BelongsTo $relation,
) {}
/**
* @param \Illuminate\Database\Eloquent\Model $model
* @param ArgumentSet $args
*/
public function __invoke($model, $args): void
{
if ($args->has('create')) {
$saveModel = new ResolveNested(new SaveModel());
$related = $saveModel(
$this->relation->make(),
$args->arguments['create']->value,
);
$this->relation->associate($related);
}
if ($args->has('connect')) {
$this->relation->associate($args->arguments['connect']->value);
}
if ($args->has('update')) {
$updateModel = new ResolveNested(new UpdateModel(new SaveModel()));
$related = $updateModel(
$this->relation->make(),
$args->arguments['update']->value,
);
$this->relation->associate($related);
}
if ($args->has('upsert')) {
$upsertModel = new ResolveNested(new UpsertModel(new SaveModel()));
$related = $upsertModel(
$this->relation->make(),
$args->arguments['upsert']->value,
);
$this->relation->associate($related);
}
self::disconnectOrDelete($this->relation, $args);
}
/** @param \Illuminate\Database\Eloquent\Relations\BelongsTo<\Illuminate\Database\Eloquent\Model, \Illuminate\Database\Eloquent\Model> $relation */
public static function disconnectOrDelete(BelongsTo $relation, ArgumentSet $args): void
{
// We proceed with disconnecting/deleting only if the given $values is truthy.
// There is no other information to be passed when issuing those operations,
// but GraphQL forces us to pass some value. It would be unintuitive for
// the end user if the given value had no effect on the execution.
if (
$args->has('disconnect')
&& $args->arguments['disconnect']->value
) {
$relation->dissociate();
}
if (
$args->has('delete')
&& $args->arguments['delete']->value
) {
$relation->dissociate();
$relation->first()?->delete();
}
}
}