AbstractEntity   A
last analyzed

Complexity

Total Complexity 42

Size/Duplication

Total Lines 363
Duplicated Lines 2.48 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 42
lcom 1
cbo 0
dl 9
loc 363
rs 9.0399
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A keys() 0 4 1
A data() 0 19 5
A setData() 0 12 3
A has() 0 4 1
A get() 0 4 1
A set() 0 5 1
A offsetSet() 3 28 5
A offsetUnset() 0 18 3
A jsonSerialize() 0 4 1
A serialize() 0 4 1
A unserialize() 0 5 1
A camelize() 0 16 3
B offsetExists() 3 40 8
B offsetGet() 3 40 8

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AbstractEntity often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractEntity, and based on these observations, apply Extract Interface, too.

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 per class.
24
     *
25
     * @var (boolean|null)[]
26
     */
27
    protected $keyCache = [];
28
29
    /**
30
     * Holds a list of getters/setters per class.
31
     *
32
     * @var string[]
33
     */
34
    protected $mutatorCache = [];
35
36
    /**
37
     * Holds a list of all camelized strings.
38
     *
39
     * @var string[]
40
     */
41
    protected static $camelCache = [];
42
43
    /**
44
     * Gets the data keys on this entity.
45
     *
46
     * @return array
47
     */
48
    public function keys()
49
    {
50
        return array_keys($this->keyCache);
51
    }
52
53
    /**
54
     * Gets all data, or a subset, from this entity.
55
     *
56
     * @uses   self::offsetExists()
57
     * @uses   self::offsetGet()
58
     * @param  string[] $keys Optional. Extracts only the requested data.
59
     * @return array Key-value array of data, excluding pairs with NULL values.
60
     */
61
    public function data(array $keys = null)
62
    {
63
        if ($keys === null) {
64
            $keys = $this->keys();
65
        }
66
67
        $data = [];
68
        foreach ($keys as $key) {
69
            if (strtolower($key) === 'data') {
70
                /** @internal Edge Case: Avoid recursive call */
71
                continue;
72
            }
73
74
            if (isset($this[$key])) {
75
                $data[$key] = $this[$key];
76
            }
77
        }
78
        return $data;
79
    }
80
81
    /**
82
     * Sets data on this entity.
83
     *
84
     * @uses   self::offsetSet()
85
     * @param  array $data Key-value array of data to append.
86
     * @return self
87
     */
88
    public function setData(array $data)
89
    {
90
        foreach ($data as $key => $value) {
91
            if (strtolower($key) === 'data') {
92
                /** @internal Edge Case: Avoid recursive call */
93
                continue;
94
            }
95
96
            $this[$key] = $value;
97
        }
98
        return $this;
99
    }
100
101
    /**
102
     * Determines if this entity contains the specified key and if its value is not NULL.
103
     *
104
     * @uses   self::offsetExists()
105
     * @param  string $key The data key to check.
106
     * @return boolean TRUE if $key exists and has a value other than NULL, FALSE otherwise.
107
     */
108
    public function has($key)
109
    {
110
        return isset($this[$key]);
111
    }
112
113
    /**
114
     * Find an entry of the configuration by its key and retrieve it.
115
     *
116
     * @uses   self::offsetGet()
117
     * @param  string $key The data key to retrieve.
118
     * @return mixed Value of the requested $key on success, NULL if the $key is not set.
119
     */
120
    public function get($key)
121
    {
122
        return $this[$key];
123
    }
124
125
    /**
126
     * Assign a value to the specified key on this entity.
127
     *
128
     * @uses   self::offsetSet()
129
     * @param  string $key   The data key to assign $value to.
130
     * @param  mixed  $value The data value to assign to $key.
131
     * @return self Chainable
132
     */
133
    public function set($key, $value)
134
    {
135
        $this[$key] = $value;
136
        return $this;
137
    }
138
139
    /**
140
     * Determines if this entity contains the specified key and if its value is not NULL.
141
     *
142
     * Routine:
143
     * - If the entity has a getter method (e.g., "foo_bar" → `fooBar()`),
144
     *   its called and its value is checked;
145
     * - If the entity has a property (e.g., `$fooBar`), its value is checked;
146
     * - If the entity has neither, FALSE is returned.
147
     *
148
     * @see    \ArrayAccess
149
     * @param  string $key The data key to check.
150
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
151
     * @return boolean TRUE if $key exists and has a value other than NULL, FALSE otherwise.
152
     */
153
    public function offsetExists($key)
