FactoryFormatterProviderTrait::getFormatter()   A
last analyzed

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 6
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\ContainerExceptionInterface;
11
use Psr\Container\ContainerInterface;
12
use Psr\Container\NotFoundExceptionInterface;
13
14
trait FactoryFormatterProviderTrait
15
{
16
    /**
17
     * @throws ServiceNotCreatedException
18
     * @throws ContainerExceptionInterface
19
     * @throws NotFoundExceptionInterface
20
     */
21
    private function getFormatter(
22
        ContainerInterface $container,
23
        string|FormatterInterface $formatter,
24
        string $serviceName
25
    ): FormatterInterface {
26
        if (is_string($formatter)) {
27
            if (!$container->has($formatter)) {
28
                throw new ServiceNotFoundException(
29
                    sprintf('The formatter \'%s\' could not be found for service \'%s\'', $formatter, $serviceName)
30
                );
31
            }
32
33
            $formatter = $container->get($formatter);
34
        }
35
36
        if (!$formatter instanceof FormatterInterface) {
37
            throw new ServiceNotCreatedException(
38
                sprintf(
39
                    'The resolved formatter must be an object of type \'%s\'; \'%s\' provided for service \'%s\'',
40
                    FormatterInterface::class,
41
                    is_object($formatter) ? get_class($formatter) : gettype($formatter),
42
                    $serviceName
43
                )
44
            );
45
        }
46
47
        return $formatter;
48
    }
49
}
50