/
Entity.php
131 lines (117 loc) · 2.79 KB
/
Entity.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<?php
namespace Hussainweb\DrupalApi\Entity;
use Psr\Http\Message\ResponseInterface;
abstract class Entity
{
/**
* @var mixed
*/
protected $data;
/**
* @param mixed $rawData
*/
final public function __construct(protected $rawData)
{
}
/**
* Get the original raw data.
*
* @return mixed
*/
public function getRawData()
{
return $this->rawData;
}
/**
* Get the response entity data.
*
* @return mixed
*/
public function getData()
{
if (!$this->data) {
// Convert the appropriate fields to integer.
$this->data = (object) $this->rawData;
$int_fields = $this->getIntegerFields();
foreach ($int_fields as $field) {
$this->data->$field = (int) $this->data->$field;
}
}
return $this->data;
}
/**
* Get the specified property from the data.
*
* @param string $name
* Property name
*
* @return mixed
* Value for the property name.
*/
public function __get($name)
{
return $this->rawData->$name ?? null;
}
/**
* Set the value to a specified property.
*
* @param string $name
* Property name
* @param mixed $value
* Value
*/
public function __set($name, mixed $value): void
{
$this->rawData->$name = $value;
}
/**
* Check if the property is set.
*
* @param string $name
* Property name
*
* @return bool
* True if the property exists.
*/
public function __isset($name): bool
{
return isset($this->rawData->$name);
}
/**
* Retrieve the name of the field which holds the id of the entity.
*
* @return string
* The name of the field which holds the id of the entity.
*/
abstract public function getIdField(): string;
/**
* Get the Id of the entity.
*
* @return mixed
*/
public function getId()
{
$id_field = $this->getIdField();
return $this->getData()->$id_field;
}
/**
* Retrieve the names of fields which are supposed to be integers.
*
* @return string[]
* Array of field names which are supposed to be integers.
*/
abstract protected function getIntegerFields(): array;
/**
* Construct the object from a HTTP Response.
*
* @param \Psr\Http\Message\ResponseInterface $response
* Response object to parse.
*
* @return static
* The EntityCollection object for the response.
*/
public static function fromResponse(ResponseInterface $response): self
{
return new static(json_decode((string) $response->getBody(), null, 512, JSON_THROW_ON_ERROR));
}
}