respect-validation/library/Rules/StartsWith.php

84 lines
1.8 KiB
PHP
Raw Normal View History

2011-02-20 19:54:11 +01:00
<?php
2015-06-08 16:47:14 +02:00
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
2011-02-20 19:54:11 +01:00
namespace Respect\Validation\Rules;
use function is_array;
use function mb_detect_encoding;
use function mb_stripos;
use function mb_strpos;
use function reset;
/**
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Marcelo Araujo <msaraujo@php.net>
*/
2011-02-20 19:54:11 +01:00
class StartsWith extends AbstractRule
{
/**
* @var mixed
*/
2011-02-20 19:54:11 +01:00
public $startValue;
/**
* @var bool
*/
2011-02-20 19:54:11 +01:00
public $identical;
/**
* @param mixed $startValue
*/
public function __construct($startValue, bool $identical = false)
2011-02-20 19:54:11 +01:00
{
$this->startValue = $startValue;
$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);
}
2011-04-04 20:07:12 +02:00
return $this->validateEquals($input);
2011-02-20 19:54:11 +01:00
}
/**
* @param mixed $input
*/
protected 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 reset($input) == $this->startValue;
}
return mb_stripos($input, $this->startValue, 0, mb_detect_encoding($input)) === 0;
2011-02-20 19:54:11 +01:00
}
/**
* @param mixed $input
*/
protected 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 reset($input) === $this->startValue;
}
return mb_strpos($input, $this->startValue, 0, mb_detect_encoding($input)) === 0;
2011-02-20 19:54:11 +01:00
}
}