-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClearManager.php
89 lines (76 loc) · 2.21 KB
/
ClearManager.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
82
83
84
85
86
87
88
89
<?php
namespace BiiiiiigMonster\Clearable;
use BiiiiiigMonster\Clearable\Attributes\Clear;
use BiiiiiigMonster\Clearable\Jobs\ClearsJob;
use Illuminate\Database\Eloquent\Model;
use ReflectionClass;
use ReflectionMethod;
class ClearManager
{
/**
* ClearManager constructor.
*
* @param Model $model
*/
public function __construct(
protected Model $model
) {
}
/**
* Make instance.
*
* @param Model $model
* @return static
*/
public static function make(Model $model): static
{
return new static($model);
}
/**
* ClearManager handle.
*/
public function handle(): void
{
$clears = $this->parse();
foreach ($clears as $relationName => $clear) {
$payload = [
$this->model::class,
$this->model->getOriginal(),
$relationName,
$clear->invokableClearClassName
];
match ($clear->clearQueue) {
null,false => ClearsJob::dispatchSync(...$payload),
true,'' => ClearsJob::dispatch(...$payload),
default => ClearsJob::dispatch(...$payload)->onQueue($clear->clearQueue)
};
}
}
/**
* Parse clears of the model.
*
* @return array<string, Clear>
*/
protected function parse(): array
{
$clears = [];
// from clears array
foreach ($this->model->getClears() as $relationName => $invokableClearClassName) {
if (is_numeric($relationName)) {
$relationName = $invokableClearClassName;
$invokableClearClassName = null;
}
$clears[$relationName] = new Clear($invokableClearClassName, $this->model->getClearQueue());
}
// from clear attribute
$rfc = new ReflectionClass($this->model);
$methods = $rfc->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
if (empty($clearAttributes = $method->getAttributes(Clear::class))) {
continue;
}
$clears[$method->getName()] = $clearAttributes[0]->newInstance();
}
return $clears;
}
}