Skip to content

Commit

Permalink
Remove some magic from TypeValidator logic and OptionsResolver type v…
Browse files Browse the repository at this point in the history
…erify logic
  • Loading branch information
drealecs authored and nicolas-grekas committed Jul 13, 2020
1 parent 0ab7e5a commit cba9d94
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
32 changes: 22 additions & 10 deletions OptionsResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,26 @@
*/
class OptionsResolver implements Options
{
private const VALIDATION_FUNCTIONS = [
'bool' => 'is_bool',
'boolean' => 'is_bool',
'int' => 'is_int',
'integer' => 'is_int',
'long' => 'is_int',
'float' => 'is_float',
'double' => 'is_float',
'real' => 'is_float',
'numeric' => 'is_numeric',
'string' => 'is_string',
'scalar' => 'is_scalar',
'array' => 'is_array',
'iterable' => 'is_iterable',
'countable' => 'is_countable',
'callable' => 'is_callable',
'object' => 'is_object',
'resource' => 'is_resource',
];

/**
* The names of all defined options.
*/
Expand Down Expand Up @@ -110,12 +130,6 @@ class OptionsResolver implements Options

private $parentsOptions = [];

private static $typeAliases = [
'boolean' => 'bool',
'integer' => 'int',
'double' => 'float',
];

/**
* Sets the default value of a given option.
*
Expand Down Expand Up @@ -995,8 +1009,6 @@ public function offsetGet($option, bool $triggerDeprecation = true)
$invalidTypes = [];

foreach ($this->allowedTypes[$option] as $type) {
$type = self::$typeAliases[$type] ?? $type;

if ($valid = $this->verifyTypes($type, $value, $invalidTypes)) {
break;
}
Expand All @@ -1007,7 +1019,7 @@ public function offsetGet($option, bool $triggerDeprecation = true)
$fmtAllowedTypes = implode('" or "', $this->allowedTypes[$option]);
$fmtProvidedTypes = implode('|', array_keys($invalidTypes));
$allowedContainsArrayType = \count(array_filter($this->allowedTypes[$option], static function ($item) {
return '[]' === substr(self::$typeAliases[$item] ?? $item, -2);
return '[]' === substr($item, -2);
})) > 0;

if (\is_array($value) && $allowedContainsArrayType) {
Expand Down Expand Up @@ -1135,7 +1147,7 @@ private function verifyTypes(string $type, $value, array &$invalidTypes, int $le
return $valid;
}

if (('null' === $type && null === $value) || (\function_exists($func = 'is_'.$type) && $func($value)) || $value instanceof $type) {
if (('null' === $type && null === $value) || (isset(self::VALIDATION_FUNCTIONS[$type]) ? self::VALIDATION_FUNCTIONS[$type]($value) : $value instanceof $type)) {
return true;
}

Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"require": {
"php": "^7.2.5",
"symfony/deprecation-contracts": "^2.1",
"symfony/polyfill-php73": "~1.0",
"symfony/polyfill-php80": "^1.15"
},
"autoload": {
Expand Down

0 comments on commit cba9d94

Please sign in to comment.