Test Failed
Push — master ( 507036...762659 )
by Julien
21:33
created

Loggers::getFormatter()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 29
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.3541

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 13
c 1
b 0
f 1
nc 10
nop 2
dl 0
loc 29
ccs 11
cts 14
cp 0.7856
crap 6.3541
rs 9.2222
1
<?php
2
3
/**
4
 * This file is part of the Zemit Framework.
5
 *
6
 * (c) Zemit Team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE.txt
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zemit\Logger;
13
14
use Phalcon\Logger\Adapter\AdapterInterface;
15
use Phalcon\Logger\Adapter\Noop;
16
use Phalcon\Logger\Adapter\Stream;
17
use Phalcon\Logger\Adapter\Syslog;
18
use Phalcon\Logger\Formatter\AbstractFormatter;
19
use Phalcon\Logger\Formatter\FormatterInterface;
20
use Phalcon\Logger\Formatter\Line;
21
use Phalcon\Logger\Logger;
22
use Phalcon\Logger\LoggerInterface;
23
use Zemit\Support\Options\Options;
24
25
class Loggers
26
{
27
    use Options;
28
    
29
    /**
30
     * An array to store logger objects
31
     * 
32
     * @var LoggerInterface[] $loggers
33
     */
34
    public array $loggers = [];
35
    
36
    /**
37
     * Gets a formatter based on the provided formatter name and options.
38
     *
39
     * @param string|null $formatter The name of the formatter to retrieve. Defaults to 'line'.
40
     * @param array $options The options for the formatter.
41
     * @return FormatterInterface The retrieved formatter.
42
     * @throws \Exception If the specified formatter is not defined.
43
     */
44 2
    public function getFormatter(?string $formatter = null, array $options = []): FormatterInterface
45
    {
46 2
        $formatter ??= 'line';
47 2
        $formatters = $this->getOption('formatters') ?? [];
48
        
49
        // Formatter must be defined
50 2
        if (!isset($formatters[$formatter])) {
51
            throw new \Exception('Logger formatter `' . $formatter . '` is not defined.');
52
        }
53
        
54
        // Formatter Instance
55 2
        $formatter = new $formatters[$formatter]();
56 2
        assert($formatter instanceof FormatterInterface);
57
        
58
        // Date Format
59 2
        if ($formatter instanceof AbstractFormatter) {
60 2
            if (isset($options['dateFormat'])) {
61
                $formatter->setDateFormat($options['date']);
62
            }
63
        }
64
        
65
        // Line Format
66 2
        if ($formatter instanceof Line) {
67 2
            if (isset($options['format'])) {
68
                $formatter->setFormat($options['format']);
69
            }
70
        }
71
        
72 2
        return $formatter;
73
    }
74
    
75
    /**
76
     * Returns an array of logger adapters based on the given drivers, formatter, and options.
77
     *
78
     * @param string|array|null $loggerDrivers The logger drivers to use. Defaults to null.
79
     * @param array $options The options to configure the adapters. Defaults to an empty array.
80
     * @param FormatterInterface|null $formatter The formatter to attach to the adapters. Defaults to null.
81
     * @return array The array of logger adapters.
82
     * @throws \Exception If a logger driver adapter is not defined.
83
     */
84 2
    public function getAdapters(string|array|null $loggerDrivers = null, array $options = [], FormatterInterface $formatter = null): array
85
    {
86 2
        $drivers = $this->getOption('drivers') ?? [];
87
        
88 2
        $formatter ??= $this->getFormatter();
89
        
90 2
        $ret = [];
91 2
        $loggerDrivers = is_array($loggerDrivers)? $loggerDrivers : explode(',', $loggerDrivers ?? 'noop');
92 2
        foreach ($loggerDrivers as $loggerDriver) {
93 2
            if (!isset($drivers[$loggerDriver])) {
94
                throw new \Exception('Logger driver adapter `' . $loggerDriver . '` is not defined.');
95
            }
96
            
97 2
            $adapterClass = $drivers[$loggerDriver];
98
            
99
            // Stream
100 2
            if ($adapterClass === Stream::class) {
101 2
                $adapter = new Stream($options['path'] . $options['filename'], $options['options'] ?? []);
102
            }
103
            
104
            // Syslog
105 2
            if ($adapterClass === Syslog::class) {
106
                $adapter = new Syslog($loggerDriver, $options['options'] ?? []);
107
            }
108
            
109
            // Noop
110 2
            if ($adapterClass === Noop::class) {
111
                $adapter = new Noop();
112
            }
113
            
114
            // Others
115 2
            $adapter ??= new $drivers[$loggerDriver]($options['options'] ?? []);
116 2
            assert($adapter instanceof AdapterInterface);
117
            
118
            // Attach Formatter
119 2
            $adapter->setFormatter($formatter);
120
            
121
            // Add Adapter
122 2
            $ret [$loggerDriver] = $adapter;
123
        }
124
        
125 2
        return $ret;
126
    }
127
    
128
    /**
129
     * Loads a logger with the given name.
130
     *
131
     * @param string $name The name of the logger to load.
132
     * @return LoggerInterface The loaded logger.
133
     * @throws \Exception
134
     */
135 2
    public function load(string $name): LoggerInterface
136
    {
137 2
        $defaultConfig = $this->getOption('default') ?? [];
138 2
        $loggersConfig = $this->getOption('loggers') ?? [];
139 2
        $loggerConfig = $loggersConfig[$name] ?? [];
140 2
        $options = [
141 2
            'driver' => $loggerConfig['driver'] ?? $defaultConfig['driver'] ?? 'noop',
142 2
            'formatter' => $loggerConfig['formatter'] ?? $defaultConfig['formatter'] ?? 'line',
143 2
            'path' => $loggerConfig['path'] ?? $defaultConfig['path'] ?? null,
144 2
            'filename' => $loggerConfig['filename'] ?? $defaultConfig['filename'] ?? 'default.log',
145 2
            'date' => $loggerConfig['date'] ?? $defaultConfig['date'] ?? 'c',
146 2
            'format' => $loggerConfig['format'] ?? $defaultConfig['format'] ?? null,
147 2
            'options' => $loggerConfig['options'] ?? $defaultConfig['options'] ?? [],
148 2
        ];
149
        
150
        // get formatter
151 2
        $formatter = $this->getFormatter($options['formatter']);
152
        
153
        // get adapters
154 2
        $adapters = $this->getAdapters($options['driver'], $options, $formatter);
155
        
156 2
        $logger = new Logger($name, $adapters);
157 2
        $this->set($name, $logger);
158 2
        return $logger;
159
    }
160
    
161
    /**
162
     * Retrieves a logger with the given name.
163
     *
164
     * @param string $name The name of the logger to retrieve.
165
     * @return LoggerInterface The retrieved logger.
166
     * @throws \Exception If the logger cannot be loaded.
167
     */
168 2
    public function get(string $name): LoggerInterface
169
    {
170 2
        if (isset($this->loggers[$name])) {
171
            return $this->loggers[$name];
172
        }
173
        
174 2
        return $this->load($name);
175
    }
176
    
177
    /**
178
     * Sets a logger with the given name.
179
     *
180
     * @param string $name The name of the logger to set.
181
     * @param LoggerInterface $logger The logger to set.
182
     * @return void
183
     */
184 2
    public function set(string $name, LoggerInterface $logger): void
185
    {
186 2
        $this->loggers[$name] = $logger;
187
    }
188
}
189