1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Respect/Validation. |
5
|
|
|
* |
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
15
|
|
|
|
16
|
|
|
use Respect\Validation\Exceptions\ComponentException; |
17
|
|
|
use function array_values; |
18
|
|
|
use function count; |
19
|
|
|
use function is_array; |
20
|
|
|
use function is_string; |
21
|
|
|
use function sprintf; |
22
|
|
|
use function str_split; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Validates whether the input is sorted in a certain order or not. |
26
|
|
|
* |
27
|
|
|
* @author Henrique Moody <[email protected]> |
28
|
|
|
* @author Mikhail Vyrtsev <[email protected]> |
29
|
|
|
*/ |
30
|
|
|
final class Sorted extends AbstractRule |
31
|
|
|
{ |
32
|
|
|
public const ASCENDING = 'ASC'; |
33
|
|
|
public const DESCENDING = 'DESC'; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var string |
37
|
|
|
*/ |
38
|
|
|
private $direction; |
39
|
|
|
|
40
|
2 |
|
public function __construct(string $direction) |
41
|
|
|
{ |
42
|
2 |
|
if ($direction !== self::ASCENDING && $direction !== self::DESCENDING) { |
43
|
1 |
|
throw new ComponentException( |
44
|
1 |
|
sprintf('Direction should be either "%s" or "%s"', self::ASCENDING, self::DESCENDING) |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
$this->direction = $direction; |
49
|
1 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritdoc} |
53
|
|
|
*/ |
54
|
18 |
|
public function validate($input): bool |
55
|
|
|
{ |
56
|
18 |
|
if (!is_array($input) && !is_string($input)) { |
57
|
|
|
return false; |
58
|
|
|
} |
59
|
|
|
|
60
|
18 |
|
$values = $this->getValues($input); |
61
|
18 |
|
$count = count($values); |
62
|
18 |
|
for ($position = 1; $position < $count; ++$position) { |
63
|
15 |
|
if (!$this->isSorted($values[$position], $values[$position - 1])) { |
64
|
10 |
|
return false; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
9 |
|
return true; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param mixed $current |
73
|
|
|
* @param mixed $last |
74
|
|
|
*/ |
75
|
15 |
|
private function isSorted($current, $last): bool |
76
|
|
|
{ |
77
|
15 |
|
if ($this->direction === self::ASCENDING) { |
78
|
9 |
|
return $current > $last; |
79
|
|
|
} |
80
|
|
|
|
81
|
7 |
|
return $current < $last; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* @param string|mixed[] $input |
86
|
|
|
* |
87
|
|
|
* @return mixed[] |
88
|
|
|
*/ |
89
|
18 |
|
private function getValues($input): array |
90
|
|
|
{ |
91
|
18 |
|
if (is_array($input)) { |
92
|
11 |
|
return array_values($input); |
93
|
|
|
} |
94
|
|
|
|
95
|
7 |
|
return str_split($input); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|