Completed
Pull Request — master (#2)
by
unknown
14:16
created

CastToIntegerConstructor::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 7
cts 7
cp 1
rs 9.7666
c 0
b 0
f 0
cc 3
nc 4
nop 1
crap 3
1
<?php
2
3
namespace MadWeb\Enum;
4
5
/**
6
 * Trait CastToIntegerConstructor to support using a string as value to create the enum, while the enum value is an
7
 * integer.
8
 *
9
 * This trait solves the issue the Enum cannot be constructed in EnumCastable used in a model while using a integer enum
10
 * value. Some database drivers return integers as integer while other returns them as string.
11
 *
12
 * For example the PHP MySQL native driver return integers, while other drivers return strings.
13
 * See the issue https://github.com/laravel/framework/issues/11780 which describes this as well.
14
 *
15
 * Please note it's not recommended to use constructors in traits, since constructors should be specific to a class to
16
 * which they belong. Another solution can be to add a boolean castToInteger on the enum class.
17
 */
18
trait CastToIntegerConstructor
19
{
20
    /**
21
     * Creates a new value of some type, with casting the supplied value to an integer if the value is present in a
22
     * non-strict comparison with the values.
23
     *
24
     * @param mixed $value
25
     *
26
     * @throws \UnexpectedValueException if incompatible type is given.
27
     */
28 45
    public function __construct($value = null)
29
    {
30
        // Use the default value when no value is supplied, this cannot be omitted due to
31
        // non-strict comparison null == 0, resulting in the integer 0.
32 45
        if (is_null($value)) {
33 15
            $value = static::__default;
34
        }
35
36
        // Verify the supplied value is present when we don't check for the type.
37 45
        if (\in_array($value, static::toArray(), false)) {
38 45
            $value = (int) $value;
39
        }
40
41 45
        parent::__construct($value);
42 45
    }
43
}
44