-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathEntity.php
More file actions
81 lines (75 loc) · 2.04 KB
/
Entity.php
File metadata and controls
81 lines (75 loc) · 2.04 KB
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
<?php
namespace Viber\Api;
use Viber\Api\Exception\ApiException;
/**
* Api entity interface
*
* @author Novikov Bogdan <hcbogdan@gmail.com>
*/
class Entity
{
/**
* Map api-response keys to class setters
*
* @var array
*/
protected $propertiesMap = [];
/**
* Make new instance from api response array
*
* @param mixed $properties list of properties
* @throws \Viber\Api\Exception\ApiException
*/
public function __construct($properties = null)
{
if (null === $properties) {
return;
}
if (!is_array($properties) && !$properties instanceof \ArrayAccess) {
throw new ApiException('Properties must be an array or implement ArrayAccess');
}
if (empty($this->propertiesMap)) { // no property map
foreach ($properties as $propName => $propValue) {
if (property_exists(get_class($this), $propName)) {
$this->$propName = $propValue;
}
}
} else { // call setters
foreach ($properties as $propName => $propValue) {
if (isset($this->propertiesMap[$propName])) {
$setterName = $this->propertiesMap[$propName];
$this->$setterName($propValue);
} else {
if (property_exists(get_class($this), $propName)) {
$this->$propName = $propValue;
}
}
}
}
/**
* Build array single-level array
*
* @return array
*/
public function toArray()
{
return [];
}
/**
* Build multi-level array for api call`s, filter or upgrade properties
*
* @return array
*/
public function toApiArray()
{
$entity = $this->toArray();
foreach ($entity as $name => &$value) {
if (null === $value) {
unset($entity[$name]);
} elseif ($value instanceof Entity) {
$value = $value->toArray();
}
}
return $entity;
}
}