Attribute   B
last analyzed

Complexity

Total Complexity 48

Size/Duplication

Total Lines 362
Duplicated Lines 2.76 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 10
loc 362
rs 8.4864
c 0
b 0
f 0
wmc 48
lcom 1
cbo 5

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 3
A boot() 0 12 4
A set() 0 5 1
A newBag() 0 4 1
A getValue() 0 8 2
A getMetaKey() 0 4 1
A castValue() 0 12 2
A setMetaKey() 0 8 2
A setType() 0 6 2
A setValue() 0 14 4
A mutateValue() 0 10 2
A isStringable() 0 4 1
A getValueType() 0 7 3
A getMutatedType() 5 8 4
A hasMutator() 0 4 1
B getMutator() 5 10 5
A getTable() 0 4 2
A setCustomTable() 0 6 2
B castToString() 0 14 5
A __toString() 0 4 1

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 Attribute 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 Attribute, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Sofa\Eloquence\Metable;
4
5
use InvalidArgumentException;
6
use Illuminate\Database\Eloquent\Model;
7
use Sofa\Eloquence\Contracts\Attribute as AttributeContract;
8
use Sofa\Eloquence\Mutator\Mutator;
9
10
/**
11
 * @property array $attributes
12
 */
13
class Attribute extends Model implements AttributeContract
14
{
15
    /**
16
     * Attribute mutator instance.
17
     *
18
     * @var \Sofa\Eloquence\Contracts\Mutator
19
     */
20
    protected static $attributeMutator;
21
22
    /**
23
     * Custom table name.
24
     *
25
     * @var string
26
     */
27
    protected static $customTable;
28
29
    /**
30
     * The database table used by the model.
31
     *
32
     * @var string
33
     */
34
    protected $table = 'meta_attributes';
35
36
    /**
37
     * Indicates if the model should be timestamped.
38
     *
39
     * @var boolean
40
     */
41
    public $timestamps = false;
42
43
    /**
44
     * The primary key for the model.
45
     *
46
     * @var string
47
     */
48
    protected $primaryKey = 'meta_id';
49
50
    /**
51
     * @var array
52
     */
53
    protected $getterMutators = [
54
        'array'      => 'json_decode',
55
        'StdClass'   => 'json_decode',
56
        'DateTime'   => 'asDateTime',
57
        Model::class => 'unserialize',
58
    ];
59
60
    /**
61
     * @var array
62
     */
63
    protected $setterMutators = [
64
        'array'      => 'json_encode',
65
        'StdClass'   => 'json_encode',
66
        'DateTime'   => 'fromDateTime',
67
        Model::class => 'serialize',
68
    ];
69
70
    /**
71
     * The attributes included in the model's JSON and array form.
72
     *
73
     * @var array
74
     */
75
    protected $visible = ['meta_key', 'meta_value', 'meta_type'];
76
77
    /**
78
     * Create new attribute instance.
79
     *
80
     * @param string|array  $key
81
     * @param mixed  $value
82
     */
83
    public function __construct($key = null, $value = null)
84
    {
85
        // default behaviour
86
        if (is_array($key)) {
87
            parent::__construct($key);
88
        } else {
89
            parent::__construct();
90
91
            if (is_string($key)) {
92
                $this->set($key, $value);
93
            }
94
        }
95
    }
96
97
    /**
98
     * Boot this model.
99
     *
100
     * @codeCoverageIgnore
101
     *
102
     * @return void
103
     */
104
    protected static function boot()
105
    {
106
        parent::boot();
107
108
        if (!isset(static::$attributeMutator)) {
109
            if (function_exists('app') && app()->bound('eloquence.mutator')) {
110
                static::$attributeMutator = app('eloquence.mutator');
111
            } else {
112
                static::$attributeMutator = new Mutator;
113
            }
114
        }
115
    }
116
117
    /**
118
     * Set the meta attribute.
119
     *
120
     * @param string $key
121
     * @param mixed  $value
122
     */
123
    protected function set($key, $value)
124
    {
125
        $this->setMetaKey($key);
126
        $this->setValue($value);
127
    }
128
129
    /**
130
     * Create new AttributeBag.
131
     *
132
     * @param  array  $models
133
     * @return \Sofa\Eloquence\Metable\AttributeBag
134
     */
135
    public function newBag(array $models = [])
136
    {
137
        return new AttributeBag($models);
138
    }
139
140
    /**
141
     * Get the meta attribute value.
142
     *
143
     * @return mixed
144
     */
145
    public function getValue()
146
    {
147
        if ($this->hasMutator($this->attributes['meta_value'], 'getter', $this->attributes['meta_type'])) {
148
            return $this->mutateValue($this->attributes['meta_value'], 'getter');
149
        }
150
151
        return $this->castValue();
152
    }
153
154
    /**
155
     * Get the meta attribute key.
156
     *
157
     * @return string
158
     */
159
    public function getMetaKey()
160
    {
161
        return $this->attributes['meta_key'];
162
    }
163
164
    /**
165
     * Cast value to proper type.
166
     *
167
     * @return mixed
168
     */
169
    protected function castValue()
170
    {
171
        $value = $this->attributes['meta_value'];
172
173
        $validTypes = ['boolean', 'integer', 'float', 'double', 'array', 'object', 'null'];
174
175
        if (in_array($this->attributes['meta_type'], $validTypes)) {
176
            settype($value, $this->attributes['meta_type']);
177
        }
178
179
        return $value;
180
    }
181
182
    /**
183
     * Set key of the meta attribute.
184
     *
185
     * @param string $key
186
     *
187
     * @throws \InvalidArgumentException
188
     */
189
    protected function setMetaKey($key)
190
    {
191
        if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $key)) {
192
            throw new InvalidArgumentException("Provided key [{$key}] is not valid variable name.");
193
        }
