Completed
Pull Request — master (#2)
by
unknown
10:36
created

CastToIntegerConstructor::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 3
nc 4
nop 1
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
 * @package MadWeb\Enums
19
 */
20
trait CastToIntegerConstructor
21
{
22
23
    /**
24
     * Creates a new value of some type, with casting the supplied value to an integer if the value is present in a
25
     * non-strict comparison with the values.
26
     *
27
     * @param mixed $value
28
     *
29
     * @throws \UnexpectedValueException if incompatible type is given.
30
     */
31
    public function __construct($value = null)
32
    {
33
        // Use the default value when no value is supplied, this cannot be omitted due to
34
        // non-strict comparison null == 0, resulting in the integer 0.
35
        if (is_null($value)) {
36
            $value = static::__default;
37
        }
38
39
        // Verify the supplied value is present when we don't check for the type.
40
        if (\in_array($value, static::toArray(), false)) {
41
            $value = (int) $value;
42
        }
43
44
        parent::__construct($value);
45
    }
46
}
47