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

FactoryFormatterProviderTrait::getFormatter()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 27
ccs 0
cts 11
cp 0
rs 9.5222
cc 5
nc 5
nop 3
crap 30
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