194
195
        $this->attributes['meta_key'] = $key;
196
    }
197
198
    /**
199
     * Set type of the meta attribute.
200
     *
201
     * @param mixed $value
202
     */
203
    protected function setType($value)
204
    {
205
        $this->attributes['meta_type'] = $this->hasMutator($value, 'setter')
206
            ? $this->getMutatedType($value, 'setter')
207
            : $this->getValueType($value);
208
    }
209
210
    /**
211
     * Set value of the meta attribute.
212
     *
213
     * @param mixed $value
214
     *
215
     * @throws \Sofa\Eloquence\Metable\InvalidTypeException
216
     */
217
    public function setValue($value)
218
    {
219
        $this->setType($value);
220
221
        if ($this->hasMutator($value, 'setter')) {
222
            $value = $this->mutateValue($value, 'setter');
223
        } elseif (!$this->isStringable($value) && !is_null($value)) {
224
            throw new InvalidTypeException(
225
                "Unsupported meta value type [{$this->getValueType($value)}]."
226
            );
227
        }
228
229
        $this->attributes['meta_value'] = $value;
230
    }
231
232
    /**
233
     * Mutate attribute value.
234
     *
235
     * @param  mixed  $value
236
     * @param  string $dir
237
     * @return mixed
238
     */
239
    protected function mutateValue($value, $dir = 'setter')
240
    {
241
        $mutator = $this->getMutator($value, $dir, $this->attributes['meta_type']);
242
243
        if (method_exists($this, $mutator)) {
244
            return $this->{$mutator}($value);
245
        }
246
247
        return static::$attributeMutator->mutate($value, $mutator);
248
    }
249
250
    /**
251
     * Determine whether the value type can be set to string.
252
     *
253
     * @param  mixed   $value
254
     * @return boolean
255
     */
256
    protected function isStringable($value)
257
    {
258
        return is_scalar($value);
259
    }
260
261
    /**
262
     * Get the value type.
263
     *
264
     * @param  mixed  $value
265
     * @return string
266
     */
267
    protected function getValueType($value)
268
    {
269
        $type = is_object($value) ? get_class($value) : gettype($value);
270
271
        // use float instead of deprecated double
272
        return ($type == 'double') ? 'float' : $type;
273
    }
274
275
    /**
276
     * Get the mutated type.
277
     *
278
     * @param  mixed  $value
279
     * @param  string $dir
280
     * @return string
281
     */
282
    protected function getMutatedType($value, $dir = 'setter')
283
    {
284 View Code Duplication
        foreach ($this->{"{$dir}Mutators"} as $mutated => $mutator) {
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...
285
            if ($this->getValueType($value) == $mutated || $value instanceof $mutated) {
286
                return $mutated;
287
            }
288
        }
289
    }
290
291
    /**
292
     * Determine whether a mutator exists for the value type.
293
     *
294
     * @param  mixed   $value
295
     * @param  string  $dir
296
     * @return boolean
297
     */
298
    protected function hasMutator($value, $dir = 'setter', $type = null)
299
    {
300
        return (bool) $this->getMutator($value, $dir, $type);
301
    }
302
303
    /**
304
     * Get mutator for the type.
305
     *
306
     * @param  mixed  $value
307
     * @param  string $dir
308
     * @return string
309
     */
310
    protected function getMutator($value, $dir = 'setter', $type = null)
311
    {
312
        $type = $type ?: $this->getValueType($value);
313
314 View Code Duplication
        foreach ($this->{"{$dir}Mutators"} as $mutated => $mutator) {
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...
315
            if ($type == $mutated || $value instanceof $mutated) {
316
                return $mutator;
317
            }
318
        }
319
    }
320
321
    /**
322
     * Allow custom table name for meta attributes via config.
323
     *
324
     * @return string
325
     */
326
    public function getTable()
327
    {
328
        return isset(static::$customTable) ? static::$customTable : parent::getTable();
329
    }
330
331
    /**
332
     * Set custom table for the meta attributes. Allows doing it only once
333
     * in order to mimic protected behaviour, most likely in the service
334
     * provider, which in turn gets the table name from configuration.
335
     *
336
     * @param string $table
337
     */
338
    public static function setCustomTable($table)
339
    {
340
        if (!isset(static::$customTable)) {
341
            static::$customTable = $table;
342
        }
343
    }
344
345
    /**
346
     * Handle casting value to string.
347
     *
348
     * @return string
349
     */
350
    public function castToString()
351
    {
352
        if ($this->attributes['meta_type'] == 'array') {
353
            return $this->attributes['meta_value'];
354
        }
355
356
        $value = $this->getValue();
357
358
        if ($this->isStringable($value) || is_object($value) && method_exists($value, '__toString')) {
359
            return (string) $value;
360
        }
361
362
        return '';
363
    }
364
365
    /**
366
     * Handle dynamic casting to string.
367
     *
368
     * @return string
369
     */
370
    public function __toString()
371
    {
372
        return $this->castToString();
373
    }
374
}
375