Singleton::__set()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.2559

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 6
ccs 3
cts 5
cp 0.6
rs 9.4285
cc 2
eloc 3
nc 2
nop 2
crap 2.2559
1
<?php
2
namespace CloudFramework\Patterns;
3
4
5
/**
6
 * Class Singleton
7
 * @package CloudFramework\Patterns
8
 */
9
class Singleton
10
{
11
12
    private static $instance = array();
13
14
    /**
15
     * Singleton instance generator
16
     * @return $this
17
     */
18 2
    public static function getInstance()
19
    {
20 2
        $class = get_called_class();
21 2
        if (!array_key_exists($class, self::$instance) || null === self::$instance[$class]) {
22 1
            $reflectorClass = new \ReflectionClass($class);
23
            try {
24 1
                self::$instance[$class] = $reflectorClass->newInstanceArgs(func_get_args());
25 1
            } catch(\Exception $e) {
26
                syslog(LOG_ERR, $e->getMessage());
27
                throw $e;
28
            }
29 1
        }
30 2
        return self::$instance[$class];
31
    }
32
33
    /**
34
     * Instance generator alias
35
     * @return $this
36
     */
37
    public static function create()
38
    {
39
        return self::getInstance(func_get_args());
40
    }
41
42
    /**
43
     * Magic setter
44
     * @param string $variable
45
     * @param mixed $value
46
     */
47 1
    public function __set($variable, $value)
48
    {
49 1
        if (property_exists($this, $variable)) {
50
            $this->$variable = $value;
51
        }
52 1
    }
53
54
    /**
55
     * Magic getter
56
     * @param string $variable
57
     * @return mixed
58
     */
59
    public function __get($variable)
60
    {
61
        if (property_exists($this, $variable)) {
62
            return $this->$variable;
63
        } else {
64
            return null;
65
        }
66
    }
67
68
    /**
69
     * Prevent the instance from being cloned
70
     * @return void
71
     */
72
    private function __clone() {}
73
74
    public function __toString()
75
    {
76
        $size = round(strlen(print_r($this, true)) / 1024, 4);
77
        return get_class($this) . " " . $size . " Kbytes";
78
    }
79
}
80