Completed
Push — master ( 30e9be...3f3ab1 )
by Mathieu
01:18
created

AbstractEntity::offsetGet()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.8497
c 0
b 0
f 0
cc 6
nc 6
nop 1
1
<?php
2
3
namespace Charcoal\Config;
4
5
use ArrayAccess;
6
use InvalidArgumentException;
7
8
/**
9
 * Default data model.
10
 *
11
 * ### Notes on {@see \ArrayAccess}:
12
 *
13
 * - Keys SHOULD be formatted as "snake_case" (e.g., "first_name") or "camelCase" (e.g., "firstName").
14
 *   and WILL be converted to the latter {@see PSR-1} to access or assign values.
15
 * - Values are accessed and assigned via methods and properties which MUST be formatted as "camelCase",
16
 *   e.g.: `$firstName`, `firstName()`, `setFirstName()`.
17
 * - A key-value pair is internally passed to a (non-private / non-static) setter method (if present)
18
 *   or assigned to a (non-private / non-static) property (declared or not) and tracks affected keys.
19
 */
20
abstract class AbstractEntity implements EntityInterface
21
{
22
    /**
23
     * Holds a list of all data keys.
24
     *
25
     * @var array
26
     */
27
    protected $keys = [];
28
29
    /**
30
     * Gets the data keys on this entity.
31
     *
32
     * @return array
33
     */
34
    public function keys()
35
    {
36
        return array_keys($this->keys);
37
    }
38
39
    /**
40
     * Gets all data, or a subset, from this entity.
41
     *
42
     * @uses   self::offsetExists()
43
     * @uses   self::offsetGet()
44
     * @param  string[] $keys Optional. Extracts only the requested data.
45
     * @return array Key-value array of data, excluding pairs with NULL values.
46
     */
47
    public function data(array $keys = null)
48
    {
49
        if ($keys === null) {
50
            $keys = $this->keys();
51
        }
52
53
        $data = [];
54
        foreach ($keys as $key) {
55
            if (strtolower($key) === 'data') {
56
                /** @internal Edge Case: Avoid recursive call */
57
                continue;
58
            }
59
60
            if (isset($this[$key])) {
61
                $data[$key] = $this[$key];
62
            }
63
        }
64
        return $data;
65
    }
66
67
    /**
68
     * Sets data on this entity.
69
     *
70
     * @uses   self::offsetSet()
71
     * @param  array $data Key-value array of data to append.
72
     * @return self
73
     */
74
    public function setData(array $data)
75
    {
76
        foreach ($data as $key => $value) {
77
            if (strtolower($key) === 'data') {
78
                /** @internal Edge Case: Avoid recursive call */
79
                continue;
80
            }
81
82
            $this[$key] = $value;
83
        }
84
        return $this;
85
    }
86
87
    /**
88
     * Determines if this entity contains the specified key and if its value is not NULL.
89
     *
90
     * @uses   self::offsetExists()
91
     * @param  string $key The data key to check.
92
     * @return boolean TRUE if $key exists and has a value other than NULL, FALSE otherwise.
93
     */
94
    public function has($key)
95
    {
96
        return isset($this[$key]);
97
    }
98
99
    /**
100
     * Find an entry of the configuration by its key and retrieve it.
101
     *
102
     * @uses   self::offsetGet()
103
     * @param  string $key The data key to retrieve.
104
     * @return mixed Value of the requested $key on success, NULL if the $key is not set.
105
     */
106
    public function get($key)
107
    {
108
        return $this[$key];
109
    }
110
111
    /**
112
     * Assign a value to the specified key on this entity.
113
     *
114
     * @uses   self::offsetSet()
115
     * @param  string $key   The data key to assign $value to.
116
     * @param  mixed  $value The data value to assign to $key.
117
     * @return self Chainable
118
     */
119
    public function set($key, $value)
120
    {
121
        $this[$key] = $value;
122
        return $this;
123
    }
124
125
    /**
126
     * Determines if this entity contains the specified key and if its value is not NULL.
127
     *
128
     * Routine:
129
     * - If the entity has a getter method (e.g., "foo_bar" → `fooBar()`),
130
     *   its called and its value is checked;
131
     * - If the entity has a property (e.g., `$fooBar`), its value is checked;
132
     * - If the entity has neither, FALSE is returned.
133
     *
134
     * @see    \ArrayAccess
135
     * @param  string $key The data key to check.
136
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
137
     * @return boolean TRUE if $key exists and has a value other than NULL, FALSE otherwise.
138
     */
139
    public function offsetExists($key)
140
    {
141
        if (is_numeric($key)) {
142
            throw new InvalidArgumentException(
143
                'Entity array access only supports non-numeric keys'
144
            );
145
        }
146
147
        $key = $this->camelize($key);
148
149
        /** @internal Edge Case: "_" → "" */
150
        if ($key === '') {
151
            return false;
152
        }
153
154 View Code Duplication
        if (is_callable([ $this, $key ])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
155
            $value = $this->{$key}();
156
        } else {
157
            if (!isset($this->{$key})) {
158
                return false;
159
            }
160
            $value = $this->{$key};
161
        }
162
163
        return ($value !== null);
164
    }
165
166
    /**
167
     * Returns the value from the specified key on this entity.
168
     *
169
     * Routine:
170
     * - If the entity has a getter method (e.g., "foo_bar" → `fooBar()`),
171
     *   its called and returns its value;
172
     * - If the entity has a property (e.g., `$fooBar`), its value is returned;
173
     * - If the entity has neither, NULL is returned.
174
     *
175
     * @see    \ArrayAccess
176
     * @param  string $key The data key to retrieve.
177
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
178
     * @return mixed Value of the requested $key on success, NULL if the $key is not set.
179
     */
180
    public function offsetGet($key)
181
    {
182
        if (is_numeric($key)) {
183
            throw new InvalidArgumentException(
184
                'Entity array access only supports non-numeric keys'
185
            );
186
        }
187
188
        $key = $this->camelize($key);
189
190
        /** @internal Edge Case: "_" → "" */
191
        if ($key === '') {
192
            return null;
193
        }
194
195
        $getter = 'get'.ucfirst($key);
196
        if (is_callable([ $this, $getter])) {
197
            return $this->{$getter}();
198
        } elseif (is_callable([ $this, $key ])) {
199
            return $this->{$key}();
200
        } else {
201
            if (isset($this->{$key})) {
202
                return $this->{$key};
203
            } else {
204
                return null;
205
            }
206
        }
207
    }
208
209
    /**
210
     * Assigns the value to the specified key on this entity.
211
     *
212
     * Routine:
213
     * - The data key is added to the {@see self::$keys entity's key pool}.
214
     * - If the entity has a setter method (e.g., "foo_bar" → `setFooBar()`),
215
     *   its called and passed the value;
216
     * - If the entity has NO setter method, the value is assigned to a property (e.g., `$fooBar`).
217
     *
218
     * @see    \ArrayAccess
219
     * @param  string $key   The data key to assign $value to.
220
     * @param  mixed  $value The data value to assign to $key.
221
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
222
     * @return void
223
     */
224
    public function offsetSet($key, $value)
225
    {
226
        if (is_numeric($key)) {
227
            throw new InvalidArgumentException(
228
                'Entity array access only supports non-numeric keys'
229
            );
230
        }
231
232
        $key = $this->camelize($key);
233
234
        /** @internal Edge Case: "_" → "" */
235
        if ($key === '') {
236
            return;
237
        }
238
239
        $setter = 'set'.ucfirst($key);
240 View Code Duplication
        if (is_callable([ $this, $setter ])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
241
            $this->{$setter}($value);
242
        } else {
243
            $this->{$key} = $value;
244
        }
245
246
        $this->keys[$key] = true;
247
    }
248
249
    /**
250
     * Removes the value from the specified key on this entity.
251
     *
252
     * Routine:
253
     * - The data key is removed from the {@see self::$keys entity's key pool}.
254
     * - NULL is {@see self::offsetSet() assigned} to the entity.
255
     *
256
     * @see    \ArrayAccess
257
     * @uses   self::offsetSet()
258
     * @param  string $key The data key to remove.
259
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
260
     * @return void
261
     */
262
    public function offsetUnset($key)
263
    {
264
        if (is_numeric($key)) {
265
            throw new InvalidArgumentException(
266
                'Entity array access only supports non-numeric keys'
267
            );
268
        }
269
270
        $key = $this->camelize($key);
271
272
        /** @internal Edge Case: "_" → "" */
273
        if ($key === '') {
274
            return;
275
        }
276
277
        $this[$key] = null;
278
        unset($this->keys[$key]);
279
    }
280
281
    /**
282
     * Gets the data that can be serialized with {@see json_encode()}.
283
     *
284
     * @see    \JsonSerializable
285
     * @return array Key-value array of data.
286
     */
287
    public function jsonSerialize()
288
    {
289
        return $this->data();
290
    }
291
292
    /**
293
     * Serializes the data on this entity.
294
     *
295
     * @see    \Serializable
296
     * @return string Returns a string containing a byte-stream representation of the object.
297
     */
298
    public function serialize()
299
    {
300
        return serialize($this->data());
301
    }
302
303
    /**
304
     * Applies the serialized data to this entity.
305
     *
306
     * @see    \Serializable
307
     * @param  string $data The serialized data to extract.
308
     * @return void
309
     */
310
    public function unserialize($data)
311
    {
312
        $data = unserialize($data);
313
        $this->setData($data);
314
    }
315
316
    /**
317
     * Transform a string from "snake_case" to "camelCase".
318
     *
319
     * @param  string $str The string to camelize.
320
     * @return string The camelized string.
321
     */
322
    final protected function camelize($str)
323
    {
324
        if (strstr($str, '_') === false) {
325
            return $str;
326
        }
327
        return lcfirst(implode('', array_map('ucfirst', explode('_', $str))));
328
    }
329
}
330