Completed
Push — master ( 23e324...70c101 )
by Martin
03:35
created

Logger::getDateTimeZone()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace Yep\WorkflowLogger;
4
5
use Yep\WorkflowLogger\Exception\WorkflowIsLockedException;
6
use Yep\WorkflowLogger\Formatter\FormatterInterface;
7
8
/**
9
 * Class Logger
10
 *
11
 * @package Yep\WorkflowLogger
12
 * @author  Martin Zeman (Zemistr) <[email protected]>
13
 */
14
class Logger extends \Monolog\Logger implements LoggerInterface
15
{
16
    /**
17
     * Detailed workflow debug information
18
     */
19
    const WORKFLOW = 111;
20
21
    /**
22
     * @var FormatterInterface
23
     */
24
    protected $workflowFormatter;
25
26
    /**
27
     * Logging levels from syslog protocol defined in RFC 5424
28
     *
29
     * @var array $levels Logging levels
30
     */
31
    protected static $levels = [
32
      self::WORKFLOW => 'WORKFLOW',
33
    ];
34
35
    /**
36
     * @var array|Workflow[]
37
     */
38
    protected $workflows = [];
39
40
    /**
41
     * Logger constructor.
42
     *
43
     * @param string             $name
44
     * @param FormatterInterface $formatter
45
     * @param array              $handlers
46
     * @param array              $processors
47
     */
48
    public function __construct(
49
      $name,
50
      FormatterInterface $formatter,
51
      $handlers = [],
52
      $processors = []
53
    ) {
54
        parent::__construct($name, $handlers, $processors);
55
        static::$levels += parent::$levels;
56
        $this->workflowFormatter = $formatter;
57
    }
58
59
    /**
60
     * @return Workflow
61
     */
62
    protected function createWorkflow()
63
    {
64
        return new Workflow(
65
          $this,
66
          $this->workflowFormatter,
67
          $this->getDateTimeZone(),
68
          static::WORKFLOW
69
        );
70
    }
71
72
    /**
73
     * @return \DateTimeZone
74
     */
75
    protected function getDateTimeZone()
76
    {
77
        if (static::$timezone) {
78
            return static::$timezone;
79
        }
80
81
        $timezone = date_default_timezone_get() ?: 'UTC';
82
83
        return static::$timezone = new \DateTimeZone($timezone);
84
    }
85
86
    /**
87
     * @param string|null $key
88
     * @return Workflow
89
     * @throws WorkflowIsLockedException
90
     */
91
    public function workflow($key = null)
92
    {
93
        if ($key === null) {
94
            return $this->createWorkflow();
95
        }
96
97
        if (!isset($this->workflows[$key])) {
98
            $this->workflows[$key] = $this->createWorkflow();
99
        }
100
101
        if ($this->workflows[$key]->isLocked()) {
102
            throw WorkflowIsLockedException::create($key);
103
        }
104
105
        return $this->workflows[$key];
106
    }
107
}
108