-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClearsJob.php
81 lines (74 loc) · 2.64 KB
/
ClearsJob.php
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
78
79
80
81
<?php
namespace BiiiiiigMonster\Clearable\Jobs;
use BiiiiiigMonster\Clearable\Contracts\InvokableClear;
use BiiiiiigMonster\Clearable\Exceptions\NotAllowedClearsException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use LogicException;
class ClearsJob implements ShouldQueue
{
use Dispatchable;
use Queueable;
use SerializesModels;
use InteractsWithQueue;
/**
* ClearJob constructor.
*
* @param string $className
* @param array $original
* @param string $relationName
* @param string|null $invokableClearClassName
*/
public function __construct(
protected string $className,
protected array $original,
protected string $relationName,
protected ?string $invokableClearClassName = null,
) {
}
/**
* ClearJob handle.
*
* @throws NotAllowedClearsException
*/
public function handle(): void
{
$model = (new $this->className())->setRawAttributes($this->original);
$relation = $model->{$this->relationName}();
// to be cleared model.
$clears = Collection::wrap($model->{$this->relationName});
if (is_a($this->invokableClearClassName, InvokableClear::class, true)) {
$invoke = new $this->invokableClearClassName();
$clears = $clears->filter(fn (Model $clear) => $invoke($clear));
}
switch (true) {
case $relation instanceof HasOneOrMany:
$clears->map(fn (Model $clear) => $clear->delete());
break;
case $relation instanceof BelongsToMany:
$relation->detach($clears->pluck($relation->getRelatedKeyName())->all());
break;
case $relation instanceof BelongsTo:
throw new NotAllowedClearsException(sprintf(
'%s::%s is relationship of %s, it not allowed to be cleared.',
$this->className,
$this->relationName,
$relation::class
));
default:
throw new LogicException(sprintf(
'%s::%s must return a relationship instance.',
$this->className,
$this->relationName
));
}
}
}