Passed
Push — master ( d47bdf...6296de )
by Kirill
03:33
created

LoggerTrait::allocateLogger()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 3
nc 2
nop 1
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Logger\Traits;
13
14
use Psr\Log\LoggerInterface;
15
use Psr\Log\NullLogger;
16
use Spiral\Core\ContainerScope;
17
use Spiral\Logger\LogsInterface;
18
19
/**
20
 * Logger trait provides access to the logger from the global container scope (if exists).
21
 */
22
trait LoggerTrait
23
{
24
    /** @var LoggerInterface|null @internal */
25
    private $logger = null;
26
27
    /**
28
     * Sets a logger.
29
     *
30
     * @param LoggerInterface $logger
31
     */
32
    public function setLogger(LoggerInterface $logger): void
33
    {
34
        $this->logger = $logger;
35
    }
36
37
    /**
38
     * Get associated or create new instance of LoggerInterface.
39
     *
40
     * @param string $channel
41
     * @return LoggerInterface
42
     */
43
    protected function getLogger(string $channel = null): LoggerInterface
44
    {
45
        if ($channel !== null) {
46
            return $this->allocateLogger($channel);
47
        }
48
49
        if ($this->logger !== null) {
50
            return $this->logger;
51
        }
52
53
        //We are using class name as log channel (name) by default
54
        return $this->logger = $this->allocateLogger(static::class);
55
    }
56
57
    /**
58
     * Create new instance of associated logger (on demand creation).
59
     *
60
     * @param string $channel
61
     * @return LoggerInterface
62
     */
63
    private function allocateLogger(string $channel): LoggerInterface
64
    {
65
        $container = ContainerScope::getContainer();
66
        if (empty($container) || !$container->has(LogsInterface::class)) {
67
            return $this->logger ?? new NullLogger();
68
        }
69
70
        //We are using class name as log channel (name) by default
71
        return $container->get(LogsInterface::class)->getLogger($channel);
72
    }
73
}
74