Passed
Pull Request — master (#1)
by Alex
08:35
created

FactoryLoggerProviderTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
eloc 20
c 2
b 0
f 0
dl 0
loc 56
ccs 0
cts 17
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A setLoggerService() 0 3 1
B getLogger() 0 32 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasMonolog\Factory;
6
7
use Laminas\ServiceManager\Exception\ServiceNotCreatedException;
8
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
9
use Laminas\ServiceManager\ServiceLocatorInterface;
10
use Monolog\Logger;
11
use Psr\Log\LoggerInterface;
12
use Psr\Log\NullLogger;
13
14
/**
15
 * Provides service factories the ability to resolve loggers from the container
16
 *
17
 * @author  Alex Patterson <[email protected]>
18
 * @package Arp\LaminasMonolog\Factory
19
 */
20
trait FactoryLoggerProviderTrait
21
{
22
    /**
23
     * @var string
24
     */
25
    protected string $loggerService = Logger::class;
26
27
    /**
28
     * @param ServiceLocatorInterface             $container
29
     * @param LoggerInterface|string|array<mixed> $logger
30
     * @param string                              $serviceName
31
     *
32
     * @return LoggerInterface
33
     *
34
     * @throws ServiceNotCreatedException
35
     */
36
    public function getLogger(ServiceLocatorInterface $container, $logger, string $serviceName): LoggerInterface
37
    {
38
        if (is_string($logger)) {
39
            if (!$container->has($logger)) {
40
                throw new ServiceNotFoundException(
41
                    sprintf('The logger \'%s\' could not be found for service \'%s\'', $logger, $serviceName)
42
                );
43
            }
44
45
            $logger = $container->get($logger);
46
        }
47
48
        if (is_array($logger)) {
49
            $logger = $container->build($this->loggerService, $logger);
50
        }
51
52
        if (null === $logger) {
53
            $logger = new NullLogger();
54
        }
55
56
        if (!$logger instanceof LoggerInterface) {
57
            throw new ServiceNotCreatedException(
58
                sprintf(
59
                    'The resolved logger must be an object of type \'%s\'; \'%s\' provided for service \'%s\'',
60
                    LoggerInterface::class,
61
                    is_object($logger) ? get_class($logger) : gettype($logger),
62
                    $serviceName
63
                )
64
            );
65
        }
66
67
        return $logger;
68
    }
69
70
    /**
71
     * @param string $loggerService
72
     */
73
    public function setLoggerService(string $loggerService): void
74
    {
75
        $this->loggerService = $loggerService;
76
    }
77
}
78