2012-07-22 15:17:31 +02:00
|
|
|
<?php
|
2015-06-08 16:47:14 +02:00
|
|
|
|
2015-06-08 17:09:25 +02:00
|
|
|
/*
|
2023-02-17 05:13:51 +01:00
|
|
|
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
|
|
|
|
* SPDX-License-Identifier: MIT
|
2015-06-08 17:09:25 +02:00
|
|
|
*/
|
|
|
|
|
2017-11-19 19:01:31 +01:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2012-07-22 15:17:31 +02:00
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
2018-05-24 07:47:09 +02:00
|
|
|
use Respect\Validation\Exceptions\ComponentException;
|
2020-07-21 22:54:41 +02:00
|
|
|
|
2018-06-07 06:18:23 +02:00
|
|
|
use function is_null;
|
|
|
|
use function mb_strlen;
|
2019-02-17 19:41:55 +01:00
|
|
|
use function mb_substr;
|
2018-06-07 06:18:23 +02:00
|
|
|
use function preg_match;
|
|
|
|
use function sprintf;
|
2012-07-22 15:17:31 +02:00
|
|
|
|
2018-06-07 06:18:23 +02:00
|
|
|
/**
|
|
|
|
* Validate numbers in any base, even with non regular bases.
|
|
|
|
*
|
|
|
|
* @author Carlos André Ferrari <caferrari@gmail.com>
|
|
|
|
* @author Henrique Moody <henriquemoody@gmail.com>
|
|
|
|
* @author William Espindola <oi@williamespindola.com.br>
|
|
|
|
*/
|
|
|
|
final class Base extends AbstractRule
|
2012-07-22 15:17:31 +02:00
|
|
|
{
|
2018-06-07 06:18:23 +02:00
|
|
|
/**
|
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
private $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var int
|
|
|
|
*/
|
|
|
|
private $base;
|
2012-07-22 15:17:31 +02:00
|
|
|
|
2018-06-07 06:18:23 +02:00
|
|
|
/**
|
|
|
|
* Initializes the Base rule.
|
|
|
|
*/
|
2019-02-09 13:42:51 +01:00
|
|
|
public function __construct(int $base, ?string $chars = null)
|
2012-07-22 15:17:31 +02:00
|
|
|
{
|
2013-01-14 22:55:03 +01:00
|
|
|
if (!is_null($chars)) {
|
|
|
|
$this->chars = $chars;
|
|
|
|
}
|
2012-07-22 15:17:31 +02:00
|
|
|
|
2016-10-30 10:44:52 +01:00
|
|
|
$max = mb_strlen($this->chars);
|
2018-06-07 06:18:23 +02:00
|
|
|
if ($base > $max) {
|
2018-05-24 07:47:09 +02:00
|
|
|
throw new ComponentException(sprintf('a base between 1 and %s is required', $max));
|
2013-01-14 22:55:03 +01:00
|
|
|
}
|
2012-07-22 15:17:31 +02:00
|
|
|
$this->base = $base;
|
|
|
|
}
|
|
|
|
|
2018-06-07 06:18:23 +02:00
|
|
|
/**
|
2019-04-05 14:33:00 +02:00
|
|
|
* {@inheritDoc}
|
2018-06-07 06:18:23 +02:00
|
|
|
*/
|
2018-01-28 15:41:31 +01:00
|
|
|
public function validate($input): bool
|
2012-07-22 15:17:31 +02:00
|
|
|
{
|
2016-10-30 10:44:52 +01:00
|
|
|
$valid = mb_substr($this->chars, 0, $this->base);
|
2013-01-14 22:55:03 +01:00
|
|
|
|
2020-07-21 22:54:41 +02:00
|
|
|
return (bool) preg_match('@^[' . $valid . ']+$@', (string) $input);
|
2012-07-22 15:17:31 +02:00
|
|
|
}
|
|
|
|
}
|