Skip to content

Commit

Permalink
[bug] support arguments with "self" typehint
Browse files Browse the repository at this point in the history
  • Loading branch information
kbond committed Mar 26, 2022
1 parent a3ff9ac commit 3eb5356
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Callback/Argument.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,20 @@ public function type(): ?string
*/
public function types(): array
{
return \array_map(static function(\ReflectionNamedType $type) { return $type->getName(); }, $this->reflectionTypes());
return \array_map(
function(\ReflectionNamedType $type) {
if ('self' !== $name = $type->getName()) {
return $name;
}

if (!$class = $this->parameter->getDeclaringClass()) {
throw new \LogicException('Unable to parse context of "self" typehint.');
}

return $class->name;
},
$this->reflectionTypes()
);
}

public function hasType(): bool
Expand Down
34 changes: 34 additions & 0 deletions tests/CallbackTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,26 @@ public function argument_allows(): void
$this->assertFalse($callback2->argument(0)->allows(new Object3()));
}

/**
* @test
*/
public function self_parameter_type(): void
{
$callback = Callback::createFor(Object6::closureSelf());

$this->assertSame(Object6::class, $callback->argument(0)->type());

$this->assertTrue($callback->argument(0)->supports(Object6::class));
$this->assertTrue($callback->argument(0)->supports(Object7::class));
$this->assertFalse($callback->argument(0)->supports(Object5::class));
$this->assertFalse($callback->argument(0)->supports('int'));

$this->assertTrue($callback->argument(0)->allows(new Object6()));
$this->assertTrue($callback->argument(0)->allows(new Object7()));
$this->assertFalse($callback->argument(0)->allows(new Object5()));
$this->assertFalse($callback->argument(0)->allows(6));
}

/**
* @test
*/
Expand Down Expand Up @@ -674,3 +694,17 @@ public function __toString(): string
function test_function()
{
}

class Object6
{
public static function closureSelf(): \Closure
{
return function(self $object) {
return $object;
};
}
}

class Object7 extends Object6
{
}

0 comments on commit 3eb5356

Please sign in to comment.