Entity::__call()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 3
c 2
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 2
crap 2
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of FlexPHP.
4
 *
5
 * (c) Freddie Gar <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace FlexPHP\Entities;
11
12
abstract class Entity implements EntityInterface
13
{
14
    /**
15
     * @param array<string, mixed> $properties
16
     */
17 28
    public function __construct(array $properties = [])
18
    {
19 28
        $this->hydrate($properties);
20 28
    }
21
22
    /**
23
     * @param mixed $value
24
     */
25 6
    public function __set(string $name, $value): void
26
    {
27 6
        $this->{$name} = $value;
28 6
    }
29
30
    /**
31
     * @param string $name
32
     *
33
     * @return mixed
34
     */
35 27
    public function __get($name)
36
    {
37 27
        return $this->{$name} ?? null;
38
    }
39
40
    /**
41
     * @param array<int> $arguments
42
     *
43
     * @return mixed
44
     */
45 27
    public function __call(string $name, array $arguments)
46
    {
47 27
        if (\count($arguments) > 0) {
48 6
            $this->__set($name, $arguments[0]);
49
        }
50
51 27
        return $this->__get($name);
52
    }
53
54
    /**
55
     * Entity to json string
56
     *
57
     * @return string
58
     */
59 3
    public function __toString()
60
    {
61 3
        return \json_encode(\array_filter($this->toArray()), \JSON_ERROR_NONE) ?: '';
62
    }
63
64
    /**
65
     * @return array<string, mixed>
66
     */
67 27
    public function toArray(): array
68
    {
69 27
        return \get_object_vars($this);
70
    }
71
72
    /**
73
     * @param  array<string> $properties
74
     */
75 28
    private function hydrate(array $properties): void
76
    {
77 28
        foreach ($properties as $property => $value) {
78 19
            if (\property_exists($this, $property)) {
79 19
                $this->{$property} = $value;
80
            }
81
        }
82 28
    }
83
}
84