-
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
88 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
/* | ||
* This file is part of the PHP-CRON-EXPR package. | ||
* | ||
* (c) Jitendra Adhikari <jiten.adhikary@gmail.com> | ||
* <https://github.com/adhocore> | ||
* | ||
* Licensed under MIT license. | ||
*/ | ||
|
||
namespace Ahc\Cron; | ||
|
||
class ReferenceTime | ||
{ | ||
// The cron parts. (Donot change it) | ||
const MINUTE = 0; | ||
const HOUR = 1; | ||
const MONTHDAY = 2; | ||
const MONTH = 3; | ||
const WEEKDAY = 4; | ||
const YEAR = 5; | ||
|
||
// Meta data parts. | ||
const DAY = 6; | ||
const WEEKDAY1 = 7; | ||
const NUMDAYS = 8; | ||
|
||
/** @var array The data */ | ||
protected $values = []; | ||
|
||
/** @var array The Magic methods */ | ||
protected $methods = []; | ||
|
||
public function __construct($time) | ||
{ | ||
$timestamp = $this->normalizeTime($time); | ||
|
||
$this->values = $this->parse($timestamp); | ||
$this->methods = (new \ReflectionClass($this))->getConstants(); | ||
} | ||
|
||
public function __call(string $method, array $args): int | ||
{ | ||
$method = \preg_replace('/^GET/', '', \strtoupper($method)); | ||
if (isset($this->methods[$method])) { | ||
return $this->values[$this->methods[$method]]; | ||
} | ||
|
||
// @codeCoverageIgnoreStart | ||
throw new \BadMethodCallException("Method '$method' doesnot exist in ReferenceTime."); | ||
// @codeCoverageIgnoreEnd | ||
} | ||
|
||
public function get(int $segment): int | ||
{ | ||
return $this->values[$segment]; | ||
} | ||
|
||
public function isAt($value, $segment): bool | ||
{ | ||
return $this->values[$segment] == $value; | ||
} | ||
|
||
protected function normalizeTime($time): int | ||
{ | ||
if (empty($time)) { | ||
$time = \time(); | ||
} elseif (\is_string($time)) { | ||
$time = \strtotime($time); | ||
} elseif ($time instanceof \DateTime) { | ||
$time = $time->getTimestamp(); | ||
} | ||
|
||
return $time; | ||
} | ||
|
||
protected function parse(int $timestamp): array | ||
{ | ||
$parts = \date('i G j n w Y d N t', $timestamp); | ||
$parts = \explode(' ', $parts); | ||
$parts = \array_map('intval', $parts); | ||
|
||
return $parts; | ||
} | ||
} |