1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* It's free open-source software released under the MIT License. |
5
|
|
|
* |
6
|
|
|
* @author Anatoly Fenric <[email protected]> |
7
|
|
|
* @copyright Copyright (c) 2018, Anatoly Fenric |
8
|
|
|
* @license https://github.com/sunrise-php/http-router/blob/master/LICENSE |
9
|
|
|
* @link https://github.com/sunrise-php/http-router |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sunrise\Http\Router\OpenApi; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Import functions |
16
|
|
|
*/ |
17
|
|
|
use function array_walk_recursive; |
18
|
|
|
use function in_array; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* AbstractObject |
22
|
|
|
*/ |
23
|
|
|
abstract class AbstractObject implements ObjectInterface |
24
|
|
|
{ |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* The fields specified in this array will not be returned when converting this object to an array |
28
|
|
|
* |
29
|
|
|
* @var string[] |
30
|
|
|
*/ |
31
|
|
|
protected const IGNORE_FIELDS = []; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* The fields specified in this array will be renamed when converting this object to an array |
35
|
|
|
* |
36
|
|
|
* The constant must contain the following structure: `[field => alias, ...]` |
37
|
|
|
* |
38
|
|
|
* @var array |
39
|
|
|
*/ |
40
|
|
|
protected const FIELD_ALIASES = []; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Recursively converts the object into an array and its children |
44
|
|
|
* |
45
|
|
|
* {@inheritDoc} |
46
|
|
|
*/ |
47
|
45 |
|
public function toArray() : array |
48
|
|
|
{ |
49
|
45 |
|
$fields = $this->getFields(); |
50
|
|
|
|
51
|
|
|
array_walk_recursive($fields, function (&$value) { |
52
|
45 |
|
if ($value instanceof ObjectInterface) { |
53
|
9 |
|
$value = $value->toArray(); |
54
|
|
|
} |
55
|
45 |
|
}); |
56
|
|
|
|
57
|
45 |
|
return $fields; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Gets all filled fields from the object |
62
|
|
|
* |
63
|
|
|
* @return array |
64
|
|
|
*/ |
65
|
45 |
|
protected function getFields() : array |
66
|
|
|
{ |
67
|
45 |
|
$fields = []; |
68
|
|
|
|
69
|
45 |
|
foreach ($this as $name => $value) { |
70
|
|
|
// empty field... |
71
|
45 |
|
if (null === $value) { |
72
|
42 |
|
continue; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
// ignored field... |
76
|
45 |
|
if (in_array($name, static::IGNORE_FIELDS)) { |
77
|
7 |
|
continue; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
// the field has an alias. renaming... |
81
|
45 |
|
if (isset(static::FIELD_ALIASES[$name])) { |
82
|
1 |
|
$name = static::FIELD_ALIASES[$name]; |
83
|
|
|
} |
84
|
|
|
|
85
|
45 |
|
$fields[$name] = $value; |
86
|
|
|
} |
87
|
|
|
|
88
|
45 |
|
return $fields; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|