Test Failed
Push — main ( 269cf1...da3911 )
by Rafael
06:16
created

Singleton::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Alxarafe\Core\Base;
4
5
use Alxarafe\Core\Utils\ClassUtils;
6
7
abstract class Singleton
8
{
9
    /**
10
     * Hold the classes on instance.
11
     *
12
     * @var array
13
     */
14
    private static array $instances = [];
15
16
    public function __construct(string $index = 'main')
17
    {
18
        $className = self::getClassName();
19
        if (isset(self::$instances[$className][$index])) {
20
            die("Please use '$className:getInstance()' instead of 'new' to instantiate a Singleton.");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
21
        }
22
        self::$instances[$className][$index] = $this;
23
    }
24
25
    /**
26
     * Returns the class name.
27
     *
28
     * @return string
29
     */
30
    protected static function getClassName(): string
31
    {
32
        $class = static::class;
33
        return ClassUtils::getShortName($class, $class);
34
    }
35
36
    /**
37
     * The object is created from within the class itself only if the class
38
     * has no instance.
39
     *
40
     * We opted to use an array to make several singletons according to the
41
     * index passed to getInstance
42
     *
43
     * @param string $index
44
     *
45
     * @return mixed
46
     */
47
    public static function getInstance(string $index = 'main')
48
    {
49
        $className = self::getClassName();
50
        if (!isset(self::$instances[$className][$index])) {
51
            new static($index);
52
        }
53
        return self::$instances[$className][$index];
54
    }
55
56
}