Completed
Push — master ( 63b008...c83e20 )
by Nikola
04:25
created

ContainerInteropLoggerFactory::resolveHandler()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 14
Ratio 100 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 14
loc 14
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
crap 3.0261
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 7
    public function __construct(string $name = 'default')
34
    {
35 7
        $this->name = $name;
36 7
    }
37
38 7
    public function __invoke(ContainerInterface $container) : Logger
39
    {
40 7
        $this->container = $container;
41
42 7
        $loggerConfig = $this->getLoggerConfig($this->name);
43
44 7
        return $this->createLogger($loggerConfig);
45
    }
46
47 2
    public static function __callStatic(string $name, array $arguments) : Logger
48
    {
49 2
        if (0 === count($arguments) || ! ($container = current($arguments)) instanceof ContainerInterface) {
50 1
            throw new InvalidArgumentException(sprintf(
51 1
                'The first argument for %s method must be of type %s',
52 1
                __METHOD__,
53 1
                ContainerInterface::class
54
            ));
55
        }
56
57 1
        return (new static($name))->__invoke($container);
58
    }
59
60 7
    protected function getLoggerConfig(string $loggerName) : array
61
    {
62 7
        $config = $this->container->has('Config') ? $this->container->get('Config') : [];
63 7
        $loggersConfig = $config[self::CONFIG_KEY] ?? [];
64 7
        $loggerConfig = $loggersConfig[$loggerName] ?? [];
65
66 7
        return array_merge(
67
            [
68 7
                'name' => $loggerName,
69
                'handlers' => [],
70
                'processors' => [],
71
            ],
72 7
            $loggerConfig
73
        );
74
    }
75
76 7
    protected function createLogger(array $config) : Logger
77
    {
78 7
        $name = $config['name'];
79 7
        unset($config['name']);
80
81 7
        if (is_array($config['handlers'])) {
82 7
            $config['handlers'] = $this->prepareHandlers($config['handlers']);
83
        }
84
85 6
        if (is_array($config['processors'])) {
86 6
            $config['processors'] = $this->prepareProcessors($config['processors']);
87
        }
88
89 6
        return $this->getLoggerFactory()->createLogger($name, $config);
90
    }
91
92 7
    protected function prepareHandlers(array $handlers) : array
93
    {
94
        return array_map(function ($handler) {
95 6
            if (is_string($handler)) {
96 4
                return $this->resolveHandler($handler);
97
            }
98
99 5
            if (is_array($handler) && isset($handler['options']['formatter']) && is_string($handler['options']['formatter'])) {
100 3
                $handler['options']['formatter'] = $this->resolveFormatter($handler['options']['formatter']);
101
            }
102
103 5
            return $handler;
104 7
        }, $handlers);
105
    }
106
107
    protected function prepareProcessors(array $processors) : array
108
    {
109 6
        return array_map(function ($processor) {
110 5
            if (is_string($processor)) {
111 3
                return $this->resolveProcessor($processor);
112
            }
113
114 2
            return $processor;
115 6
        }, $processors);
116
    }
117
118 4 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 4
        $handler = $this->resolveFromContainer($handlerName);
121
122 4
        if (null === $handler) {
123 1
            throw InvalidContainerServiceException::forUnresolved('handler', $handlerName);
124
        }
125
126 3
        if (! $handler instanceof HandlerInterface) {
127
            throw InvalidContainerServiceException::forInvalid('handler', $handlerName, HandlerInterface::class);
128
        }
129
130 3
        return $handler;
131
    }
132
133 3 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 3
        $formatter = $this->resolveFromContainer($formatterName);
136
137 3
        if (null === $formatter) {
138
            throw InvalidContainerServiceException::forUnresolved('formatter', $formatterName);
139
        }
140
141 3
        if (! $formatter instanceof FormatterInterface) {
142
            throw InvalidContainerServiceException::forInvalid('formatter', $formatterName, FormatterInterface::class);
143
        }
144
145 3
        return $formatter;
146
    }
147
148 3 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 3
        $processor = $this->resolveFromContainer($processorName);
151
152 3
        if (null === $processor) {
153
            throw InvalidContainerServiceException::forUnresolved('processor', $processorName);
154
        }
155
156 3
        if (! is_callable($processor)) {
157
            throw InvalidContainerServiceException::forInvalid('processor', $processorName, 'callable');
158
        }
159
160 3
        return $processor;
161
    }
162
163 4
    final protected function resolveFromContainer(string $serviceOrFactory)
164
    {
165 4
        if ($this->container->has($serviceOrFactory)) {
166 3
            return $this->container->get($serviceOrFactory);
167
        }
168
169 4
        if (class_exists($serviceOrFactory)) {
170 3
            $factory = new $serviceOrFactory();
171 3
            return $factory($this->container);
172
        }
173
174 1
        return null;
175
    }
176
177 6
    final protected function getLoggerFactory() : LoggerFactory
178
    {
179 6
        if (null === $this->loggerFactory) {
180 6
            $this->loggerFactory = new LoggerFactory();
181
        }
182
183 6
        return $this->loggerFactory;
184
    }
185
}
186