ReferenceTime::get()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the PHP-CRON-EXPR package.
7
 *
8
 * (c) Jitendra Adhikari <[email protected]>
9
 *     <https://github.com/adhocore>
10
 *
11
 * Licensed under MIT license.
12
 */
13
14
namespace Ahc\Cron;
15
16
/**
17
 * @method int minute()
18
 * @method int hour()
19
 * @method int monthDay()
20
 * @method int month()
21
 * @method int weekDay()  0 based day of week.
22
 * @method int year()
23
 * @method int day()
24
 * @method int weekDay1() 1 based day of week.
25
 * @method int numDays()  Number of days in the month.
26
 */
27
class ReferenceTime
28
{
29
    // The cron parts. (Donot change it)
30
    const MINUTE   = 0;
31
    const HOUR     = 1;
32
    const MONTHDAY = 2;
33
    const MONTH    = 3;
34
    const WEEKDAY  = 4;
35
    const YEAR     = 5;
36
37
    // Meta data parts.
38
    const DAY      = 6;
39
    const WEEKDAY1 = 7;
40
    const NUMDAYS  = 8;
41
42
    /** @var array The data */
43
    protected $values = [];
44
45
    /** @var array The Magic methods */
46
    protected $methods = [];
47
48
    public function __construct($time)
49
    {
50
        $timestamp = $this->normalizeTime($time);
51
52
        $this->values  = $this->parse($timestamp);
53
        $this->methods = (new \ReflectionClass($this))->getConstants();
54
    }
55
56
    public function __call(string $method, array $args): int
57
    {
58
        $method = \preg_replace('/^GET/', '', \strtoupper($method));
59
        if (isset($this->methods[$method])) {
60
            return $this->values[$this->methods[$method]];
61
        }
62
63
        // @codeCoverageIgnoreStart
64
        throw new \BadMethodCallException("Method '$method' doesnot exist in ReferenceTime.");
65
        // @codeCoverageIgnoreEnd
66
    }
67
68
    public function get(int $segment): int
69
    {
70
        return $this->values[$segment];
71
    }
72
73
    public function isAt($value, $segment): bool
74
    {
75
        return $this->values[$segment] == $value;
76
    }
77
78
    protected function normalizeTime($time): int
79
    {
80
        if (empty($time)) {
81
            $time = \time();
82
        } elseif (\is_string($time)) {
83
            $time = \strtotime($time);
84
        } elseif ($time instanceof \DateTime) {
85
            $time = $time->getTimestamp();
86
        }
87
88
        return $time;
89
    }
90
91
    protected function parse(int $timestamp): array
92
    {
93
        $parts = \date('i G j n w Y d N t', $timestamp);
94
        $parts = \explode(' ', $parts);
95
        $parts = \array_map('intval', $parts);
96
97
        return $parts;
98
    }
99
}
100