-
-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathNestedOneToOne.php
More file actions
56 lines (43 loc) · 1.82 KB
/
NestedOneToOne.php
File metadata and controls
56 lines (43 loc) · 1.82 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
<?php declare(strict_types=1);
namespace Nuwave\Lighthouse\Execution\Arguments;
use GraphQL\Error\Error;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Nuwave\Lighthouse\Support\Contracts\ArgResolver;
class NestedOneToOne implements ArgResolver
{
public function __construct(
protected string $relationName,
) {}
/**
* @param \Illuminate\Database\Eloquent\Model $model
* @param ArgumentSet $args
*/
public function __invoke($model, $args): void
{
$relation = $model->{$this->relationName}();
assert($relation instanceof HasOne || $relation instanceof MorphOne);
if ($args->has('create')) {
if ($relation->exists()) {
$relatedClass = class_basename($relation->getRelated());
$parentClass = class_basename($model);
throw new Error("Cannot create a related model: a {$relatedClass} already exists for this {$parentClass}. Use upsert to modify the existing model.");
}
$saveModel = new ResolveNested(new SaveModel($relation));
$saveModel($relation->make(), $args->arguments['create']->value);
}
if ($args->has('update')) {
$updateModel = new ResolveNested(new UpdateModel(new SaveModel($relation)));
$updateModel($relation->make(), $args->arguments['update']->value);
}
if ($args->has('upsert')) {
$upsertModel = new ResolveNested(new UpsertModel(new SaveModel($relation)));
$upsertModel($relation->first() ?? $relation->make(), $args->arguments['upsert']->value);
}
if ($args->has('delete')) {
$relation->getRelated()::destroy(
$args->arguments['delete']->toPlain(),
);
}
}
}