Code

< 40 %
40-60 %
> 60 %
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