respect-validation/library/Rules/EndsWith.php

83 lines
1.7 KiB
PHP
Raw Normal View History

2011-02-20 19:54:11 +01:00
<?php
2015-06-08 16:47:14 +02:00
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
2011-02-20 19:54:11 +01:00
namespace Respect\Validation\Rules;
use function end;
use function is_array;
use function mb_strlen;
use function mb_strripos;
use function mb_strrpos;
/**
* Validates only if the value is at the end of the input.
*
* @author Alexandre Gomes Gaigalas <alganet@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Hugo Hamon <hugo.hamon@sensiolabs.com>
* @author William Espindola <oi@williamespindola.com.br>
*/
final class EndsWith extends AbstractRule
2011-02-20 19:54:11 +01:00
{
/**
* @var mixed
*/
private $endValue;
/**
* @var bool
*/
private $identical;
2011-02-20 19:54:11 +01:00
/**
* @param mixed $endValue
*/
public function __construct($endValue, bool $identical = false)
2011-02-20 19:54:11 +01:00
{
$this->endValue = $endValue;
$this->identical = $identical;
}
/**
* {@inheritDoc}
*/
public function validate($input): bool
2011-02-20 19:54:11 +01:00
{
if ($this->identical) {
2011-02-20 19:54:11 +01:00
return $this->validateIdentical($input);
}
2015-03-28 12:43:27 +01:00
return $this->validateEquals($input);
2011-02-20 19:54:11 +01:00
}
/**
* @param mixed $input
*/
private function validateEquals($input): bool
2011-02-20 19:54:11 +01:00
{
if (is_array($input)) {
2011-02-20 19:54:11 +01:00
return end($input) == $this->endValue;
}
2015-03-28 12:43:27 +01:00
return mb_strripos($input, $this->endValue) === mb_strlen($input) - mb_strlen($this->endValue);
2011-02-20 19:54:11 +01:00
}
/**
* @param mixed $input
*/
private function validateIdentical($input): bool
2011-02-20 19:54:11 +01:00
{
if (is_array($input)) {
2011-02-20 19:54:11 +01:00
return end($input) === $this->endValue;
}
2015-03-28 12:43:27 +01:00
return mb_strrpos($input, $this->endValue) === mb_strlen($input) - mb_strlen($this->endValue);
2011-02-20 19:54:11 +01:00
}
}