LoggerWorker::info()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Derafu: Biblioteca PHP (Núcleo).
7
 * Copyright (C) Derafu <https://www.derafu.org>
8
 *
9
 * Este programa es software libre: usted puede redistribuirlo y/o modificarlo
10
 * bajo los términos de la Licencia Pública General Affero de GNU publicada por
11
 * la Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o
12
 * (a su elección) cualquier versión posterior de la misma.
13
 *
14
 * Este programa se distribuye con la esperanza de que sea útil, pero SIN
15
 * GARANTÍA ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD
16
 * PARA UN PROPÓSITO DETERMINADO. Consulte los detalles de la Licencia Pública
17
 * General Affero de GNU para obtener una información más detallada.
18
 *
19
 * Debería haber recibido una copia de la Licencia Pública General Affero de GNU
20
 * junto a este programa.
21
 *
22
 * En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
23
 */
24
25
namespace Derafu\Lib\Core\Package\Prime\Component\Log\Worker;
26
27
use Derafu\Lib\Core\Foundation\Abstract\AbstractWorker;
28
use Derafu\Lib\Core\Package\Prime\Component\Log\Contract\LoggerWorkerInterface;
29
use Derafu\Lib\Core\Package\Prime\Component\Log\Entity\Caller;
30
use Derafu\Lib\Core\Package\Prime\Component\Log\Entity\Level;
31
use Derafu\Lib\Core\Support\Store\Contract\JournalInterface;
32
use Derafu\Lib\Core\Support\Store\Journal;
33
use Monolog\Formatter\FormatterInterface;
34
use Monolog\Logger;
35
36
/**
37
 * Clase de LoggerServiceInterface con la implementación del sistema de log.
38
 */
