Completed
Push — master ( 027918...a3ee43 )
by Joschi
03:15
created

AbstractGenericProperties::toArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
/**
4
 * apparat-object
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Object
8
 * @subpackage  Apparat\Object\Application
9
 * @author      Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright   Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license     http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Apparat\Object\Domain\Model\Properties;
38
39
use Apparat\Object\Application\Utility\ArrayUtility;
40
use Apparat\Object\Domain\Model\Object\ObjectInterface;
41
42
/**
43
 * Abstract generic object properties collection
44
 *
45
 * @package Apparat\Object
46
 * @subpackage Apparat\Object\Application
47
 */
48
abstract class AbstractGenericProperties extends AbstractProperties implements GenericPropertiesInterface
49
{
50
    /**
51
     * Property collection constructor
52
     *
53
     * @param array $data Property data
54
     * @param ObjectInterface $object Owner object
55
     */
56 36
    public function __construct(array $data, ObjectInterface $object)
57
    {
58 36
        parent::__construct($data, $object);
59 36
    }
60
61
    /**
62
     * Get a property value
63
     *
64
     * Multi-level properties might be traversed by property name paths separated with colons (":").
65
     *
66
     * @param string $property Property name
67
     * @return mixed Property value
68
     * @throws InvalidArgumentException If the property name is invalid
69
     */
70 5
    public function getProperty($property)
71
    {
72 5
        $propertyPath = $this->buildPropertyPath($property);
73
74
        // Traverse the property tree
75 4
        $propertyPathSteps = [];
76 4
        $data =& $this->data;
77 4
        foreach ($propertyPath as $property) {
78 4
            $propertyPathSteps[] = $property;
79
80
            // If the property name step is invalid
81 4
            if (!array_key_exists($property, $data)) {
82 3
                throw new InvalidArgumentException(
83 3
                    sprintf(
84 3
                        'Invalid property name "%s"',
85 3
                        implode(self::PROPERTY_TRAVERSAL_SEPARATOR, $propertyPathSteps)
86 3
                    ),
87
                    InvalidArgumentException::INVALID_PROPERTY_NAME
88 3
                );
89
            }
90
91 3
            $data =& $data[$property];
92 3
        }
93
94 3
        return $data;
95
    }
96
97
    /**
98
     * Translate a property name to a property path segments
99
     *
100
     * @param string $property Property name
101
     * @return array Property path
102
     * @throws InvalidArgumentException If the property name is empty
103
     */
104 7
    protected function buildPropertyPath($property)
105
    {
106 7
        $propertyPath = array_filter(array_map('trim', explode(self::PROPERTY_TRAVERSAL_SEPARATOR, $property)));
107
108
        // If the property traversal path is empty
109 7
        if (!count($propertyPath)) {
110 1
            throw new InvalidArgumentException('Empty property name', InvalidArgumentException::EMPTY_PROPERTY_NAME);
111
        }
112
113 6
        return $propertyPath;
114
    }
115
116
    /**
117
     * Set a property value
118
     *
119
     * Multi-level properties might be traversed by property name paths separated with colons (":").
120
     *
121
     * @param string $property Property name
122
     * @param mixed $value Property value
123
     * @return GenericPropertiesInterface Self reference
124
     */
125 5
    public function setProperty($property, $value)
126
    {
127 5
        return $this->setPropertyPath($this->buildPropertyPath($property), $this->data, $value);
128
    }
129
130
    /**
131
     * Set a property value by path list and base data
132
     *
133
     * @param array $propertyPath Path list
134
     * @param array $propertyTree Base data
135
     * @param mixed $value Property value
136
     * @return GenericPropertiesInterface Self reference
137
     */
138 1
    protected function setPropertyPath(array $propertyPath, array $propertyTree, $value)
139
    {
140
        // Traverse the property tree and find the property node to set
141 1
        $created = false;
142 1
        $data =& $this->findPropertyNode($propertyPath, $propertyTree, $created);
143
144
        // If a new property is created with a non-empty value or an existing property is altered: Mutate
145 1
        if ($created ? !empty($value) : !$this->assertEquals($data, $value)) {
146 1
            $data = $value;
147 1
            return new static($propertyTree, $this->object);
148
        }
149
150 1
        return $this;
151
    }
152
153
    /**
154
     * Traverse the property tree and return a possibly node
155
     *
156
     * @param array $propertyPath Property name path
157
     * @param array $propertyTree Copy of the current property tree
158
     * @param boolean $created Property has been created
159
     * @return mixed Property node
160
     */
161 1
    protected function &findPropertyNode(
162
        array $propertyPath,
163
        array &$propertyTree,
164
        &$created
165
    ) {
166 1
        $data =& $propertyTree;
167
168
        // Run through all sub-properties
169 1
        foreach ($propertyPath as $property) {
170
            // Create the sub-property if it doesn't exist
171 1
            if (!array_key_exists($property, $data)) {
172 1
                $data[$property] = [];
173 1
                $created = true;
174 1
            }
175
176 1
            $data =& $data[$property];
177 1
        }
178
179 1
        return $data;
180
    }
181
182
    /**
183
     * Assert that two values equal
184
     *
185
     * @param mixed $expected Expected value
186
     * @param mixed $actual Actual value
187
     * @return boolean Actual value equals the expected one
188
     */
189 2
    protected function assertEquals($expected, $actual)
190
    {
191
        // If both values don't have the same type
192 2
        if (gettype($expected) !== gettype($actual)) {
193 1
            return false;
194
        }
195
196
        // If we are comparing arrays
197 2
        if (is_array($expected)) {
198 1
            return ArrayUtility::reduce($expected) == ArrayUtility::reduce($actual);
199
        }
200
201
        // Compare the values
202 2
        return $expected == $actual;
203
    }
204
}
205