1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ag84ark\ObjectConvertor; |
4
|
|
|
|
5
|
|
|
use ArrayAccess; |
6
|
|
|
use Illuminate\Contracts\Support\Arrayable; |
7
|
|
|
use Illuminate\Contracts\Support\Jsonable; |
8
|
|
|
use JsonSerializable; |
9
|
|
|
|
10
|
|
|
abstract class BaseModelApi implements ArrayAccess, Arrayable, Jsonable, JsonSerializable |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @param bool $withNull Return null values or not |
14
|
|
|
*/ |
15
|
14 |
|
public function toArray(bool $withNull = true): array |
16
|
|
|
{ |
17
|
14 |
|
return ObjectConvertor::toArray($this, $withNull); |
18
|
|
|
} |
19
|
|
|
|
20
|
6 |
|
public function toJson($options = 0): string |
21
|
|
|
{ |
22
|
6 |
|
return json_encode($this->jsonSerialize(), $options); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Convert the object into something JSON serializable. |
27
|
|
|
*/ |
28
|
6 |
|
public function jsonSerialize(): array |
29
|
|
|
{ |
30
|
6 |
|
return $this->toArray(); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Convert the model to its string representation. |
35
|
|
|
* |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
2 |
|
public function __toString() |
39
|
|
|
{ |
40
|
2 |
|
return $this->toJson(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @return static |
45
|
|
|
*/ |
46
|
6 |
|
public static function fromArray(array $arrayData) |
47
|
|
|
{ |
48
|
6 |
|
return ObjectConvertor::toObjectBaseModelApi($arrayData, new static()); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Determine if the given attribute exists. |
53
|
|
|
* |
54
|
|
|
* @param mixed $offset |
55
|
|
|
*/ |
56
|
|
|
public function offsetExists($offset): bool |
57
|
|
|
{ |
58
|
|
|
return ! is_null($this->$offset); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Get the value for a given offset. |
63
|
|
|
* |
64
|
|
|
* @param mixed $offset |
65
|
|
|
* |
66
|
|
|
* @return mixed |
67
|
|
|
*/ |
68
|
|
|
public function offsetGet($offset) |
69
|
|
|
{ |
70
|
|
|
return $this->$offset ?? null; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Set the value for a given offset. |
75
|
|
|
* |
76
|
|
|
* @param mixed $offset |
77
|
|
|
* @param mixed $value |
78
|
|
|
*/ |
79
|
|
|
public function offsetSet($offset, $value): void |
80
|
|
|
{ |
81
|
|
|
if (! is_null($offset) && $this->offsetExists($offset)) { |
82
|
|
|
$this->$offset = $value; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Unset the value for a given offset. |
88
|
|
|
* |
89
|
|
|
* @param mixed $offset |
90
|
|
|
*/ |
91
|
|
|
public function offsetUnset($offset): void |
92
|
|
|
{ |
93
|
|
|
unset($this->$offset); |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|