154
    {
155
        if (is_numeric($key)) {
156
            throw new InvalidArgumentException(
157
                'Entity array access only supports non-numeric keys'
158
            );
159
        }
160
161
        $key = $this->camelize($key);
162
163
        /** @internal Edge Case: "_" → "" */
164
        if ($key === '') {
165
            return false;
166
        }
167
168
        $getter = 'get'.ucfirst($key);
169
        if (!isset($this->mutatorCache[$getter])) {
170
            $this->mutatorCache[$getter] = is_callable([ $this, $getter ]);
171
        }
172
173
        if ($this->mutatorCache[$getter]) {
174
            return ($this->{$getter}() !== null);
175
        }
176
177
        // -- START DEPRECATED
178 View Code Duplication
        if (!isset($this->mutatorCache[$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...
179
            $this->mutatorCache[$key] = is_callable([ $this, $key ]);
180
        }
181
182
        if ($this->mutatorCache[$key]) {
183
            return ($this->{$key}() !== null);
184
        }
185
        // -- END DEPRECATED
186
187
        if (isset($this->{$key})) {
188
            return true;
189
        }
190
191
        return false;
192
    }
193
194
    /**
195
     * Returns the value from the specified key on this entity.
196
     *
197
     * Routine:
198
     * - If the entity has a getter method (e.g., "foo_bar" → `fooBar()`),
199
     *   its called and returns its value;
200
     * - If the entity has a property (e.g., `$fooBar`), its value is returned;
201
     * - If the entity has neither, NULL is returned.
202
     *
203
     * @see    \ArrayAccess
204
     * @param  string $key The data key to retrieve.
205
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
206
     * @return mixed Value of the requested $key on success, NULL if the $key is not set.
207
     */
208
    public function offsetGet($key)
209
    {
210
        if (is_numeric($key)) {
211
            throw new InvalidArgumentException(
212
                'Entity array access only supports non-numeric keys'
213
            );
214
        }
215
216
        $key = $this->camelize($key);
217
218
        /** @internal Edge Case: "_" → "" */
219
        if ($key === '') {
220
            return null;
221
        }
222
223
        $getter = 'get'.ucfirst($key);
224
        if (!isset($this->mutatorCache[$getter])) {
225
            $this->mutatorCache[$getter] = is_callable([ $this, $getter ]);
226
        }
227
228
        if ($this->mutatorCache[$getter]) {
229
            return $this->{$getter}();
230
        }
231
232
        // -- START DEPRECATED
233 View Code Duplication
        if (!isset($this->mutatorCache[$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...
234
            $this->mutatorCache[$key] = is_callable([ $this, $key ]);
235
        }
236
237
        if ($this->mutatorCache[$key]) {
238
            return $this->{$key}();
239
        }
240
        // -- END DEPRECATED
241
242
        if (isset($this->{$key})) {
243
            return $this->{$key};
244
        }
245
246
        return null;
247
    }
248
249
    /**
250
     * Assigns the value to the specified key on this entity.
251
     *
252
     * Routine:
253
     * - The data key is added to the {@see self::$keys entity's key pool}.
254
     * - If the entity has a setter method (e.g., "foo_bar" → `setFooBar()`),
255
     *   its called and passed the value;
256
     * - If the entity has NO setter method, the value is assigned to a property (e.g., `$fooBar`).
257
     *
258
     * @see    \ArrayAccess
259
     * @param  string $key   The data key to assign $value to.
260
     * @param  mixed  $value The data value to assign to $key.
261
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
262
     * @return void
263
     */
264
    public function offsetSet($key, $value)
265
    {
266
        if (is_numeric($key)) {
267
            throw new InvalidArgumentException(
268
                'Entity array access only supports non-numeric keys'
269
            );
270
        }
271
272
        $key = $this->camelize($key);
273
274
        /** @internal Edge Case: "_" → "" */
275
        if ($key === '') {
276
            return;
277
        }
278
279
        $setter = 'set'.ucfirst($key);
280 View Code Duplication
        if (!isset($this->mutatorCache[$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...
281
            $this->mutatorCache[$setter] = is_callable([ $this, $setter ]);
282
        }
283
284
        if ($this->mutatorCache[$setter]) {
285
            $this->{$setter}($value);
286
        } else {
287
            $this->{$key} = $value;
288
        }
289
290
        $this->keyCache[$key] = true;
291
    }
292
293
    /**
294
     * Removes the value from the specified key on this entity.
295
     *
296
     * Routine:
297
     * - The data key is removed from the {@see self::$keys entity's key pool}.
298
     * - NULL is {@see self::offsetSet() assigned} to the entity.
299
     *
300
     * @see    \ArrayAccess
301
     * @uses   self::offsetSet()
302
     * @param  string $key The data key to remove.
303
     * @throws InvalidArgumentException If the $key is not a string or is a numeric value.
304
     * @return void
305
     */
306
    public function offsetUnset($key)
307
    {
308
        if (is_numeric($key)) {
309
            throw new InvalidArgumentException(
310
                'Entity array access only supports non-numeric keys'
311
            );
312
        }
313
314
        $key = $this->camelize($key);
315
316
        /** @internal Edge Case: "_" → "" */
317
        if ($key === '') {
318
            return;
319
        }
320
321
        $this[$key] = null;
322
        unset($this->keyCache[$key]);
323
    }
324
325
    /**
326
     * Gets the data that can be serialized with {@see json_encode()}.
327
     *
328
     * @see    \JsonSerializable
329
     * @return array Key-value array of data.
330
     */
331
    public function jsonSerialize()
332
    {
333
        return $this->data();
334
    }
335
336
    /**
337
     * Serializes the data on this entity.
338
     *
339
     * @see    \Serializable
340
     * @return string Returns a string containing a byte-stream representation of the object.
341
     */
342
    public function serialize()
343
    {
344
        return serialize($this->data());
345
    }
346
347
    /**
348
     * Applies the serialized data to this entity.
349
     *
350
     * @see    \Serializable
351
     * @param  string $data The serialized data to extract.
352
     * @return void
353
     */
354
    public function unserialize($data)
355
    {
356
        $data = unserialize($data);
357
        $this->setData($data);
358
    }
359
360
    /**
361
     * Transform a string from "snake_case" to "camelCase".
362
     *
363
     * @param  string $value The string to camelize.
364
     * @return string The camelized string.
365
     */
366
    final protected function camelize($value)
367
    {
368
        $key = $value;
369
370
        if (isset(static::$camelCache[$key])) {
371
            return static::$camelCache[$key];
372
        }
373
374
        if (strpos($value, '_') !== false) {
375
            $value = implode('', array_map('ucfirst', explode('_', $value)));
376
        }
377
378
        static::$camelCache[$key] = lcfirst($value);
379
380
        return static::$camelCache[$key];
381
    }
382
}
383