Completed
Pull Request — master (#357)
by Anton
03:23
created

AbstractProxy::initInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2
Metric Value
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Bluz\Proxy;
13
14
use Bluz\Common\Exception\CommonException;
15
use Bluz\Common\Exception\ComponentException;
16
17
/**
18
 * Abstract Proxy
19
 *
20
 * @package  Bluz\Proxy
21
 * @author   Anton Shevchuk
22
 * @link     https://github.com/bluzphp/framework/wiki/Proxy
23
 */
24
abstract class AbstractProxy
25
{
26
    /**
27
     * @var array instances of classes
28
     */
29
    protected static $instances = array();
30
31
    /**
32
     * Init class instance
33
     *
34
     * @return mixed
35
     * @throws ComponentException
36
     */
37
    protected static function initInstance()
38
    {
39
        throw new ComponentException(
40
            "Realization of method `initInstance()` is required for class `". static::class ."`"
41
        );
42
    }
43
44
    /**
45
     * Get class instance
46
     *
47
     * @return mixed
48
     * @throws ComponentException
49
     */
50 692
    public static function getInstance()
51
    {
52 692
        $class = static::class;
53 692
        if (!isset(static::$instances[$class])) {
54 4
            static::$instances[$class] = static::initInstance();
55 4
            if (!static::$instances[$class]) {
56
                throw new ComponentException("Proxy class `$class` is not initialized");
57
            }
58 4
        }
59
60 692
        return static::$instances[$class];
61
    }
62
63
    /**
64
     * Set or replace instance
65
     *
66
     * @param  mixed $instance
67
     * @return void
68
     */
69 671
    public static function setInstance($instance)
70
    {
71 671
        static::$instances[static::class] = $instance;
72 671
    }
73
74
    /**
75
     * Handle dynamic, static calls to the object.
76
     *
77
     * @param  string $method
78
     * @param  array $args
79
     * @return mixed
80
     * @throws CommonException
81
     * @throws ComponentException
82
     */
83 692
    public static function __callStatic($method, $args)
84
    {
85 692
        $instance = static::getInstance();
86
87
        // not need to check method exists, because we can use Nil class or magic methods
88
        /*if (!method_exists($instance, $method)) {
89
            throw new CommonException("Class `". get_class($instance) ."` don't have `$method` method");
90
        }*/
91
92 692
        return $instance->$method(...$args);
93
    }
94
}
95