respect-validation/library/Rules/StartsWith.php

90 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
/*
* 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 is_array;
use function is_string;
use function mb_stripos;
use function mb_strpos;
use function reset;
/**
* Validates whether the input starts with a given value.
*
* @author Alexandre Gomes Gaigalas <alganet@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Marcelo Araujo <msaraujo@php.net>
*/
final class StartsWith extends AbstractRule
2011-02-20 19:54:11 +01:00
{
/**
* @var mixed
*/
private $startValue;
/**
* @var bool
*/
private $identical;
2011-02-20 19:54:11 +01:00
/**
* @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;
}
if (is_string($input) && is_string($this->startValue)) {
return mb_stripos($input, $this->startValue) === 0;
}
return false;
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;
}
if (is_string($input) && is_string($this->startValue)) {
return mb_strpos($input, $this->startValue) === 0;
}
return false;
2011-02-20 19:54:11 +01:00
}
}