<?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 git.master, git.master_jit, rfc.property-hooks
- string(4) "test"
This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.
Active branches
Archived branches
Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page
preferences:
53.33 ms | 405 KiB | 9 Q