<?php
final class IntFilter
{
public static function check(int $value, array $options = array())
{
return $value;
}
}
final class StringFilter
{
public static function check(string $value, array $options = array())
{
// Trim
if (false !== ($options['trim'] ?? true)) {
$value = trim($value);
}
$length = mb_strlen($value, '8bit');
// Empty
if (false === ($options['empty'] ?? true)) {
if (0 === $length) {
throw new LengthException('chaine vide !');
}
}
// Min & max length
if (isset($options['max'])) {
$maxLength = IntFilter::check($options['max'], ['min' => 1]);
if ($length > $maxLength) {
throw new LengthException('trop long !');
}
}
if (isset($options['min'])) {
$minLength = IntFilter::check($options['min'], ['min' => 1]);
if ($length < $minLength) {
throw new LengthException('trop court !');
}
}
if (isset($options['startsWith'])) {
$needle = StringFilter::check($options['startsWith']);
if (false === self::startsWith($value, $needle)) {
throw new InvalidArgumentException('mauvais début !');
}
}
if (isset($options['endsWith'])) {
$needle = StringFilter::check($options['endsWith']);
if (false === self::endsWith($value, $needle)) {
throw new InvalidArgumentException('mauvaise fin !');
}
}
return $value;
}
private static function startsWith($haystack, $needle)
{
return $haystack[0] === $needle[0] ? strncmp($haystack, $needle, mb_strlen($needle, '8bit')) === 0 : false;
}
private static function endsWith($haystack, $needle)
{
$length = mb_strlen($needle, '8bit');
$haystack = mb_substr($haystack, -$length);
return $haystack[0] === $needle[0] ? strncmp($haystack, $needle, $length) === 0 : false;
}
}
var_dump(StringFilter::check(' test ', ['endsWith' => 'st']));
- Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.7
- string(4) "test"
preferences:
130.86 ms | 404 KiB | 174 Q