respect-validation/library/Rules/StartsWith.php

60 lines
1.4 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;
/**
* @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
{
public $startValue;
2011-02-20 19:54:11 +01:00
public $identical;
public function __construct($startValue, $identical = false)
2011-02-20 19:54:11 +01:00
{
$this->startValue = $startValue;
$this->identical = $identical;
}
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
}
protected function validateEquals($input)
{
if (is_array($input)) {
2011-02-20 19:54:11 +01:00
return reset($input) == $this->startValue;
}
return 0 === mb_stripos($input, $this->startValue, 0, mb_detect_encoding($input));
2011-02-20 19:54:11 +01:00
}
protected function validateIdentical($input)
{
if (is_array($input)) {
2011-02-20 19:54:11 +01:00
return reset($input) === $this->startValue;
}
return 0 === mb_strpos($input, $this->startValue, 0, mb_detect_encoding($input));
2011-02-20 19:54:11 +01:00
}
}