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

DateTimeStrategyFactory::__invoke()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 24
rs 9.7998
cc 3
nc 3
nop 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