SplEnumSingletonTrait::getInstance()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 4
c 1
b 0
f 1
nc 2
nop 1
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 6
rs 10
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
namespace Ducks\Component\SplTypes;
13
14
/**
15
 * Trait used for enum emulation
16
 *
17
 * @phpstan-require-extends SplEnum
18
 * @phpstan-require-implements SplEnumSingletonable
19
 *
20
 * @psalm-api
21
 */
22
trait SplEnumSingletonTrait
23
{
24
    /**
25
     * internal instance of enum
26
     *
27
     * @var SplEnumSingletonable[]
28
     *
29
     * @phpstan-var array<string,SplEnumSingletonable>
30
     */
31
    private static array $instances = [];
32
33
    /**
34
     * Return the singleton enum instance.
35
     *
36
     * @param string $name
37
     *
38
     * @return SplEnumSingletonable
39
     *
40
     * @throws \Error if $name is not a case
41
     *
42
     * @see SplEnum::__callStatic()
43
     */
44
    public static function getInstance(string $name): SplEnumSingletonable
45
    {
46
        if (!isset(self::$instances[$name])) {
47
            /** @var SplEnumSingletonable $instance */
48
            $instance = static::$name();
49
            self::$instances[$name] = $instance;
50
        }
51
52
        return self::$instances[$name];
53
    }
54
}
55