Completed
Push — master ( fd3130...674c45 )
by John
03:39
created

AbstractFieldParserDate::factory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
ccs 4
cts 4
cp 1
crap 1
1
<?php
2
3
namespace Graze\CiffRenderer\Parser\FieldParser;
4
5
use Graze\CiffRenderer\Parser\FieldParser\FieldParserFixedText;
6
use Graze\CiffRenderer\Parser\FieldParser\FieldParserInterface;
7
use Graze\CiffRenderer\Parser\FieldParser\DateFormatter\DateFormatterFactory;
8
use Graze\CiffRenderer\Exception\UnsupportedDateFormatException;
9
10
abstract class AbstractFieldParserDate extends FieldParserFixedText implements FieldParserInterface
11
{
12
    /**
13
     * @var \DateTimeImmutable
14
     */
15
    protected $dateTimeNow;
16
17
    /**
18
     * @var DateFormatterFactory
19
     */
20
    private $dateFormatterFactory;
21
22
    /**
23
     * @param \DateTimeImmutable $dateTimeNow
24
     * @param DateFormatterFactory $dateFormatterFactory
25
     */
26 16
    public function __construct(\DateTimeImmutable $dateTimeNow, DateFormatterFactory $dateFormatterFactory)
27
    {
28 16
        $this->dateTimeNow = $dateTimeNow;
29 16
        $this->dateFormatterFactory = $dateFormatterFactory;
30 16
    }
31
32
    /**
33
     * @return string
34
     * @throws UnsupportedDateFormatException
35
     */
36 2
    public function getText()
37
    {
38
        try {
39 2
            $dateFormat = $this->getDateFormat();
40 2
            $dateFormatter = $this->dateFormatterFactory->getFormatter($dateFormat);
41 2
            return $dateFormatter->format($this->getDateTime(), $dateFormat);
42
        } catch (\Exception $e) {
43
            throw new UnsupportedDateFormatException($this->getDateFormat(), $e);
44
        }
45
    }
46
47
    /**
48
     * Fetch a DateTime object set to the correct date/time.
49
     *
50
     * @return \DateTimeInterface
51
     */
52
    abstract protected function getDateTime();
53
54
    /**
55
     * @return string
56
     */
57 2
    public function getDateFormat()
58
    {
59 2
        return (string) $this->xmlField->Data->Object->Default;
60
    }
61
62
    /**
63
     * @return FieldParserInterface
64
     */
65 2
    public static function factory()
66
    {
67 2
        return new static(
68 2
            new \DateTimeImmutable(),
69 2
            new DateFormatterFactory()
70 2
        );
71
    }
72
}
73