Passed
Pull Request — master (#7)
by Alex
08:15
created

DateIntervalFactory::createDateInterval()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 7
c 1
b 1
f 0
dl 0
loc 9
rs 10
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\DateIntervalFactoryException;
8
9
/**
10
 * Factory class used as a service to create \DateInterval instances.
11
 *
12
 * @author  Alex Patterson <[email protected]>
13
 * @package Arp\DateTime
14
 */
15
class DateIntervalFactory implements DateIntervalFactoryInterface
16
{
17
    /**
18
     * Create a new DateInterval instance using the provided $spec.
19
     *
20
     * @param string $spec The specification of the interval.
21
     *
22
     * @return \DateInterval
23
     *
24
     * @throws DateIntervalFactoryException  If the date interval cannot be created.
25
     */
26
    public function createDateInterval(string $spec): \DateInterval
27
    {
28
        try {
29
            return new \DateInterval($spec);
30
        } catch (\Throwable $e) {
31
            throw new DateIntervalFactoryException(
32
                sprintf('Failed to create a valid \DateInterval instance using \'%s\': %s', $spec, $e->getMessage()),
33
                $e->getCode(),
34
                $e
35
            );
36
        }
37
    }
38
39
    /**
40
     * Perform a diff of two dates and return the \DateInterval
41
     *
42
     * @param \DateTimeInterface $origin    The origin date
43
     * @param \DateTimeInterface $target    The date to compare to
44
     * @param bool               $absolute  If the interval is negative, should it be forced to be a positive value?
45
     *
46
     * @return \DateInterval
47
     *
48
     * @throws DateIntervalFactoryException If the date diff cannot be performed
49
     */
50
    public function diff(\DateTimeInterface $origin, \DateTimeInterface $target, bool $absolute = false): \DateInterval
51
    {
52
        $dateInterval = $origin->diff($target, $absolute);
53
54
        if (false === $dateInterval || !$dateInterval instanceof \DateInterval) {
55
            throw new DateIntervalFactoryException(
56
                'Failed to create valid \DateInterval while performing date diff'
57
            );
58
        }
59
60
        return $dateInterval;
61
    }
62
}
63