Passed
Pull Request — master (#2)
by Alex
07:25
created

DateTimeStrategyFactory   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 3
eloc 15
c 2
b 0
f 0
dl 0
loc 36
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 24 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasDateTime\Factory\Hydrator\Strategy;
6
7
use Arp\LaminasFactory\AbstractFactory;
8
use Laminas\Hydrator\Strategy\DateTimeFormatterStrategy;
9
use Laminas\Hydrator\Strategy\Exception\InvalidArgumentException;
10
use Laminas\ServiceManager\Exception\ServiceNotCreatedException;
11
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
12
use Psr\Container\ContainerInterface;
13
14
/**
15
 * @author  Alex Patterson <[email protected]>
16
 * @package Arp\LaminasDateTime\Factory\Hydrator\Strategy
17
 */
18
final class DateTimeStrategyFactory extends AbstractFactory
19
{
20
    /**
21
     * @param ContainerInterface        $container
22
     * @param string                    $requestedName
23
     * @param array<string, mixed>|null $options
24
     *
25
     * @return DateTimeFormatterStrategy
26
     *
27
     * @throws ServiceNotCreatedException
28
     * @throws ServiceNotFoundException
29
     */
30
    public function __invoke(
31
        ContainerInterface $container,
32
        string $requestedName,
33
        array $options = null
34
    ): DateTimeFormatterStrategy {
35
        $options = $options ?? $this->getServiceOptions($container, $requestedName);
36
37
        $format = $options['format'] ?? null;
38
        if (null === $format) {
39
            throw new ServiceNotCreatedException(
40
                sprintf(
41
                    'The required \'format\' configuration option is missing for service \'%s\'',
42
                    $requestedName
43
                )
44
            );
45
        }
46
47
        try {
48
            return new DateTimeFormatterStrategy($format, $options['timezone'] ?? null, $options['fallback'] ?? false);
49
        } catch (InvalidArgumentException $e) {
50
            throw new ServiceNotCreatedException(
51
                sprintf('Failed to create date time strategy \'%s\': %s', $requestedName, $e->getMessage()),
52
                $e->getCode(),
53
                $e
54
            );
55
        }
56
    }
57
}
58