Completed
Push — master ( 40f4e7...541b10 )
by Nikola
02:44
created

ContainerInteropLoggerFactory::prepareHandlers()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5.583

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 5
cts 7
cp 0.7143
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 1
nop 1
crap 5.583
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MonologFactory;
6
7
use Interop\Container\ContainerInterface;
8
use Monolog\Formatter\FormatterInterface;
9
use Monolog\Handler\HandlerInterface;
10
use Monolog\Logger;
11
use MonologFactory\Exception\InvalidArgumentException;
12
use MonologFactory\Exception\InvalidContainerServiceException;
13
14
class ContainerInteropLoggerFactory
15
{
16
    const CONFIG_KEY = 'logger';
17
18
    /**
19
     * @var string
20
     */
21
    protected $name;
22
23
    /**
24
     * @var ContainerInterface
25
     */
26
    protected $container;
27
28
    /**
29
     * @var LoggerFactory
30
     */
31
    private $loggerFactory;
32
33 3
    public function __construct(string $name = 'default')
34
    {
35 3
        $this->name = $name;
36 3
    }
37
38 3
    public function __invoke(ContainerInterface $container) : Logger
39
    {
40 3
        $this->container = $container;
41
42 3
        $loggerConfig = $this->getLoggerConfig($this->name);
43
44 3
        return $this->createLogger($loggerConfig);
45
    }
46
47 1
    public static function __callStatic(string $name, array $arguments) : Logger
48
    {
49 1
        if (0 === count($arguments) || ! ($container = current($arguments)) instanceof ContainerInterface) {
50
            throw new InvalidArgumentException(sprintf(
51
                'The first argument for %s method must be of type %s',
52
                __FUNCTION__,
53
                ContainerInterface::class
54
            ));
55
        }
56
57 1
        return (new static($name))->__invoke($container);
58
    }
59
60 3
    protected function getLoggerConfig(string $loggerName) : array
61
    {
62 3
        $config = $this->container->has('Config') ? $this->container->get('Config') : [];
63 3
        $loggersConfig = $config[self::CONFIG_KEY] ?? [];
64 3
        $loggerConfig = $loggersConfig[$loggerName] ?? [];
65
66 3
        return array_merge(
67
            [
68 3
                'name' => $loggerName,
69
                'handlers' => [],
70
                'processors' => [],
71
            ],
72 3
            $loggerConfig
73
        );
74
    }
75
76 3
    protected function createLogger(array $config) : Logger
77
    {
78 3
        $name = $config['name'];
79 3
        unset($config['name']);
80
81 3
        if (is_array($config['handlers'])) {
82 3
            $config['handlers'] = $this->prepareHandlers($config['handlers']);
83
        }
84
85 3
        if (is_array($config['processors'])) {
86 3
            $config['processors'] = $this->prepareProcessors($config['processors']);
87
        }
88
89 3
        return $this->getLoggerFactory()->createLogger($name, $config);
90
    }
91
92 3
    protected function prepareHandlers(array $handlers) : array
93
    {
94
        return array_map(function ($handler) {
95 2
            if (is_string($handler)) {
96
                return $this->resolveHandler($handler);
97
            }
98
99 2
            if (is_array($handler) && isset($handler['options']['formatter']) && is_string($handler['options']['formatter'])) {
100
                $handler['options']['formatter'] = $this->resolveFormatter($handler['options']['formatter']);
101
            }
102
103 2
            return $handler;
104 3
        }, $handlers);
105
    }
106
107
    protected function prepareProcessors(array $processors) : array
108
    {
109 3
        return array_map(function ($processor) {
110 2
            if (is_string($processor)) {
111
                return $this->resolveProcessor($processor);
112
            }
113
114 2
            return $processor;
115 3
        }, $processors);
116
    }
117
118 View Code Duplication
    protected function resolveHandler(string $handlerName) : HandlerInterface
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
    {
120
        $handler = $this->resolveFromContainer($handlerName);
121
122
        if (null === $handler) {
123
            throw InvalidContainerServiceException::forUnresolved('handler', $handlerName);
124
        }
125
126
        if (! $handler instanceof HandlerInterface) {
127
            throw InvalidContainerServiceException::forInvalid('handler', $handlerName, HandlerInterface::class);
128
        }
129
130
        return $handler;
131
    }
132
133 View Code Duplication
    protected function resolveFormatter(string $formatterName) : FormatterInterface
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
    {
135
        $formatter = $this->resolveFromContainer($formatterName);
136
137
        if (null === $formatter) {
138
            throw InvalidContainerServiceException::forUnresolved('formatter', $formatterName);
139
        }
140
141
        if (! $formatter instanceof FormatterInterface) {
142
            throw InvalidContainerServiceException::forInvalid('formatter', $formatterName, FormatterInterface::class);
143
        }
144
145
        return $formatter;
146
    }
147
148 View Code Duplication
    protected function resolveProcessor(string $processorName) : callable
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
149
    {
150
        $processor = $this->resolveFromContainer($processorName);
151
152
        if (null === $processor) {
153
            throw InvalidContainerServiceException::forUnresolved('processor', $processorName);
154
        }
155
156
        if (! is_callable($processor)) {
157
            throw InvalidContainerServiceException::forInvalid('processor', $processorName, 'callable');
158
        }
159
160
        return $processor;
161
    }
162
163
    final protected function resolveFromContainer(string $serviceOrFactory)
164
    {
165
        if ($this->container->has($serviceOrFactory)) {
166
            return $this->container->get($serviceOrFactory);
167
        }
168
169
        if (class_exists($serviceOrFactory)) {
170
            $factory = new $serviceOrFactory();
171
            return $factory($this->container);
172
        }
173
174
        return null;
175
    }
176
177 3
    final protected function getLoggerFactory() : LoggerFactory
178
    {
179 3
        if (null === $this->loggerFactory) {
180 3
            $this->loggerFactory = new LoggerFactory();
181
        }
182
183 3
        return $this->loggerFactory;
184
    }
185
}
186