LoggerRegistry   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 2
dl 0
loc 52
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getLogger() 0 4 1
A registerLogChannel() 0 8 1
A registerPsrLogger() 0 6 1
A getLoggerAlias() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leinonen\Yii2Monolog;
6
7
use Yii;
8
use Monolog\Logger;
9
use Psr\Log\LoggerInterface;
10
11
class LoggerRegistry
12
{
13
    /**
14
     * Returns the corresponding logger for the given channelName.
15
     *
16
     * @param string $channelName
17
     *
18
     * @return Logger
19
     */
20 9
    public function getLogger(string $channelName): Logger
21
    {
22 9
        return Yii::$container->get($this->getLoggerAlias($channelName));
23
    }
24
25
    /**
26
     * Registers a new log channel into Yii's DI container.
27
     * The channel will be registered with an alias yii2-monolog.ChannelName.
28
     *
29
     * @param string $channelName
30
     * @param callable $loggerCreationCallable The callable which should return the logger.
31
     */
32 10
    public function registerLogChannel(string $channelName, callable $loggerCreationCallable)
33
    {
34 10
        $serviceName = $this->getLoggerAlias($channelName);
35
36 10
        Yii::$container->setSingleton($serviceName, function () use ($channelName, $loggerCreationCallable) {
37 10
            return $loggerCreationCallable($channelName);
38 10
        });
39 10
    }
40
41
    /**
42
     * Registers the logger to be used with the Psr LoggerInterface.
43
     *
44
     * @param callable $loggerCreationCallable
45
     */
46
    public function registerPsrLogger(callable $loggerCreationCallable)
47
    {
48 10
        Yii::$container->setSingleton(LoggerInterface::class, function () use ($loggerCreationCallable) {
49 4
            return $loggerCreationCallable();
50 10
        });
51 10
    }
52
53
    /**
54
     * @param string $channelName
55
     *
56
     * @return string
57
     */
58 11
    private function getLoggerAlias(string $channelName): string
59
    {
60 11
        return "yii2-monolog.{$channelName}";
61
    }
62
}
63