forked from TelegramBot/Api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseType.php
More file actions
99 lines (86 loc) · 2.39 KB
/
BaseType.php
File metadata and controls
99 lines (86 loc) · 2.39 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace TelegramBot\Api;
/**
* Class BaseType
* Base class for Telegram Types
*
* @package TelegramBot\Api
*/
abstract class BaseType
{
/**
* Array of required data params for type
*
* @var array
*/
protected static $requiredParams = [];
/**
* Map of input data
*
* @var array
*/
protected static $map = [];
/**
* Validate input data
*
* @param array $data
*
* @return bool
*
* @throws InvalidArgumentException
*/
public static function validate($data)
{
if (count(array_intersect_key(array_flip(static::$requiredParams), $data)) === count(static::$requiredParams)) {
return true;
}
throw new InvalidArgumentException();
}
public function map($data)
{
foreach (static::$map as $key => $item) {
if (isset($data[$key]) && (!is_array($data[$key]) || (is_array($data[$key]) && !empty($data[$key])))) {
$method = 'set' . self::toCamelCase($key);
if ($item === true) {
$this->$method($data[$key]);
} else {
$this->$method($item::fromResponse($data[$key]));
}
}
}
}
protected static function toCamelCase($str)
{
return str_replace(" ", "", ucwords(str_replace("_", " ", $str)));
}
public function toJson($inner = false)
{
$output = [];
foreach (static::$map as $key => $item) {
$property = lcfirst(self::toCamelCase($key));
if (!is_null($this->$property)) {
if (is_array($this->$property)) {
$output[$key] = array_map(
function ($v) {
return is_object($v) ? $v->toJson(true) : $v;
},
$this->$property
);
} else {
$output[$key] = $item === true ? $this->$property : $this->$property->toJson(true);
}
}
}
return $inner === false ? json_encode($output) : $output;
}
public static function fromResponse($data)
{
if ($data === true) {
return true;
}
self::validate($data);
$instance = new static();
$instance->map($data);
return $instance;
}
}