-
Notifications
You must be signed in to change notification settings - Fork 0
/
Model.php
80 lines (58 loc) · 1.6 KB
/
Model.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
<?php
namespace Expresser\Support;
abstract class Model extends Fluent
{
public $exists = false;
protected $original = [];
public function __construct($attributes = [])
{
$attributes = static::prepareAttributes($attributes);
parent::__construct($attributes);
$this->syncOriginal();
}
public function syncOriginal()
{
$this->original = $this->attributes;
return $this;
}
public static function hydrate(array $items)
{
$instance = (new static);
return $instance->newCollection(array_map(function ($item) use ($instance) {
return $instance->newFromBuilder($item);
}, $items));
}
public function newFromBuilder($attributes = [])
{
$model = $this->newInstance($attributes, true);
return $model;
}
public function newInstance($attributes = [], $exists = false)
{
$model = new static($attributes);
$model->exists = $exists;
return $model;
}
public function getDirty()
{
$dirty = [];
foreach ($this->attributes as $key => $value) {
if (!array_key_exists($key, $this->original) || $value !== $this->original[$key]) {
$dirty[$key] = $value;
}
}
return $dirty;
}
public static function query()
{
return (new static())->newQuery();
}
protected static function prepareAttributes($value)
{
if (!is_array($value)) {
$value = json_decode(json_encode($value), true);
}
return $value;
}
abstract public function newQuery();
}