Singletons   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 9
c 2
b 1
f 0
dl 0
loc 29
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get() 0 11 4
1
<?php
2
3
/**
4
 * This file is part of the Cervo package.
5
 *
6
 * Copyright (c) 2010-2019 Nevraxe inc. & Marc André Audet <[email protected]>.
7
 *
8
 * @package   Cervo
9
 * @author    Marc André Audet <[email protected]>
10
 * @copyright 2010 - 2019 Nevraxe inc. & Marc André Audet
11
 * @license   See LICENSE.md  MIT
12
 * @link      https://github.com/Nevraxe/Cervo
13
 * @since     5.0.0
14
 */
15
16
declare(strict_types=1);
17
18
namespace Cervo;
19
20
use Cervo\Exceptions\Singletons\InvalidClassException;
21
use Cervo\Interfaces\SingletonInterface;
22
use Cervo\Utils\ClassUtils;
23
24
/**
25
 * Singletons manager for Cervo.
26
 *
27
 * @author Marc André Audet <[email protected]>
28
 */
29
final class Singletons
30
{
31
    private $objects = [];
32
33
    private $context;
34
35
    public function __construct(Context $context)
36
    {
37
        $this->context = $context;
38
    }
39
40
    /**
41
     * Fetch an object from the Singletons registry, or instantialise it.
42
     *
43
     * @param string $className The name of the class to get as Singleton
44
     *
45
     * @return SingletonInterface
46
     */
47
    public function get(string $className): SingletonInterface
48
    {
49
        if (isset($this->objects[$className]) && is_object($this->objects[$className])) {
50
            return $this->objects[$className];
51
        }
52
53
        if (!ClassUtils::implements($className, SingletonInterface::class)) {
54
            throw new InvalidClassException();
55
        }
56
57
        return ($this->objects[$className] = new $className($this->context));
58
    }
59
}
60