Skip to content

Commit

Permalink
Type: added allows()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Sep 20, 2021
1 parent 35c3660 commit 2c8d162
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Utils/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,4 +177,23 @@ public function isClass(): bool
{
return $this->single && !Reflection::isBuiltinType($this->types[0]);
}


/**
* Verifies type compatibility. For example, it checks if a value of a certain type could be passed as a parameter.
*/
public function allows(string $type): bool
{
if ($this->types === ['mixed']) {
return true;
}
return Arrays::every((self::fromString($type))->types, function ($testedType) {
$builtin = Reflection::isBuiltinType($testedType);
return Arrays::some($this->types, function ($currentType) use ($testedType, $builtin) {
return $builtin
? strcasecmp($currentType, $testedType) === 0
: is_a($testedType, $currentType, true);
});
});
}
}
57 changes: 57 additions & 0 deletions tests/Utils/Type.allows.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

/**
* Test: Nette\Utils\Type::allows()
*/

declare(strict_types=1);

use Nette\Utils\Type;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


class Foo
{
}

class FooChild extends Foo
{
}


$type = Type::fromString('string');
Assert::true($type->allows('string'));
Assert::false($type->allows('null'));
Assert::false($type->allows('string|null'));
Assert::false($type->allows('Foo'));
Assert::false($type->allows('FooChild'));
Assert::false($type->allows('Foo|FooChild'));


$type = Type::fromString('string|null');
Assert::true($type->allows('string'));
Assert::true($type->allows('null'));
Assert::true($type->allows('string|null'));
Assert::false($type->allows('Foo'));
Assert::false($type->allows('FooChild'));
Assert::false($type->allows('Foo|FooChild'));


$type = Type::fromString('string|Foo');
Assert::true($type->allows('string'));
Assert::false($type->allows('null'));
Assert::false($type->allows('string|null'));
Assert::true($type->allows('Foo'));
Assert::true($type->allows('FooChild'));
Assert::true($type->allows('Foo|FooChild'));


$type = Type::fromString('mixed');
Assert::true($type->allows('string'));
Assert::true($type->allows('null'));
Assert::true($type->allows('string|null'));
Assert::true($type->allows('Foo'));
Assert::true($type->allows('FooChild'));
Assert::true($type->allows('Foo|FooChild'));

0 comments on commit 2c8d162

Please sign in to comment.