summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/scheduler/src/OneOff.php
blob: ebe945d4dbafc9e227ecef0d5e110f37dfd30baf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

namespace ipl\Scheduler;

use DateTime;
use DateTimeInterface;
use DateTimeZone;
use InvalidArgumentException;
use ipl\Scheduler\Contract\Frequency;

use function ipl\Stdlib\get_php_type;

class OneOff implements Frequency
{
    /** @var DateTimeInterface Start time of this frequency */
    protected $dateTime;

    public function __construct(DateTimeInterface $dateTime)
    {
        $this->dateTime = clone $dateTime;
        $this->dateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
    }

    public function isDue(DateTimeInterface $dateTime): bool
    {
        return ! $this->isExpired($dateTime) && $this->dateTime == $dateTime;
    }

    public function getNextDue(DateTimeInterface $dateTime): DateTimeInterface
    {
        return $this->dateTime;
    }

    public function isExpired(DateTimeInterface $dateTime): bool
    {
        return $this->dateTime < $dateTime;
    }

    public function getStart(): ?DateTimeInterface
    {
        return $this->dateTime;
    }

    public function getEnd(): ?DateTimeInterface
    {
        return $this->getStart();
    }

    public static function fromJson(string $json): Frequency
    {
        $data = json_decode($json, true);
        if (! is_string($data)) {
            throw new InvalidArgumentException(
                sprintf(
                    '%s expects json decoded value to be string, got %s instead',
                    __METHOD__,
                    get_php_type($data)
                )
            );
        }

        return new static(new DateTime($data));
    }

    public function jsonSerialize(): string
    {
        return $this->dateTime->format(static::SERIALIZED_DATETIME_FORMAT);
    }
}