Test Failed
Push — 7.x ( bea7e1...2b11c5 )
by Adrien
08:51
created

SplReflectionEnumBackedCase   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 14
c 1
b 0
f 1
dl 0
loc 51
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getBackingValue() 0 4 1
A __construct() 0 7 2
A getValue() 0 12 2
1
<?php
2
3
/**
4
 * Part of SplTypes package.
5
 *
6
 * (c) Adrien Loyant <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Ducks\Component\SplTypes\Reflection;
15
16
use Ducks\Component\SplTypes\SplUnitEnum;
17
18
class SplReflectionEnumBackedCase extends SplReflectionEnumUnitCase
19
{
20
    /**
21
     * Instantiates a ReflectionEnumBackedCase object
22
     *
23
     * @param object|string $class An enum instance or a name.
24
     * @param string $constant An enum constant name.
25
     *
26
     * @throws \ReflectionException if $class is not a \ReflectionEnumBackedCase
27
     *
28
     * @link https://www.php.net/manual/en/reflectionenumbackedcase.construct.php
29
     */
30
    public function __construct($class, string $constant)
31
    {
32
        parent::__construct($class, $constant);
33
34
        if (!$this->getEnum()->isBacked()) {
35
            throw new \ReflectionException(
36
                'Enum case ' . $this->class . '::' . $this->name . ' is not a backed case'
37
            );
38
        }
39
    }
40
41
    /**
42
     * Gets the scalar value backing this Enum case
43
     *
44
     * @return int|string The scalar equivalent of this enum case.
45
     *
46
     * @link https://www.php.net/manual/en/reflectionenumbackedcase.getbackingvalue.php
47
     */
48
    public function getBackingValue()
49
    {
50
        return $this->getDeclaringClass()
51
            ->getConstant($this->name);
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function getValue(): SplUnitEnum
58
    {
59
        $instance = parent::getValue();
60
61
        $class = new \ReflectionObject($instance);
62
        if ($class->hasProperty('value')) {
63
            $property = $class->getProperty('value');
64
            $property->setAccessible(true);
65
            $property->setValue($instance, $class->getConstant($this->name));
66
        }
67
68
        return $instance;
69
    }
70
}
71