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

AbstractEntity::offsetExists()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 30

Duplication

Lines 8
Ratio 26.67 %

Importance

Changes 0
Metric Value
dl 8
loc 30
rs 8.8177
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
        $getter = 'get'.ucfirst($key);
155
        if (is_callable([ $this, $getter])) {
156
            $value = $this->{$getter}();
157
        }
158 View Code Duplication
        else 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...
159
            $value = $this->{$key}();
160
        } else {
161
            if (!isset($this->{$key})) {
162
                return false;
163
            }
164
            $value = $this->{$key};
165
        }
166
167
        return ($value !== null);
168
    }
169
170
    /**
171
     * Returns the value from the specified key on this entity.
172
     *
173
     * Routine:
174
     * - If the entity has a getter method (e.g., "foo_bar" → `fooBar()`),
175
     *   its called and returns its value;
176
     * - If the entity has a property (e.g., `$fooBar`), its value is returned;
177
     * - If the entity has neither, NULL is returned.
178
     *
179
     * @see    \ArrayAccess
180
     * @param  string $key The data key to retrieve.
181
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
182
     * @return mixed Value of the requested $key on success, NULL if the $key is not set.
183
     */
184
    public function offsetGet($key)
185
    {
186
        if (is_numeric($key)) {
187
            throw new InvalidArgumentException(
188
                'Entity array access only supports non-numeric keys'
189
            );
190
        }
191
192
        $key = $this->camelize($key);
193
194
        /** @internal Edge Case: "_" → "" */
195
        if ($key === '') {
196
            return null;
197
        }
198
199
        $getter = 'get'.ucfirst($key);
200
        if (is_callable([ $this, $getter])) {
201
            return $this->{$getter}();
202
        } elseif (is_callable([ $this, $key ])) {
203
            return $this->{$key}();
204
        } else {
205
            if (isset($this->{$key})) {
206
                return $this->{$key};
207
            } else {
208
                return null;
209
            }
210
        }
211
    }
212
213
    /**
214
     * Assigns the value to the specified key on this entity.
215
     *
216
     * Routine:
217
     * - The data key is added to the {@see self::$keys entity's key pool}.
218
     * - If the entity has a setter method (e.g., "foo_bar" → `setFooBar()`),
219
     *   its called and passed the value;
220
     * - If the entity has NO setter method, the value is assigned to a property (e.g., `$fooBar`).
221
     *
222
     * @see    \ArrayAccess
223
     * @param  string $key   The data key to assign $value to.
224
     * @param  mixed  $value The data value to assign to $key.
225
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
226
     * @return void
227
     */
228
    public function offsetSet($key, $value)
229
    {
230
        if (is_numeric($key)) {
231
            throw new InvalidArgumentException(
232
                'Entity array access only supports non-numeric keys'
233
            );
234
        }
235
236
        $key = $this->camelize($key);
237
238
        /** @internal Edge Case: "_" → "" */
239
        if ($key === '') {
240
            return;
241
        }
242
243
        $setter = 'set'.ucfirst($key);
244 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...
245
            $this->{$setter}($value);
246
        } else {
247
            $this->{$key} = $value;
248
        }
249
250
        $this->keys[$key] = true;
251
    }
252
253
    /**
254
     * Removes the value from the specified key on this entity.
255
     *
256
     * Routine:
257
     * - The data key is removed from the {@see self::$keys entity's key pool}.
258
     * - NULL is {@see self::offsetSet() assigned} to the entity.
259
     *
260
     * @see    \ArrayAccess
261
     * @uses   self::offsetSet()
262
     * @param  string $key The data key to remove.
263
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
264
     * @return void
265
     */
266
    public function offsetUnset($key)
267
    {
268
        if (is_numeric($key)) {
269
            throw new InvalidArgumentException(
270
                'Entity array access only supports non-numeric keys'
271
            );
272
        }
273
274
        $key = $this->camelize($key);
275
276
        /** @internal Edge Case: "_" → "" */
277
        if ($key === '') {
278
            return;
279
        }
280
281
        $this[$key] = null;
282
        unset($this->keys[$key]);
283
    }
284
285
    /**
286
     * Gets the data that can be serialized with {@see json_encode()}.
287
     *
288
     * @see    \JsonSerializable
289
     * @return array Key-value array of data.
290
     */
291
    public function jsonSerialize()
292
    {
293
        return $this->data();
294
    }
295
296
    /**
297
     * Serializes the data on this entity.
298
     *
299
     * @see    \Serializable
300
     * @return string Returns a string containing a byte-stream representation of the object.
301
     */
302
    public function serialize()
303
    {
304
        return serialize($this->data());
305
    }
306
307
    /**
308
     * Applies the serialized data to this entity.
309
     *
310
     * @see    \Serializable
311
     * @param  string $data The serialized data to extract.
312
     * @return void
313
     */
314
    public function unserialize($data)
315
    {
316
        $data = unserialize($data);
317
        $this->setData($data);
318
    }
319
320
    /**
321
     * Transform a string from "snake_case" to "camelCase".
322
     *
323
     * @param  string $str The string to camelize.
324
     * @return string The camelized string.
325
     */
326
    final protected function camelize($str)
327
    {
328
        if (strstr($str, '_') === false) {
329
            return $str;
330
        }
331
        return lcfirst(implode('', array_map('ucfirst', explode('_', $str))));
332
    }
333
}
334