respect-validation/library/Rules/Sorted.php

95 lines
2 KiB
PHP
Raw Normal View History

2017-06-29 04:18:02 +02:00
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
2017-06-29 04:18:02 +02:00
*/
declare(strict_types=1);
2017-06-29 04:18:02 +02:00
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\ComponentException;
use function array_values;
use function count;
use function is_array;
use function is_string;
use function sprintf;
use function str_split;
/**
* Validates whether the input is sorted in a certain order or not.
*
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Mikhail Vyrtsev <reeywhaar@gmail.com>
*/
final class Sorted extends AbstractRule
2017-06-29 04:18:02 +02:00
{
public const ASCENDING = 'ASC';
public const DESCENDING = 'DESC';
/**
* @var string
*/
private $direction;
2017-06-29 14:03:50 +02:00
public function __construct(string $direction)
2017-06-29 04:42:29 +02:00
{
if ($direction !== self::ASCENDING && $direction !== self::DESCENDING) {
throw new ComponentException(
sprintf('Direction should be either "%s" or "%s"', self::ASCENDING, self::DESCENDING)
);
}
$this->direction = $direction;
2017-06-29 04:42:29 +02:00
}
2017-06-29 04:18:02 +02:00
/**
* {@inheritDoc}
*/
public function validate($input): bool
2017-06-29 04:18:02 +02:00
{
if (!is_array($input) && !is_string($input)) {
return false;
2017-11-12 14:21:46 +01:00
}
$values = $this->getValues($input);
$count = count($values);
for ($position = 1; $position < $count; ++$position) {
if (!$this->isSorted($values[$position], $values[$position - 1])) {
return false;
2017-11-12 14:21:46 +01:00
}
2017-06-29 04:42:29 +02:00
}
2017-11-12 14:21:46 +01:00
2017-06-29 04:42:29 +02:00
return true;
2017-06-29 04:18:02 +02:00
}
/**
* @param mixed $current
* @param mixed $last
*/
private function isSorted($current, $last): bool
{
if ($this->direction === self::ASCENDING) {
return $current > $last;
}
return $current < $last;
}
/**
* @param string|mixed[] $input
*
* @return mixed[]
*/
private function getValues($input): array
{
if (is_array($input)) {
return array_values($input);
}
return str_split($input);
}
2017-06-29 04:18:02 +02:00
}