diff --git a/README.md b/README.md index 8942f07..188346b 100755 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ use org\example\{Base, Inject, Fixture}; $type= Reflection::type(Fixture::class); +$type->anonymous(); // FALSE $type->name(); // org.example.Fixture $type->declaredName(); // Fixture $type->literal(); // Fixture::class @@ -144,6 +145,7 @@ foreach ($type->methods() as $name => $method) { $method->parameters(); // Parameters $method->parameter(0); // Parameter or NULL $method->closure($instance); // Closure instance + $method->invocable($instance); // Invocable $method->invoke($instance, []); // (method return value) } ``` @@ -175,12 +177,33 @@ foreach ($parameters as $name => $parameter) { } ``` -Packages can be reflected upon by passing namespace names to `Reflection::of()`. +Closure can be reflected upon via the *Invocable* class: ```php use lang\Reflection; -$package= Reflection::of('org.example'); +$invocable= Reflection::invocable('strlen'); + +$invocable->anonymous(); // FALSE +$invocable->name(); // strlen +$invocable->declaredName(); // strlen +$invocable->literal(); // strlen +$invocable->comment(); // (api doc comment) +$invocable->package(); // Package or NULL +$invocable->annotations(); // Annotations +$invocable->annotation(Inject::class); // Annotation or NULL +$invocable->returns(); // Constraint +$invocable->parameters(); // Parameters +$invocable->parameter(0); // Parameter or NULL +$invocable->invoke(['Test']); // strlen("Test") = 4 +``` + +Packages can be reflected upon by passing namespace names to `Reflection::package()`. + +```php +use lang\Reflection; + +$package= Reflection::package('org.example'); $package->name(); // org.example $package->literal(); // 'org\example' diff --git a/src/main/php/lang/Reflection.class.php b/src/main/php/lang/Reflection.class.php index 7c70851..fc63c31 100755 --- a/src/main/php/lang/Reflection.class.php +++ b/src/main/php/lang/Reflection.class.php @@ -1,7 +1,8 @@ = 80000 ? new FromAttributes() : new FromSyntaxTree(); } @@ -34,23 +36,33 @@ public static function meta(): MetaInformation { /** * Returns a reflection type for a given argument. * - * @param string|object|lang.XPClass|lang.reflection.Type|ReflectionClass $arg + * @param string|callable $arg + * @return lang.reflection.Invocable + */ + public static function invocable($arg) { + return $arg instanceof Invocable ? $arg : new Invocable($arg); + } + + /** + * Returns a reflection type for a given argument. + * + * @param string|object $arg * @return lang.reflection.Type * @throws lang.ClassNotFoundException */ public static function type($arg) { if ($arg instanceof XPClass) { return new Type($arg->reflect()); - } else if ($arg instanceof \ReflectionClass) { + } else if ($arg instanceof ReflectionClass) { return new Type($arg); } else if ($arg instanceof Type) { return $arg; } else if (is_object($arg)) { - return new Type(new \ReflectionObject($arg)); + return new Type(new ReflectionObject($arg)); } else { try { - return new Type(new \ReflectionClass(strtr($arg, '.', '\\'))); - } catch (\ReflectionException $e) { + return new Type(new ReflectionClass(strtr($arg, '.', '\\'))); + } catch (ReflectionException $e) { throw new ClassNotFoundException($arg, [ClassLoader::getDefault()]); } } @@ -59,16 +71,16 @@ public static function type($arg) { /** * Returns a reflection package for a given argument. * - * @param string|object|lang.XPClass|lang.reflection.Type|ReflectionClass $arg + * @param string|object $arg * @return lang.reflection.Type * @throws lang.IllegalArgumentException */ public static function package($arg) { if ($arg instanceof XPClass) { return new Package($arg->reflect()->getNamespaceName()); - } else if ($arg instanceof \ReflectionClass) { + } else if ($arg instanceof ReflectionClass || $arg instanceof ReflectionFunction) { return new Package($arg->getNamespaceName()); - } else if ($arg instanceof Type) { + } else if ($arg instanceof Type || $arg instanceof Invocable) { return $arg->package(); } else if (is_object($arg)) { $class= get_class($arg); @@ -86,34 +98,36 @@ public static function package($arg) { } /** - * Creates a new reflection instance, which may either refer to a type - * or to a package. + * Creates a new reflection instance, which may either refer to an invocable, + * a type or to a package. * - * @param string|object|lang.XPClass|lang.reflection.Type|ReflectionClass $arg - * @return lang.reflection.Type|lang.reflection.Package + * @param string|object $arg + * @return lang.reflection.Invocable|lang.reflection.Type|lang.reflection.Package * @throws lang.ClassNotFoundException */ public static function of($arg) { if ($arg instanceof XPClass) { return new Type($arg->reflect()); - } else if ($arg instanceof \ReflectionClass) { + } else if ($arg instanceof ReflectionClass) { return new Type($arg); } else if ($arg instanceof Type) { return $arg; + } else if ($arg instanceof Closure || $arg instanceof ReflectionFunction) { + return new Invocable($arg); } else if (is_object($arg)) { - return new Type(new \ReflectionObject($arg)); + return new Type(new ReflectionObject($arg)); } else { $cl= ClassLoader::getDefault(); $name= strtr($arg, '\\', '.'); if ($cl->providesClass($name)) { - return new Type(new \ReflectionClass($cl->loadClass0($name))); + return new Type(new ReflectionClass($cl->loadClass0($name))); } else if ($cl->providesPackage($name)) { return new Package($name); } try { - return new Type(new \ReflectionClass(strtr($arg, '.', '\\'))); - } catch (\ReflectionException $e) { + return new Type(new ReflectionClass(strtr($arg, '.', '\\'))); + } catch (ReflectionException $e) { throw new ClassNotFoundException($name, [$cl]); } } diff --git a/src/main/php/lang/meta/FromAttributes.class.php b/src/main/php/lang/meta/FromAttributes.class.php index 4c77402..50ed950 100755 --- a/src/main/php/lang/meta/FromAttributes.class.php +++ b/src/main/php/lang/meta/FromAttributes.class.php @@ -1,6 +1,6 @@ annotations($reflect, $reflect); + } + /** @return iterable */ public function ofType($reflect) { return $this->annotations($reflect, $reflect); @@ -52,7 +57,7 @@ public function ofMethod($reflect) { /** @return iterable */ public function ofParameter($method, $reflect) { - return $this->annotations($reflect, $method->getDeclaringClass()); + return $this->annotations($reflect, $method instanceof ReflectionMethod ? $method->getDeclaringClass() : $method); } /** diff --git a/src/main/php/lang/meta/FromSyntaxTree.class.php b/src/main/php/lang/meta/FromSyntaxTree.class.php index 6a1b0a5..7892d40 100755 --- a/src/main/php/lang/meta/FromSyntaxTree.class.php +++ b/src/main/php/lang/meta/FromSyntaxTree.class.php @@ -198,6 +198,11 @@ public function imports($reflect) { return $imports; } + /** @return iterable */ + public function ofInvocable($reflect) { + throw new IllegalStateException('Invocables cannot have annotations in PHP 7'); + } + /** @return iterable */ public function ofType($reflect) { $tree= $this->tree($reflect, $reflect->getFileName()); diff --git a/src/main/php/lang/meta/MetaInformation.class.php b/src/main/php/lang/meta/MetaInformation.class.php index 57f792c..7d18a02 100755 --- a/src/main/php/lang/meta/MetaInformation.class.php +++ b/src/main/php/lang/meta/MetaInformation.class.php @@ -7,7 +7,7 @@ * it to another source otherwise. */ class MetaInformation { - private $annotations; + public $annotations; public function __construct($annotations) { $this->annotations= $annotations; diff --git a/src/main/php/lang/reflection/Invocable.class.php b/src/main/php/lang/reflection/Invocable.class.php new file mode 100755 index 0000000..5b09d70 --- /dev/null +++ b/src/main/php/lang/reflection/Invocable.class.php @@ -0,0 +1,179 @@ +reflect= new ReflectionMethod(...$arg); + $this->receiver= $this->reflect->isStatic() ? null : $receiver ?? $arg[0]; + } else { + $this->reflect= $arg instanceof ReflectionFunctionAbstract ? $arg : new ReflectionFunction($arg); + $this->receiver= $receiver; + } + } + + /** Returns whether this is an anonymous function */ + public function anonymous(): bool { + return + $this->reflect instanceof ReflectionFunction && + (PHP_VERSION_ID < 80200 ? strpos($this->reflect->name, '{closure}') : $this->reflect->isAnonymous()) + ; + } + + /** Returns the name, null for anonymous functions */ + public function name(): ?string { return $this->anonymous() ? null : strtr($this->reflect->name, '\\', '.'); } + + /** Returns type literal (in namespaced form) */ + public function literal(): ?string { return $this->anonymous() ? null : $this->reflect->name; } + + /** Returns declared name (without namespace) */ + public function declaredName(): ?string { return $this->anonymous() ? null : $this->reflect->getShortName(); } + + /** Returns a compound name consisting of `[NAME]()` */ + public function compoundName(): string { + if ($this->reflect instanceof ReflectionMethod) { + return strtr($this->reflect->class.'::'.$this->reflect->name, '\\', '.').'()'; + } else { + return $this->anonymous() ? '{closure}()' : strtr($this->reflect->name, '\\', '.').'()'; + } + } + + /** + * Returns this invocable's package. Anonymous functions are always in the + * top-level package + * + * @return lang.reflection.Package + */ + public function package() { + if (PHP_VERSION_ID < 80200) { + $ns= false === strpos($this->reflect->name, '{closure}') ? $this->reflect->getNamespaceName() : ''; + } else if (PHP_VERSION_ID < 80400) { + $ns= $this->reflect->isAnonymous() ? '' : $this->reflect->getNamespaceName(); + } else { + $ns= $this->reflect->getNamespaceName(); + } + return new Package($ns); + } + + /** + * Returns this functions's doc comment, or NULL if there is none. + * + * @return ?string + */ + public function comment() { + return false === ($c= $this->reflect->getDocComment()) + ? null + : trim(preg_replace('/\n\s+\* ?/', "\n", substr($c, 3, -2))) + ; + } + + /** @return lang.reflection.Annotations */ + public function annotations() { + $this->annotations ?? $this->annotations= Reflection::meta()->annotations->ofInvocable($this->reflect); + return new Annotations($this->annotations); + } + + /** @return ?lang.reflection.Annotation */ + public function annotation(string $type) { + $this->annotations ?? $this->annotations= Reflection::meta()->annotations->ofInvocable($this->reflect); + + $t= strtr($type, '.', '\\'); + return isset($this->annotations[$t]) ? new Annotation($t, $this->annotations[$t]) : null; + } + + /** + * Looks up a parameter + * + * @param int|string $arg Either a position or a name + * @return ?lang.reflection.Parameter + */ + public function parameter($arg) { + if (is_int($arg)) { + $p= $this->reflect->getParameters()[$arg] ?? null; + } else { + $p= null; + foreach ($this->reflect->getParameters() as $parameter) { + if ($arg !== $parameter->name) continue; + $p= $parameter; + break; + } + } + return null === $p ? null : new Parameter($p, $this->reflect); + } + + /** Returns all parameters */ + public function parameters(): Parameters { return new Parameters($this->reflect); } + + /** @return lang.reflection.Constraint */ + public function returns() { + $present= true; + $t= Type::resolve($this->reflect->getReturnType(), [], function($set) use(&$present) { + $present= false; + }); + return new Constraint($t ?? Type::$VAR, $present); + } + + /** + * Invokes this closure + * + * @param var[] $args + * @return var + * @throws lang.reflection.CannotInvoke if prerequisites to the invocation fail + * @throws lang.reflection.InvocationFailed if invocation raises an exception + */ + public function invoke(array $args= []) { + try { + $pass= PHP_VERSION_ID < 80000 && $args ? Routine::pass($this->reflect, $args) : $args; + + if ($this->reflect instanceof ReflectionFunction) { + return $this->reflect->invokeArgs($pass); + } else { + + // TODO: Remove superfluous call to setAccessible() if on PHP8.1+ + // see https://wiki.php.net/rfc/make-reflection-setaccessible-no-op + PHP_VERSION_ID < 80100 && $this->reflect->setAccessible(true); + return $this->reflect->invokeArgs($this->receiver, $pass); + } + } catch (ReflectionException|ArgumentCountError|TypeError $e) { + throw new CannotInvoke($this, $e); + } catch (Throwable $e) { + + // This really should be an ArgumentCountError... + if (0 === strpos($e->getMessage(), 'Unknown named parameter $')) { + throw new CannotInvoke($this, $e); + } + + throw new InvocationFailed($this, $e); + } + } + + /** @return string */ + public function hashCode() { return 'I'.md5($this->compoundName()); } + + /** @return string */ + public function toString() { return nameof($this).'<'.$this->compoundName().'>'; } + + /** + * Compares this member to another value + * + * @param var $value + * @return int + */ + public function compareTo($value) { + return $value instanceof self + ? $this->compoundName() <=> $value->compoundName() + : 1 + ; + } +} \ No newline at end of file diff --git a/src/main/php/lang/reflection/Member.class.php b/src/main/php/lang/reflection/Member.class.php index 568b394..2dcb808 100755 --- a/src/main/php/lang/reflection/Member.class.php +++ b/src/main/php/lang/reflection/Member.class.php @@ -3,7 +3,7 @@ use lang\{XPClass, Reflection, Value}; /** Base class for constants, properties and methods */ -abstract class Member implements Annotated, Value { +abstract class Member implements Annotated, Target, Value { protected $reflect, $annotations; /** diff --git a/src/main/php/lang/reflection/Method.class.php b/src/main/php/lang/reflection/Method.class.php index cfe43da..fdb97d4 100755 --- a/src/main/php/lang/reflection/Method.class.php +++ b/src/main/php/lang/reflection/Method.class.php @@ -21,7 +21,7 @@ class Method extends Routine { public function closure(?object $instance= null) { try { $closure= $this->reflect->getClosure($instance); - } catch (\Throwable $e) { + } catch (Throwable $e) { throw new IllegalArgumentException($e->getMessage()); } @@ -39,6 +39,23 @@ public function closure(?object $instance= null) { return $closure; } + /** + * Returns an invocable + * + * @param ?object $instance + * @return lang.reflection.Invocable + * @throws lang.IllegalArgumentException for incorrect or missing instances + */ + public function invocable(?object $instance= null) { + if ($instance && !($instance instanceof $this->reflect->class)) { + throw new IllegalArgumentException('Instance is not an instance of the class method was declared in'); + } else if (null === $instance && !$this->reflect->isStatic()) { + throw new IllegalArgumentException('Instance cannot be null for non-static methods'); + } + + return new Invocable($this->reflect, $instance); + } + /** * Invokes this method * diff --git a/src/main/php/lang/reflection/Parameter.class.php b/src/main/php/lang/reflection/Parameter.class.php index cb11475..7b40762 100755 --- a/src/main/php/lang/reflection/Parameter.class.php +++ b/src/main/php/lang/reflection/Parameter.class.php @@ -1,5 +1,6 @@ reflect= $reflect; - $this->method= $method ?? $reflect->getDeclaringFunction(); + $this->holder= $holder ?? $reflect->getDeclaringFunction(); } /** Returns parameter name */ @@ -45,7 +46,10 @@ public function default() { if ($this->reflect->isDefaultValueAvailable()) { $value= $this->reflect->getDefaultValue(); if (null === $value) { - $this->annotations ?? $this->annotations= Reflection::meta()->parameterAnnotations($this->method, $this->reflect); + $this->annotations ?? $this->annotations= $this->holder instanceof ReflectionMethod + ? Reflection::meta()->parameterAnnotations($this->holder, $this->reflect) + : Reflection::meta()->annotations->ofParameter($this->holder, $this->reflect) + ; return $this->annotations['Default'][0] ?? null; } return $value; @@ -56,13 +60,19 @@ public function default() { /** @return lang.reflection.Annotations */ public function annotations() { - $this->annotations ?? $this->annotations= Reflection::meta()->parameterAnnotations($this->method, $this->reflect); + $this->annotations ?? $this->annotations= $this->holder instanceof ReflectionMethod + ? Reflection::meta()->parameterAnnotations($this->holder, $this->reflect) + : Reflection::meta()->annotations->ofParameter($this->holder, $this->reflect) + ; return new Annotations($this->annotations); } /** @return ?lang.reflection.Annotation */ public function annotation(string $type) { - $this->annotations ?? $this->annotations= Reflection::meta()->parameterAnnotations($this->method, $this->reflect); + $this->annotations ?? $this->annotations= $this->holder instanceof ReflectionMethod + ? Reflection::meta()->parameterAnnotations($this->holder, $this->reflect) + : Reflection::meta()->annotations->ofParameter($this->holder, $this->reflect) + ; $t= strtr($type, '.', '\\'); return isset($this->annotations[$t]) ? new Annotation($t, $this->annotations[$t]) : null; @@ -73,14 +83,20 @@ public function constraint() { $present= true; // Only use meta information if necessary - $api= function($set) use(&$present, &$names) { - $present= $set; - $names= Reflection::meta()->methodParameterTypes($this->method); - return $names[$this->reflect->getPosition()] ?? null; - }; + if ($this->holder instanceof ReflectionMethod) { + $resolve= Member::resolve($this->reflect); + $api= function($set) use(&$present) { + $present= $set; + $names= Reflection::meta()->methodParameterTypes($this->holder); + return $names[$this->reflect->getPosition()] ?? null; + }; + } else { + $resolve= []; + $api= function($set) use(&$present) { $present= $set; return null; }; + } return new Constraint( - Type::resolve($this->reflect->getType(), Member::resolve($this->reflect), $api) ?? Type::$VAR, + Type::resolve($this->reflect->getType(), $resolve, $api) ?? Type::$VAR, $present ); } diff --git a/src/main/php/lang/reflection/Parameters.class.php b/src/main/php/lang/reflection/Parameters.class.php index 6854099..be7e8d0 100755 --- a/src/main/php/lang/reflection/Parameters.class.php +++ b/src/main/php/lang/reflection/Parameters.class.php @@ -9,11 +9,11 @@ * @test lang.reflection.unittest.MethodsTest */ class Parameters implements \IteratorAggregate { - private $method; + private $holder; - /** @param ReflectionMethod $method */ - public function __construct($method) { - $this->method= $method; + /** @param ReflectionFunctionAbstract $holder */ + public function __construct($holder) { + $this->holder= $holder; } /** @@ -23,7 +23,7 @@ public function __construct($method) { * @return int */ public function size($required= false) { - return $required ? $this->method->getNumberOfRequiredParameters() : $this->method->getNumberOfParameters(); + return $required ? $this->holder->getNumberOfRequiredParameters() : $this->holder->getNumberOfParameters(); } /** @@ -33,8 +33,8 @@ public function size($required= false) { * @return ?lang.reflection.Parameter */ public function at(int $position) { - $list= $this->method->getParameters(); - return isset($list[$position]) ? new Parameter($list[$position], $this->method) : null; + $list= $this->holder->getParameters(); + return isset($list[$position]) ? new Parameter($list[$position], $this->holder) : null; } /** @@ -44,22 +44,22 @@ public function at(int $position) { * @return ?lang.reflection.Parameter */ public function named(string $name) { - foreach ($this->method->getParameters() as $param) { - if ($name === $param->name) return new Parameter($param, $this->method); + foreach ($this->holder->getParameters() as $param) { + if ($name === $param->name) return new Parameter($param, $this->holder); } return null; } /** @return ?lang.reflection.Parameter */ public function first() { - $list= $this->method->getParameters(); - return $list ? new Parameter($list[0], $this->method) : null; + $list= $this->holder->getParameters(); + return $list ? new Parameter($list[0], $this->holder) : null; } /** @return iterable */ public function getIterator(): Traversable { - foreach ($this->method->getParameters() as $parameter) { - yield $parameter->name => new Parameter($parameter, $this->method); + foreach ($this->holder->getParameters() as $parameter) { + yield $parameter->name => new Parameter($parameter, $this->holder); } } @@ -73,16 +73,16 @@ public function getIterator(): Traversable { * @return bool */ public function accept(array $arguments, $count= null): bool { - $parameters= $this->method->getParameters(); + $parameters= $this->holder->getParameters(); if (null !== $count && $count !== sizeof($parameters)) return false; // Only fetch api doc types if necessary $api= function() use(&$i, &$types) { - $types ?? $types= Reflection::meta()->methodParameterTypes($this->method); + $types ?? $types= Reflection::meta()->methodParameterTypes($this->holder); return $types[$i] ?? null; }; - $context= Member::resolve($this->method); + $context= Member::resolve($this->holder); foreach ($parameters as $i => $parameter) { // If a given value is missing check whether parameter is optional diff --git a/src/main/php/lang/reflection/Target.class.php b/src/main/php/lang/reflection/Target.class.php new file mode 100755 index 0000000..7303045 --- /dev/null +++ b/src/main/php/lang/reflection/Target.class.php @@ -0,0 +1,7 @@ +compoundName(), $cause); $this->target= $target; } /** Returns the target member */ - public function target(): Member { return $this->target; } + public function target(): Target { return $this->target; } } \ No newline at end of file diff --git a/src/main/php/lang/reflection/Type.class.php b/src/main/php/lang/reflection/Type.class.php index e8b9427..c2336d2 100755 --- a/src/main/php/lang/reflection/Type.class.php +++ b/src/main/php/lang/reflection/Type.class.php @@ -17,14 +17,23 @@ public function __construct($reflect) { $this->reflect= $reflect; } + /** Returns whether this is an anonymous function */ + public function anonymous(): bool { return $this->reflect->isAnonymous(); } + /** Returns type name (in dotted form) */ - public function name(): string { return strtr($this->reflect->name, '\\', '.'); } + public function name(): ?string { + return $this->reflect->isAnonymous() ? null : strtr($this->reflect->name, '\\', '.'); + } /** Returns declared name (without namespace) */ - public function declaredName(): string { return $this->reflect->getShortName(); } + public function declaredName(): ?string { + return $this->reflect->isAnonymous() ? null : $this->reflect->getShortName(); + } /** Returns type literal (in namespaced form) */ - public function literal(): string { return $this->reflect->name; } + public function literal(): ?string { + return $this->reflect->isAnonymous() ? null : $this->reflect->name; + } /** Returns corresponding lang.XPClass instance */ public function class(): XPClass { return new XPClass($this->reflect); } diff --git a/src/test/php/lang/reflection/unittest/AnonymousClassTest.class.php b/src/test/php/lang/reflection/unittest/AnonymousClassTest.class.php index 7e5205e..03f2ac0 100755 --- a/src/test/php/lang/reflection/unittest/AnonymousClassTest.class.php +++ b/src/test/php/lang/reflection/unittest/AnonymousClassTest.class.php @@ -5,9 +5,24 @@ class AnonymousClassTest { + #[Test] + public function anonymous() { + Assert::true(Reflection::type(new class() { })->anonymous()); + } + #[Test] public function name() { - Assert::equals('class@anonymous', strstr(Reflection::type(new class() { })->name(), "\0", true)); + Assert::null(Reflection::type(new class() { })->name()); + } + + #[Test] + public function literal() { + Assert::null(Reflection::type(new class() { })->literal()); + } + + #[Test] + public function declared_name() { + Assert::null(Reflection::type(new class() { })->declaredName()); } /** @see https://github.com/xp-framework/reflection/issues/33 */ diff --git a/src/test/php/lang/reflection/unittest/InvocableTest.class.php b/src/test/php/lang/reflection/unittest/InvocableTest.class.php new file mode 100755 index 0000000..cbe5303 --- /dev/null +++ b/src/test/php/lang/reflection/unittest/InvocableTest.class.php @@ -0,0 +1,192 @@ + true, null]; + yield [function() { return true; }, null]; + yield [[$this, 'instance'], 'instance']; + yield [[self::class, 'class'], 'class']; + yield [[Closure::class, 'fromCallable'], 'fromCallable']; + yield [Closure::fromCallable('strtoupper'), 'strtoupper']; + yield [new ReflectionFunction('strtoupper'), 'strtoupper']; + } + + #[Test, Values(from: 'callables')] + public function can_create($callable) { + new Invocable($callable); + } + + #[Test, Values(from: 'callables')] + public function name($callable, $expected) { + Assert::equals($expected, (new Invocable($callable))->name()); + } + + #[Test] + public function compound_name_of_function() { + Assert::equals('strlen()', (new Invocable('strlen'))->compoundName()); + } + + #[Test] + public function compound_name_of_instance_method() { + Assert::equals( + 'lang.reflection.unittest.InvocableTest::instance()', + (new Invocable([$this, 'instance']))->compoundName() + ); + } + + #[Test] + public function compound_name_of_class_method() { + Assert::equals( + 'lang.reflection.unittest.InvocableTest::class()', + (new Invocable([self::class, 'class']))->compoundName() + ); + } + + #[Test] + public function global_function() { + $strlen= new Invocable('strlen'); + + Assert::equals('strlen', $strlen->name()); + Assert::equals('strlen', $strlen->literal()); + Assert::equals('strlen', $strlen->declaredName()); + Assert::equals(new Package(''), $strlen->package()); + } + + #[Test] + public function anonymous_function() { + $anonymous= new Invocable(fn() => true); + + Assert::null($anonymous->name()); + Assert::null($anonymous->literal()); + Assert::null($anonymous->declaredName()); + Assert::equals(new Package(''), $anonymous->package()); + } + + #[Test] + public function namespaced_function() { + eval('namespace test; function fixture() { }'); + $namespaced= new Invocable('test\\fixture'); + + Assert::equals('test.fixture', $namespaced->name()); + Assert::equals('test\\fixture', $namespaced->literal()); + Assert::equals('fixture', $namespaced->declaredName()); + Assert::equals(new Package('test'), $namespaced->package()); + } + + #[Test] + public function no_comment() { + Assert::null((new Invocable(fn() => true))->comment()); + } + + #[Test] + public function with_comment() { + Assert::equals('Test', (new Invocable(/** Test */ fn() => true))->comment()); + } + + #[Test, Runtime(php: '>=8.0')] + public function no_annotations() { + Assert::equals([], iterator_to_array((new Invocable(fn() => true))->annotations())); + } + + #[Test, Runtime(php: '>=8.0')] + public function with_annotation() { + $closure= eval('return #[\\test\\Test] fn() => true;'); + Assert::equals('test', (new Invocable($closure))->annotation(Test::class)->name()); + } + + #[Test, Runtime(php: '>=8.0')] + public function with_annotations() { + $closure= eval('return #[\\test\\Test, \\test\\Values] fn() => true;'); + + $annotations= []; + foreach ((new Invocable($closure))->annotations() as $annotation) { + $annotations[]= $annotation->name(); + } + Assert::equals(['test', 'values'], $annotations); + } + + #[Test] + public function empty_parameters() { + $parameters= (new Invocable(fn() => true))->parameters(); + Assert::equals(0, $parameters->size()); + } + + #[Test] + public function parameters() { + $parameters= (new Invocable(fn($name) => true))->parameters(); + Assert::equals(1, $parameters->size()); + } + + #[Test, Values([0, 'name'])] + public function parameter($arg) { + $parameter= (new Invocable(fn($name) => true))->parameter($arg); + Assert::equals('name', $parameter->name()); + Assert::false($parameter->optional()); + } + + #[Test] + public function optional_parameter() { + $parameters= (new Invocable(fn($name= null) => true))->parameters(); + Assert::equals(0, $parameters->size($required= true)); + Assert::equals(1, $parameters->size($required= false)); + } + + #[Test] + public function without_return_type() { + $constraint= (new Invocable(fn($name) => true))->returns(); + Assert::false($constraint->present()); + Assert::equals(Type::$VAR, $constraint->type()); + } + + #[Test] + public function return_type() { + $constraint= (new Invocable(fn($name): bool => true))->returns(); + Assert::true($constraint->present()); + Assert::equals(Primitive::$BOOL, $constraint->type()); + } + + #[Test] + public function invoke() { + $invocable= (new Invocable(fn($name) => strtoupper($name))); + Assert::equals('TEST', $invocable->invoke(['test'])); + } + + #[Test] + public function invoke_named() { + $invocable= (new Invocable(fn($name) => strtoupper($name))); + Assert::equals('TEST', $invocable->invoke(['name' => 'test'])); + } + + #[Test, Expect(CannotInvoke::class)] + public function invoke_missing_argument() { + $invocable= (new Invocable(fn($name) => strtoupper($name))); + $invocable->invoke([]); + } + + #[Test] + public function invoke_instance_method() { + $invocable= new Invocable([$this, 'instance']); + Assert::equals('@test', $invocable->invoke(['Test'])); + } + + #[Test] + public function invoke_class_method() { + $invocable= new Invocable([$this, 'class']); + Assert::equals('@test', $invocable->invoke(['Test'])); + } +} \ No newline at end of file diff --git a/src/test/php/lang/reflection/unittest/MethodsTest.class.php b/src/test/php/lang/reflection/unittest/MethodsTest.class.php index f1bccc2..e3a8371 100755 --- a/src/test/php/lang/reflection/unittest/MethodsTest.class.php +++ b/src/test/php/lang/reflection/unittest/MethodsTest.class.php @@ -206,6 +206,22 @@ public function fixture() { } Assert::equals("Returns the fixture\nor NULL.", $t->method('fixture')->comment()); } + #[Test] + public function closure() { + $t= $this->declare('{ public function fixture($name) { return "@".strtolower($name); } }'); + $closure= $t->method('fixture')->closure($t->newinstance()); + + Assert::equals('@test', $closure('Test')); + } + + #[Test] + public function static_closure() { + $t= $this->declare('{ public static function fixture($name) { return "@".strtolower($name); } }'); + $closure= $t->method('fixture')->closure(null); + + Assert::equals('@test', $closure('Test')); + } + #[Test, Expect(IllegalArgumentException::class)] public function closure_with_missing_instance() { $this->declare('{ public function fixture() { } }')->method('fixture')->closure(null); @@ -216,6 +232,32 @@ public function closure_with_incorrect_instance() { $this->declare('{ public function fixture() { } }')->method('fixture')->closure($this); } + #[Test] + public function invocable() { + $t= $this->declare('{ public function fixture($name) { return "@".strtolower($name); } }'); + $invocable= $t->method('fixture')->invocable($t->newInstance()); + + Assert::equals('@test', $invocable->invoke(['Test'])); + } + + #[Test] + public function static_invocable() { + $t= $this->declare('{ public static function fixture($name) { return "@".strtolower($name); } }'); + $invocable= $t->method('fixture')->invocable(null); + + Assert::equals('@test', $invocable->invoke(['Test'])); + } + + #[Test, Expect(IllegalArgumentException::class)] + public function invocable_with_missing_instance() { + $this->declare('{ public function fixture() { } }')->method('fixture')->invocable(null); + } + + #[Test, Expect(IllegalArgumentException::class)] + public function invocable_with_incorrect_instance() { + $this->declare('{ public function fixture() { } }')->method('fixture')->invocable($this); + } + #[Test] public function hash_code() { $t= $this->declare('{ public function fixture() { } }'); diff --git a/src/test/php/lang/reflection/unittest/ReflectionTest.class.php b/src/test/php/lang/reflection/unittest/ReflectionTest.class.php index 6b58312..368c3b1 100755 --- a/src/test/php/lang/reflection/unittest/ReflectionTest.class.php +++ b/src/test/php/lang/reflection/unittest/ReflectionTest.class.php @@ -1,15 +1,22 @@ true, 'short closure']; + yield [function() { }, 'closure']; + } + + /** @return iterable */ + private function types() { yield [self::class, 'class literal']; yield [nameof($this), 'class name']; yield [$this, 'instance']; @@ -32,12 +39,12 @@ private function packages() { yield [new ReflectionObject($this), 'reflection object']; } - #[Test, Values(from: 'arguments')] - public function of($argument) { - Assert::equals(nameof($this), Reflection::of($argument)->name()); + #[Test, Values(from: 'invocables')] + public function invocable($argument) { + Assert::instance(Invocable::class, Reflection::invocable($argument)); } - #[Test, Values(from: 'arguments')] + #[Test, Values(from: 'types')] public function type($argument) { Assert::equals(nameof($this), Reflection::type($argument)->name()); } @@ -47,6 +54,36 @@ public function package($argument) { Assert::equals(new Package('lang.reflection.unittest'), Reflection::package($argument)); } + #[Test] + public function package_of_closure() { + Assert::equals(new Package(''), Reflection::package(fn() => true)); + } + + #[Test] + public function package_of_invocable() { + Assert::equals(new Package(''), Reflection::package(Reflection::invocable('strlen'))); + } + + #[Test] + public function package_of_function() { + Assert::equals(new Package(''), Reflection::package(new ReflectionFunction('strlen'))); + } + + #[Test, Values(from: 'types')] + public function of($argument) { + Assert::equals(nameof($this), Reflection::of($argument)->name()); + } + + #[Test] + public function of_closure() { + Assert::instance(Invocable::class, Reflection::of(fn() => true)); + } + + #[Test] + public function of_function() { + Assert::instance(Invocable::class, Reflection::of(new ReflectionFunction('strlen'))); + } + #[Test] public function of_package_name() { Assert::instance(Package::class, Reflection::of('lang.reflection.unittest'));