39
class LoggerWorker extends AbstractWorker implements LoggerWorkerInterface
40
{
41
    /**
42
     * Instancia del logger de Monolog.
43
     *
44
     * @var Logger
45
     */
46
    private Logger $logger;
47
48
    /**
49
     * Instancia del almacenamiento de los logs.
50
     *
51
     * @var JournalInterface
52
     */
53
    private JournalInterface $journal;
54
55
    /**
56
     * Esquema de la configuración del worker.
57
     *
58
     * @var array
59
     */
60
    protected array $configurationSchema = [
61
        'channel' => [
62
            'types' => 'string',
63
            'default' => 'derafu_lib',
64
        ],
65
    ];
66
67
    /**
68
     * Arreglo con los handlers del logger.
69
     *
70
     * @var array
71
     */
72
    private array $loggerHandlers;
73
74
    /**
75
     * Formateador para los mensajes del log.
76
     *
77
     * @var FormatterInterface|null
78
     */
79
    private ?FormatterInterface $formatter;
80
81
    /**
82
     * Constructor del worker.
83
     *
84
     * @param array $handlers Lista de handlers adicionales.
85
     * @param FormatterInterface|null $formatter Formatter para los logs.
86
     */
87 38
    public function __construct(
88
        array $handlers = [],
89
        ?FormatterInterface $formatter = null,
90
    ) {
91 38
        $this->handlers = $handlers;
92 38
        $this->formatter = $formatter;
93
    }
94
95
    /**
96
     * {@inheritDoc}
97
     */
98 38
    public function getJournal(): JournalInterface
99
    {
100 38
        return $this->journal;
101
    }
102
103
    /**
104
     * {@inheritDoc}
105
     */
106 24
    public function log($level, $message, array $context = []): void
107
    {
108 24
        $level = (new Level($level))->getMonologLevel();
109 24
        $context = $this->normalizeContext($context);
110 24
        $this->getLogger()->log($level, $message, $context);
111
    }
112
113
    /**
114
     * {@inheritDoc}
115
     */
116 1
    public function debug($message, array $context = []): void
117
    {
118 1
        $context = $this->normalizeContext($context);
119 1
        $this->getLogger()->debug($message, $context);
120
    }
121
122
    /**
123
     * {@inheritDoc}
124
     */
125 2
    public function info($message, array $context = []): void
126
    {
127 2
        $context = $this->normalizeContext($context);
128 2
        $this->getLogger()->info($message, $context);
129
    }
130
131
    /**
132
     * {@inheritDoc}
133
     */
134 1
    public function notice($message, array $context = []): void
135
    {
136 1
        $context = $this->normalizeContext($context);
137 1
        $this->getLogger()->notice($message, $context);
138
    }
139
140
    /**
141
     * {@inheritDoc}
142
     */
143 4
    public function warning($message, array $context = []): void
144
    {
145 4
        $context = $this->normalizeContext($context);
146 4
        $this->getLogger()->warning($message, $context);
147
    }
148
149
    /**
150
     * {@inheritDoc}
151
     */
152 6
    public function error($message, array $context = []): void
153
    {
154 6
        $context = $this->normalizeContext($context);
155 6
        $this->getLogger()->error($message, $context);
156
    }
157
158
    /**
159
     * {@inheritDoc}
160
     */
161 1
    public function critical($message, array $context = []): void
162
    {
163 1
        $context = $this->normalizeContext($context);
164 1
        $this->getLogger()->critical($message, $context);
165
    }
166
167
    /**
168
     * {@inheritDoc}
169
     */
170 1
    public function alert($message, array $context = []): void
171
    {
172 1
        $context = $this->normalizeContext($context);
173 1
        $this->getLogger()->alert($message, $context);
174
    }
175
176
    /**
177
     * {@inheritDoc}
178
     */
179 1
    public function emergency($message, array $context = []): void
180
    {
181 1
        $context = $this->normalizeContext($context);
182 1
        $this->getLogger()->emergency($message, $context);
183
    }
184
185
    /**
186
     * Normaliza el contexto del registro de la bitácora.
187
     *
188
     * @param array $context
189
     * @return array
190
     */
191 38
    private function normalizeContext(array $context): array
192
    {
193
        // Se agrega el caller.
194 38
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
195 38
        $context['__caller'] = new Caller(
196 38
            file: $trace[1]['file'] ?? null,
0 ignored issues
show
Bug introduced by
It seems like $trace[1]['file'] ?? null can also be of type null; however, parameter $file of Derafu\Lib\Core\Package\...y\Caller::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

196
            /** @scrutinizer ignore-type */ file: $trace[1]['file'] ?? null,
Loading history...
197 38
            line: $trace[1]['line'] ?? null,
0 ignored issues
show
Bug introduced by
It seems like $trace[1]['line'] ?? null can also be of type null; however, parameter $line of Derafu\Lib\Core\Package\...y\Caller::__construct() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

197
            /** @scrutinizer ignore-type */ line: $trace[1]['line'] ?? null,
Loading history...
198 38
            function: $trace[2]['function'] ?? null,
0 ignored issues
show
Bug introduced by
It seems like $trace[2]['function'] ?? null can also be of type null; however, parameter $function of Derafu\Lib\Core\Package\...y\Caller::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

198
            /** @scrutinizer ignore-type */ function: $trace[2]['function'] ?? null,
Loading history...
199 38
            class: $trace[2]['class'] ?? null,
0 ignored issues
show
Bug introduced by
It seems like $trace[2]['class'] ?? null can also be of type null; however, parameter $class of Derafu\Lib\Core\Package\...y\Caller::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

199
            /** @scrutinizer ignore-type */ class: $trace[2]['class'] ?? null,
Loading history...
200 38
            type: $trace[2]['type'] ?? null
0 ignored issues
show
Bug introduced by
It seems like $trace[2]['type'] ?? null can also be of type null; however, parameter $type of Derafu\Lib\Core\Package\...y\Caller::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

200
            /** @scrutinizer ignore-type */ type: $trace[2]['type'] ?? null
Loading history...
201 38
        );
202
203
        // Entregar el contexto normalizado.
204 38
        return $context;
205
    }
206
207
    /**
208
     * Entrega la instancia del logger asegurándo que esté inicializada.
209
     *
210
     * @return Logger
211
     */
212 38
    private function getLogger(): Logger
213
    {
214 38
        if (!isset($this->logger)) {
215 38
            $this->initialize();
216
        }
217
218 38
        return $this->logger;
219
    }
220
221
    /**
222
     * Inicializa el logger.
223
     *
224
     * @return void
225
     */
226 38
    private function initialize(): void
227
    {
228
        // Crear el logger.
229 38
        $channel = $this->getConfiguration()->get('channel');
230 38
        $this->logger = new Logger($channel);
231
232
        // Crear el procesador de los registros de la bitácora.
233 38
        $processor = new Processor();
234 38
        $this->logger->pushProcessor($processor);
235
236
        // Crear el almacenamiento de los registros de la bitácora.
237 38
        $this->journal = new Journal();
238
239
        // Crear el handler de almacenamiento en memoria de los logs.
240 38
        $journalHandler = new JournalHandler($this->journal);
241 38
        if ($this->formatter !== null) {
242 38
            $journalHandler->setFormatter($this->formatter);
243
        }
244 38
        $this->loggerHandlers[] = $journalHandler;
245
246
        // Agregar los handlers.
247 38
        foreach ($this->loggerHandlers as $handler) {
248 38
            $this->logger->pushHandler($handler);
249
        }
250
    }
251
}
252