Skip to content

Repository files navigation

Callback Validator

Validates callback signatures against a prototype.

Status

Build StatusScrutinizer Code QualityCode Coverage

Usage

// Create a prototype function (can be any callable)$prototype = function (A$a, B$b, $c): ?string {};
// Validate that callables match the prototype$tests = [
$prototype, // truefunction (A$a, B$b, $c) {}, // false - return type does not matchfunction ($a, $b, $c): ?string {}, // true - arguments are contravariantfunction (A$a, B$b): ?string {}, // true - extra args don't cause errorsfunction (A$a, B$b, $c, $d): ?string {}, // false - Insufficient args cause an errorfunction (C$a, B$b, $c): ?string {}, // true if C is a supertype of A, false otherwisefunction (SuperTypeOfA$a, B$b, $c): ?string {}, // truefunction (A$a, B$b, $c): string {}, // true - return types are covariant
];
// Create a type from a prototype$type = CallbackType::createFromCallable($prototype);
run_tests($type, $tests);
// ...or create a type by hand for more granular control over variance rules$type = newCallbackType(
newReturnType(BuiltInTypes::STRING, ReturnType::NULLABLE | ReturnType::COVARIANT),
newParameterType('a', A::class),
newParameterType('b', B::class),
newParameterType('c')
);
run_tests($type, $tests);
functionrun_tests(CallbackType$type, array$tests)
{
foreach ($testsas$test) {
if ($type->isSatisfiedBy($test)) {
echo"pass\n";
} else {
// CallbackType implements __toString() for easy inspectionsecho CallbackType::createFromCallable($test) . " does not satisfy {$type}\n";
}
}
}

TODO

  • Lots more tests
  • Explain (text explanation of why callback does not validate)

About

Tools for validating callback signatures in PHP

Resources

Stars

43 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages