Skip to content

Commit

Permalink
refactor(expr): use reference time class, cleanup process()
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed Dec 27, 2019
1 parent 2ad504b commit 1ce873d
Showing 1 changed file with 13 additions and 47 deletions.
60 changes: 13 additions & 47 deletions src/Expression.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,14 @@ public static function getDues(array $jobs, $time = null): array
*/
public function isCronDue(string $expr, $time = null): bool
{
list($expr, $times) = $this->process($expr, $time);
$this->checker->setReference(new ReferenceTime($time));

foreach ($expr as $pos => $segment) {
foreach (\explode(' ', $this->normalizeExpr($expr)) as $pos => $segment) {
if ($segment === '*' || $segment === '?') {
continue;
}

if (!$this->checker->checkDue($segment, $pos, $times)) {
if (!$this->checker->checkDue($segment, $pos)) {
return false;
}
}
Expand All @@ -147,7 +147,6 @@ public function isCronDue(string $expr, $time = null): bool
public function filter(array $jobs, $time = null): array
{
$dues = $cache = [];
$time = $this->normalizeTime($time);

foreach ($jobs as $name => $expr) {
$expr = $this->normalizeExpr($expr);
Expand All @@ -164,44 +163,6 @@ public function filter(array $jobs, $time = null): array
return $dues;
}

/**
* Process and prepare input.
*
* @param string $expr
* @param mixed $time
*
* @return array [expr, time]
*/
protected function process(string $expr, $time): array
{
$expr = $this->normalizeExpr($expr);
$expr = \preg_split('~\s+~', $expr); // 14

if (\count($expr) < 5 || \count($expr) > 6) {
throw new \UnexpectedValueException(
'Cron $expr should have 5 or 6 segments delimited by space'
);
}

$time = static::normalizeTime($time);
$times = \array_map('intval', \explode(' ', \date('i G j n w Y t d m N', $time)));

return [$expr, $times];
}

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 normalizeExpr(string $expr): string
{
$expr = \trim($expr);
Expand All @@ -210,10 +171,15 @@ protected function normalizeExpr(string $expr): string
return static::$expressions[$expr];
}

return \str_ireplace(
\array_keys(static::$literals),
\array_values(static::$literals),
$expr
);
$expr = \preg_replace('~\s+~', ' ', \strtr($expr, static::$literals));
$count = \substr_count($expr, ' ');

if ($count < 4 || $count > 5) {
throw new \UnexpectedValueException(
'Cron $expr should have 5 or 6 segments delimited by space'
);
}

return $expr;
}
}

0 comments on commit 1ce873d

Please sign in to comment.