Completed
Push — master ( 3181c3...80f4ac )
by Juuso
10:53
created

LoggerRegistry   A

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