Completed
Push — master ( 6306cb...ea9893 )
by Nikola
02:46
created

ContainerInteropLoggerFactory::resolveFormatter()   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 10
    public function __construct(string $name = 'default')
34
    {
35 10
        $this->name = $name;
36 10
    }
37
38 10
    public function __invoke(ContainerInterface $container) : Logger
39
    {
40 10
        $this->container = $container;
41
42 10
        $loggerConfig = $this->getLoggerConfig($this->name);
43
44 10
        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 10
    protected function getLoggerConfig(string $loggerName) : array
61
    {
62 10
        $config = [];
63 10
        foreach (['config', 'Config'] as $configServiceName) {
64 10
            if ($this->container->has($configServiceName)) {
65 10
                $config = $this->container->get($configServiceName);
66 10
                break;
67
            }
68
        }
69
        
70 10
        $loggerConfig = $config[self::CONFIG_KEY][$loggerName] ?? [];
71
72 10
        return array_merge(
73
            [
74 10
                'name' => $loggerName,
75
                'handlers' => [],
76
                'processors' => [],
77
            ],
78 10
            $loggerConfig
79
        );
80
    }
81
82 10
    protected function createLogger(array $config) : Logger
83
    {
84 10
        $name = $config['name'];
85 10
        unset($config['name']);
86
87 10
        if (is_array($config['handlers'])) {
88 10
            $config['handlers'] = $this->prepareHandlers($config['handlers']);
89
        }
90
91 8
        if (is_array($config['processors'])) {
92 8
            $config['processors'] = $this->prepareProcessors($config['processors']);
93
        }
94
95 7
        return $this->getLoggerFactory()->createLogger($name, $config);
96
    }
97
98 10
    protected function prepareHandlers(array $handlers) : array
99
    {
100
        return array_map(function ($handler) {
101 9
            if (is_string($handler)) {
102 4
                return $this->resolveHandler($handler);
103
            }
104
105 8
            if (is_array($handler) && isset($handler['options']['formatter']) && is_string($handler['options']['formatter'])) {
106 4
                $handler['options']['formatter'] = $this->resolveFormatter($handler['options']['formatter']);
107
            }
108
109 7
            return $handler;
110 10
        }, $handlers);
111
    }
112
113
    protected function prepareProcessors(array $processors) : array
114
    {
115 8
        return array_map(function ($processor) {
116 6
            if (is_string($processor)) {
117 4
                return $this->resolveProcessor($processor);
118
            }
119
120 2
            return $processor;
121 8
        }, $processors);
122
    }
123
124 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...
125
    {
126 4
        $handler = $this->resolveFromContainer($handlerName);
127
128 4
        if (null === $handler) {
129 1
            throw InvalidContainerServiceException::forUnresolved('handler', $handlerName);
130
        }
131
132 3
        if (! $handler instanceof HandlerInterface) {
133
            throw InvalidContainerServiceException::forInvalid('handler', $handlerName, HandlerInterface::class);
134
        }
135
136 3
        return $handler;
137
    }
138
139 4 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...
140
    {
141 4
        $formatter = $this->resolveFromContainer($formatterName);
142
143 4
        if (null === $formatter) {
144 1
            throw InvalidContainerServiceException::forUnresolved('formatter', $formatterName);
145
        }
146
147 3
        if (! $formatter instanceof FormatterInterface) {
148
            throw InvalidContainerServiceException::forInvalid('formatter', $formatterName, FormatterInterface::class);
149
        }
150
151 3
        return $formatter;
152
    }
153
154 4 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...
155
    {
156 4
        $processor = $this->resolveFromContainer($processorName);
157
158 4
        if (null === $processor) {
159 1
            throw InvalidContainerServiceException::forUnresolved('processor', $processorName);
160
        }
161
162 3
        if (! is_callable($processor)) {
163
            throw InvalidContainerServiceException::forInvalid('processor', $processorName, 'callable');
164
        }
165
166 3
        return $processor;
167
    }
168
169 6
    final protected function resolveFromContainer(string $serviceOrFactory)
170
    {
171 6
        if ($this->container->has($serviceOrFactory)) {
172 3
            return $this->container->get($serviceOrFactory);
173
        }
174
175 6
        if (class_exists($serviceOrFactory)) {
176 3
            $factory = new $serviceOrFactory();
177 3
            return $factory($this->container);
178
        }
179
180 3
        return null;
181
    }
182
183 7
    final protected function getLoggerFactory() : LoggerFactory
184
    {
185 7
        if (null === $this->loggerFactory) {
186 7
            $this->loggerFactory = new LoggerFactory();
187
        }
188
189 7
        return $this->loggerFactory;
190
    }
191
}
192