1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Arp\DateTime; |
||
6 | |||
7 | use Arp\DateTime\Exception\DateTimeZoneFactoryException; |
||
8 | |||
9 | final class DateTimeZoneFactory implements DateTimeZoneFactoryInterface |
||
10 | { |
||
11 | /** |
||
12 | * @var class-string<\DateTimeZone> |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
13 | */ |
||
14 | private string $dateTimeZoneClassName; |
||
15 | |||
16 | /** |
||
17 | * @throws DateTimeZoneFactoryException |
||
18 | */ |
||
19 | public function __construct(string $dateTimeZoneClassName = null) |
||
20 | { |
||
21 | $dateTimeZoneClassName ??= \DateTimeZone::class; |
||
22 | if (!is_a($dateTimeZoneClassName, \DateTimeZone::class, true)) { |
||
23 | throw new DateTimeZoneFactoryException( |
||
24 | sprintf( |
||
25 | 'The \'dateTimeZoneClassName\' parameter must be a class name that implements \'%s\'', |
||
26 | \DateTimeZone::class |
||
27 | ) |
||
28 | ); |
||
29 | } |
||
30 | $this->dateTimeZoneClassName = $dateTimeZoneClassName; |
||
31 | } |
||
32 | |||
33 | /** |
||
34 | * @throws DateTimeZoneFactoryException |
||
35 | */ |
||
36 | public function createDateTimeZone(string $spec): \DateTimeZone |
||
37 | { |
||
38 | try { |
||
39 | /** @throws \Exception */ |
||
40 | return new $this->dateTimeZoneClassName($spec); |
||
41 | } catch (\Exception $e) { |
||
42 | throw new DateTimeZoneFactoryException( |
||
43 | sprintf('Failed to create a valid \DateTimeZone instance using \'%s\'', $spec), |
||
44 | $e->getCode(), |
||
45 | $e |
||
46 | ); |
||
47 | } |
||
48 | } |
||
49 | } |
||
50 |