1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Lifeboat\Models; |
4
|
|
|
|
5
|
|
|
use Lifeboat\Connector; |
6
|
|
|
use Lifeboat\Exceptions\InvalidArgumentException; |
7
|
|
|
use Lifeboat\Resource\ObjectResource; |
8
|
|
|
use Lifeboat\Factory\ObjectFactory; |
9
|
|
|
use Lifeboat\Utils\ArrayLib; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class Model |
13
|
|
|
* @package Lifeboat\Models |
14
|
|
|
* |
15
|
|
|
* @property int $ID |
16
|
|
|
*/ |
17
|
|
|
abstract class Model extends ObjectResource { |
18
|
|
|
|
19
|
|
|
abstract public function model(): string; |
20
|
|
|
|
21
|
|
|
public function __construct(Connector $client, array $_object_data = []) |
22
|
|
|
{ |
23
|
|
|
if (!ArrayLib::is_associative($_object_data)) { |
24
|
|
|
throw new InvalidArgumentException("Model::__construct() expects an associative array"); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
parent::__construct($client, $_object_data); |
28
|
|
|
|
29
|
|
|
$model = $this->model(); |
|
|
|
|
30
|
|
|
|
31
|
|
|
// Mutate objects if needs be |
32
|
|
|
foreach ($this->toArray() as $field => $value) { |
33
|
|
|
if (is_array($value)) { |
34
|
|
|
if (ArrayLib::is_associative($value)) { |
35
|
|
|
// Model or Object |
36
|
|
|
if (!array_key_exists('field_name', $value)) { |
37
|
|
|
$this->$field = ObjectFactory::make($client, $value); |
38
|
|
|
} else { |
39
|
|
|
// Has One Relation - Deprecated |
40
|
|
|
$name = $value['field_name']; |
41
|
|
|
$this->$name = $value['field_value']; |
42
|
|
|
$this->$field = ObjectFactory::make($client, $value['object_data']); |
43
|
|
|
} |
44
|
|
|
} else { |
45
|
|
|
// HasMany / ManyMany Relation |
46
|
|
|
$list = []; |
47
|
|
|
foreach ($value as $item) { |
48
|
|
|
if (ArrayLib::is_associative($item)) { |
49
|
|
|
$list[] = ObjectFactory::make($client, $item); |
50
|
|
|
} else { |
51
|
|
|
$list[] = $item; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$this->$field = $list; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return array |
63
|
|
|
*/ |
64
|
|
|
public function toArray(): array |
65
|
|
|
{ |
66
|
|
|
return iterator_to_array($this->getIterator()); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return bool |
71
|
|
|
*/ |
72
|
|
|
public function exists(): bool |
73
|
|
|
{ |
74
|
|
|
return $this->ID > 0; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @return Model|null |
79
|
|
|
*/ |
80
|
|
|
protected function save(): ?Model |
81
|
|
|
{ |
82
|
|
|
if ($this->exists()) { |
83
|
|
|
return $this->getService()->update($this->ID, $this->toArray()); |
84
|
|
|
} else { |
85
|
|
|
return $this->getService()->create($this->toArray()); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|