respect-validation/library/Rules/Type.php

87 lines
1.9 KiB
PHP
Raw Normal View History

2015-02-02 13:50:17 +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);
2015-02-02 13:50:17 +01:00
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\ComponentException;
use function array_keys;
use function gettype;
use function implode;
use function is_callable;
use function sprintf;
2015-02-02 13:50:17 +01:00
/**
* Validates the type of input.
*
* @author Gabriel Caruso <carusogabriel34@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Paul Karikari <paulkarikari1@gmail.com>
*/
final class Type extends AbstractRule
2015-02-02 13:50:17 +01:00
{
/**
* Collection of available types for validation.
*
*/
private const AVAILABLE_TYPES = [
2015-06-08 16:47:14 +02:00
'array' => 'array',
'bool' => 'boolean',
'boolean' => 'boolean',
'callable' => 'callable',
'double' => 'double',
'float' => 'double',
'int' => 'integer',
'integer' => 'integer',
'null' => 'NULL',
'object' => 'object',
'resource' => 'resource',
'string' => 'string',
2015-10-18 03:44:47 +02:00
];
2015-02-02 13:50:17 +01:00
/**
* Type to validate input against.
*
* @var string
*/
private $type;
/**
* Initializes the rule.
*
* @throws ComponentException When $type is not a valid one
*/
public function __construct(string $type)
2015-02-02 13:50:17 +01:00
{
if (!isset(self::AVAILABLE_TYPES[$type])) {
throw new ComponentException(
sprintf(
'"%s" is not a valid type (Available: %s)',
$type,
implode(', ', array_keys(self::AVAILABLE_TYPES))
)
);
2015-02-02 13:50:17 +01:00
}
$this->type = $type;
}
/**
* {@inheritDoc}
*/
public function validate($input): bool
2015-02-02 13:50:17 +01:00
{
if ($this->type === 'callable') {
2015-02-02 13:50:17 +01:00
return is_callable($input);
}
return self::AVAILABLE_TYPES[$this->type] === gettype($input);
2015-02-02 13:50:17 +01:00
}
}