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

FactoryFormatterProviderTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 14
c 1
b 0
f 0
dl 0
loc 38
ccs 0
cts 11
cp 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A getFormatter() 0 27 5
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 Monolog\Formatter\FormatterInterface;
10
use Psr\Container\ContainerInterface;
11
12
/**
13
 * Trait used to allow factories to resolve a Formatter from configuration options
14
 *
15
 * @author  Alex Patterson <[email protected]>
16
 * @package Arp\LaminasMonolog\Factory
17
 */
18
trait FactoryFormatterProviderTrait
19
{
20
    /**
21
     * @param ContainerInterface        $container
22
     * @param string|FormatterInterface $formatter
23
     * @param string                    $serviceName
24
     *
25
     * @return FormatterInterface
26
     *
27
     * @throws ServiceNotCreatedException
28
     */
29
    private function getFormatter(
30
        ContainerInterface $container,
31
        $formatter,
32
        string $serviceName
33
    ): FormatterInterface {
34
        if (is_string($formatter)) {
35
            if (!$container->has($formatter)) {
36
                throw new ServiceNotFoundException(
37
                    sprintf('The formatter \'%s\' could not be found for service \'%s\'', $formatter, $serviceName)
38
                );
39
            }
40
41
            $formatter = $container->get($formatter);
42
        }
43
44
        if (!$formatter instanceof FormatterInterface) {
45
            throw new ServiceNotCreatedException(
46
                sprintf(
47
                    'The resolved formatter must be an object of type \'%s\'; \'%s\' provided for service \'%s\'',
48
                    FormatterInterface::class,
49
                    is_object($formatter) ? get_class($formatter) : gettype($formatter),
50
                    $serviceName
51
                )
52
            );
53
        }
54
55
        return $formatter;
56
    }
57
}
58