Passed
Pull Request — master (#11)
by Alex
02:52
created

DateTimeZoneFactory::createDateTimeZone()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 17
rs 9.9
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\DateTime;
6
7
use Arp\DateTime\Exception\DateTimeZoneFactoryException;
8
9
/**
10
 * @author  Alex Patterson <[email protected]>
11
 * @package Arp\DateTime
12
 */
13
final class DateTimeZoneFactory implements DateTimeZoneFactoryInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    private string $dateTimeZoneClassName;
19
20
    /**
21
     * @param string|null $dateTimeZoneClassName
22
     *
23
     * @throws DateTimeZoneFactoryException
24
     */
25
    public function __construct(string $dateTimeZoneClassName = null)
26
    {
27
        $dateTimeZoneClassName ??= \DateTimeZone::class;
28
        if (!is_a($dateTimeZoneClassName, \DateTimeZone::class, true)) {
29
            throw new DateTimeZoneFactoryException(
30
                sprintf(
31
                    'The \'dateTimeZoneClassName\' parameter must be a class name that implements \'%s\'',
32
                    \DateTimeZone::class
33
                )
34
            );
35
        }
36
        $this->dateTimeZoneClassName = $dateTimeZoneClassName;
37
    }
38
39
    /**
40
     * @param string $spec The date time zone specification
41
     *
42
     * @return \DateTimeZone
43
     *
44
     * @throws DateTimeZoneFactoryException If the \DateTimeZone cannot be created
45
     */
46
    public function createDateTimeZone(string $spec): \DateTimeZone
47
    {
48
        try {
49
            /** @var \DateTimeZone $dateTimeZone */
50
            /** @noinspection PhpUnnecessaryLocalVariableInspection */
51
            /** @noinspection OneTimeUseVariablesInspection */
52
            $dateTimeZone = new $this->dateTimeZoneClassName($spec);
53
            return $dateTimeZone;
54
        } catch (\Exception $e) {
55
            throw new DateTimeZoneFactoryException(
56
                sprintf(
57
                    'Failed to create a valid \DateTimeZone instance using \'%s\': %s',
58
                    $spec,
59
                    $e->getMessage()
60
                ),
61
                $e->getCode(),
62
                $e
63
            );
64
        }
65
    }
66
}
67