1 | <?php |
||
15 | abstract class Model implements Common |
||
16 | { |
||
17 | const MESSAGE_ID_REQUIRED = 'Id is required'; |
||
18 | const MESSAGE_ID_CAN_NOT_CHANGED = 'Id can not be changed'; |
||
19 | |||
20 | private $client; |
||
21 | |||
22 | private $fields = []; |
||
23 | |||
24 | private $data = null; |
||
25 | |||
26 | private $id = null; |
||
27 | |||
28 | private $lastStatus = 0; |
||
29 | |||
30 | /** |
||
31 | * Model constructor. |
||
32 | * |
||
33 | * @param Client $client |
||
34 | * @param $fields |
||
35 | * @throws Exception |
||
36 | */ |
||
37 | 6 | public function __construct(Client $client, array $fields) |
|
50 | |||
51 | 2 | public function get($id = null) |
|
52 | { |
||
53 | 2 | if ($id === null && $this->id !== null) { |
|
54 | return $this->data; |
||
55 | } |
||
56 | |||
57 | 2 | $this->set(['id' => $id]); |
|
58 | |||
59 | $response = $this->client->getResponse($this->getUrl(__FUNCTION__, [$this->getId()]), $this->getFields()); |
||
60 | |||
61 | $this->set($response['data'], $response['status']); |
||
62 | |||
63 | return $this->data; |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * Set data to model |
||
68 | * |
||
69 | * @param array $data |
||
70 | * @param null $status |
||
71 | * @return $this |
||
72 | * @throws Exception |
||
73 | */ |
||
74 | 5 | public function set(array $data, $status = null) |
|
75 | { |
||
76 | 5 | if (empty($data['id']) && empty($this->id)) { |
|
77 | 4 | throw new Exception(Model::MESSAGE_ID_REQUIRED); |
|
78 | } |
||
79 | |||
80 | 1 | if (!empty($data['id']) && !empty($this->id) && $data['id'] != $this->id) { |
|
81 | throw new Exception(Model::MESSAGE_ID_CAN_NOT_CHANGED); |
||
82 | } |
||
83 | |||
84 | 1 | $this->data = array_merge( |
|
85 | 1 | (array)$this->data, |
|
86 | 1 | array_intersect_key($data, array_flip(array_merge($this->getFields(), ['id']))) |
|
87 | ); |
||
88 | |||
89 | 1 | $this->id = $this->data['id']; |
|
90 | |||
91 | 1 | if ($status) { |
|
92 | $this->lastStatus = $status; |
||
93 | } |
||
94 | |||
95 | 1 | return $this; |
|
96 | } |
||
97 | |||
98 | 1 | public function getFields() |
|
104 | |||
105 | 1 | public function getId() |
|
109 | |||
110 | 1 | public function post(array $data) |
|
111 | { |
||
118 | |||
119 | public function put(array $data) |
||
129 | |||
130 | public function delete($id = null) |
||
142 | |||
143 | public function __get($name) |
||
151 | } |