Test Failed
Pull Request — master (#34)
by Anatoly
02:07
created

AbstractObject::getFields()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 24
rs 9.6111
cc 5
nc 5
nop 0
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
     * @var string[]
28
     */
29
    protected const IGNORE_FIELDS = [];
30
31
    /**
32
     * @var array
33
     */
34
    protected const FIELD_ALIASES = [];
35
36
    /**
37
     * {@inheritDoc}
38
     */
39
    public function toArray() : array
40
    {
41
        $fields = $this->getFields();
42
43
        array_walk_recursive($fields, function (&$value) {
44
            if ($value instanceof ObjectInterface) {
45
                $value = $value->toArray();
46
            }
47
        });
48
49
        return $fields;
50
    }
51
52
    /**
53
     * Gets all filled fields of the object
54
     *
55
     * @return array
56
     */
57
    protected function getFields() : array
58
    {
59
        $fields = [];
60
61
        foreach ($this as $name => $value) {
62
            // empty field...
63
            if (null === $value) {
64
                continue;
65
            }
66
67
            // ignored field...
68
            if (in_array($name, static::IGNORE_FIELDS)) {
69
                continue;
70
            }
71
72
            // the field has an alias. renaming...
73
            if (isset(static::FIELD_ALIASES[$name])) {
74
                $name = static::FIELD_ALIASES[$name];
75
            }
76
77
            $fields[$name] = $value;
78
        }
79
80
        return $fields;
81
    }
82
}
83