Test Failed
Pull Request — master (#1)
by Alex
02:38
created

FactoryLoggerProviderTrait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 18
c 1
b 0
f 0
dl 0
loc 52
rs 10

2 Methods

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