/
TimeRangeRule.php
72 lines (53 loc) · 1.9 KB
/
TimeRangeRule.php
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
70
71
72
<?php declare(strict_types=1);
namespace Shopware\Core\Framework\Rule;
use Shopware\Core\Framework\Log\Package;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
#[Package('services-settings')]
class TimeRangeRule extends Rule
{
final public const RULE_NAME = 'timeRange';
private const TIME_REGEX = '/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/';
protected string $fromTime;
protected string $toTime;
private bool $validationTurnover = false;
private \DateTimeInterface $to;
private \DateTimeInterface $from;
public function match(RuleScope $scope): bool
{
$now = $scope->getCurrentTime();
$this->from = $this->extractTime($this->fromTime, $now);
$this->to = $this->extractTime($this->toTime, $now);
$this->switchValidationIfToIsSmallerThanFrom();
return $this->returnResultWithSightOnValidationTurnover($now);
}
public function getConstraints(): array
{
return [
'toTime' => [new NotBlank(), new Regex(self::TIME_REGEX)],
'fromTime' => [new NotBlank(), new Regex(self::TIME_REGEX)],
];
}
private function extractTime(string $time, \DateTimeImmutable $now): \DateTimeInterface
{
[$hour, $minute] = explode(':', $time);
return $now->setTime((int) $hour, (int) $minute);
}
private function switchValidationIfToIsSmallerThanFrom(): void
{
if ($this->to < $this->from) {
$tmp = $this->from;
$this->from = $this->to;
$this->to = $tmp;
$this->validationTurnover = true;
}
}
private function returnResultWithSightOnValidationTurnover(\DateTimeImmutable $now): bool
{
$result = $this->to >= $now && $this->from <= $now;
if ($this->validationTurnover) {
return !$result;
}
return $result;
}
}