1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace MichaelRubel\LoopFunctions\Traits; |
6
|
|
|
|
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
|
9
|
|
|
trait LoopFunctions |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Maps your model attributes to local class properties. |
13
|
|
|
* |
14
|
|
|
* @param Model|null $model |
15
|
|
|
* @param mixed $rescue |
16
|
|
|
* |
17
|
|
|
* @return void |
18
|
|
|
*/ |
19
|
8 |
|
public function attributesToProperties(?Model $model = null, mixed $rescue = null): void |
20
|
|
|
{ |
21
|
8 |
|
if (! is_null($model)) { |
22
|
8 |
|
collect($model->getAttributes()) |
|
|
|
|
23
|
8 |
|
->except($this->ignoreKeys()) |
24
|
8 |
|
->each(function ($value, $property) use ($model, $rescue) { |
25
|
8 |
|
if (property_exists($this, $property)) { |
26
|
8 |
|
rescue( |
27
|
8 |
|
fn () => $this->{$property} = $model->{$property}, |
28
|
|
|
$rescue, |
29
|
8 |
|
config('loop-functions.log') ?? false |
30
|
|
|
); |
31
|
|
|
} |
32
|
8 |
|
}); |
33
|
|
|
} |
34
|
8 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Map array data to class properties. |
38
|
|
|
* |
39
|
|
|
* @param array|null $data |
40
|
|
|
* @param mixed|null $rescue |
41
|
|
|
* |
42
|
|
|
* @return void |
43
|
|
|
*/ |
44
|
2 |
|
public function arrayToProperties(?array $data, mixed $rescue = null): void |
45
|
|
|
{ |
46
|
2 |
|
collect($data ?? []) |
|
|
|
|
47
|
2 |
|
->except($this->ignoreKeys()) |
48
|
2 |
|
->each( |
49
|
2 |
|
fn ($value, $key) => is_array($value) |
50
|
1 |
|
? $this->arrayToProperties($value, $rescue) |
51
|
2 |
|
: $this->assignValue($key, $value, $rescue) |
52
|
2 |
|
); |
53
|
2 |
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Assign the value to the property or rescue. |
57
|
|
|
* |
58
|
|
|
* @param string $key |
59
|
|
|
* @param mixed $value |
60
|
|
|
* @param mixed|null $rescue |
61
|
|
|
* |
62
|
|
|
* @return void |
63
|
|
|
*/ |
64
|
2 |
|
private function assignValue(string $key, mixed $value, mixed $rescue = null): void |
65
|
|
|
{ |
66
|
2 |
|
if (property_exists($this, $key)) { |
67
|
2 |
|
rescue( |
68
|
2 |
|
fn () => $this->{$key} = $value, |
69
|
|
|
$rescue, |
70
|
2 |
|
config('loop-functions.log') ?? false |
71
|
|
|
); |
72
|
|
|
} |
73
|
2 |
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @return array |
77
|
|
|
*/ |
78
|
10 |
|
private function ignoreKeys(): array |
79
|
|
|
{ |
80
|
10 |
|
$defaults = ['id', 'password']; |
81
|
|
|
|
82
|
10 |
|
$ignores = config('loop-functions.ignore_keys', $defaults); |
83
|
|
|
|
84
|
10 |
|
return is_array($ignores) |
85
|
10 |
|
? $ignores |
86
|
10 |
|
: $defaults; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|