Completed
Push — master ( 741d83...eb3c74 )
by Michał
02:22
created

Log::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 1
dl 0
loc 14
ccs 11
cts 11
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace BlueRegister;
4
5
use \SimpleLog\LogInterface;
6
7
class Log
8
{
9
    /**
10
     * @var null|LogInterface
11
     */
12
    protected $log;
13
14
    /**
15
     * @param mixed $logObject
16
     * @throws \LogicException
17
     * @throws \InvalidArgumentException
18
     */
19 18
    public function __construct($logObject)
20
    {
21 18
        switch (true) {
22 18
            case $logObject instanceof LogInterface:
23 11
                $this->log = $logObject;
24 11
                break;
25
26 8
            case is_string($logObject):
27 6
                $this->classExists($logObject)
28 4
                    ->createObjectFromString($logObject);
29 2
                break;
30
31 2
            default:
32 2
                $this->logObjectException($logObject);
33 2
        }
34 12
    }
35
36
    /**
37
     * @param string $logObject
38
     * @throws \LogicException
39
     */
40 4
    protected function createObjectFromString($logObject)
41
    {
42 4
        $this->log = new $logObject();
43
44 4
        if (!$this->log instanceof LogInterface) {
45 2
            $message = 'Log should be instance of SimpleLog\LogInterface: ' . get_class($this->log);
46 2
            throw new \LogicException($message);
47
        }
48 2
    }
49
50
    /**
51
     * @param object $logObject
52
     * @throws \LogicException
53
     */
54 2
    protected function logObjectException($logObject)
55
    {
56 2
        $object = 'unknown type';
57
58 2
        if (is_object($logObject)) {
59 2
            $object = get_class($logObject);
60 2
        }
61
62 2
        throw new \LogicException('Cannot create Log instance: ' . $object);
63
    }
64
65
    /**
66
     * check that class exists and throw exception if not
67
     *
68
     * @param string $namespace
69
     * @return $this
70
     * @throws \InvalidArgumentException
71
     */
72 6
    protected function classExists($namespace)
73
    {
74 6
        if (!class_exists($namespace)) {
75 2
            throw new \InvalidArgumentException('Class don\'t exists: ' . $namespace);
76
        }
77
78 4
        return $this;
79
    }
80
81
    /**
82
     * @param string|array $message
83
     * @return $this
84
     */
85 7
    public function makeLog($message)
86
    {
87 7
        if (!is_null($this->log)) {
88 7
            $this->log->makeLog($message);
89 7
        }
90
91 7
        return $this;
92
    }
93
}
94