Skip to content

Commit

Permalink
feat: support for magic methods registered via __get and __isset
Browse files Browse the repository at this point in the history
  • Loading branch information
tcarrio committed Aug 22, 2024
1 parent 929049d commit 4e368d4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Tool/ValueExtractorTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ protected function extractValue(mixed $element, ?string $propertyOrMethod): mixe
return $element->{$propertyOrMethod}();
}

if (isset($element->$propertyOrMethod)) {
return $element->$propertyOrMethod;
}

throw new InvalidPropertyOrMethod(sprintf(
'Method or property "%s" not defined in %s',
$propertyOrMethod,
Expand Down
31 changes: 31 additions & 0 deletions tests/Tool/ValueExtractorTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,35 @@ public function getType(): string

$this->assertSame('works!', $test('testProperty'), 'Could not extract value by property');
}

public function testShouldExtractValueByMagicMethod(): void
{
$test = new class {
use ValueExtractorTrait;

/**
* @return mixed
*/
public function __invoke(string $propertyOrMethod)
{
return $this->extractValue($this, $propertyOrMethod);
}

public function __get(string $name): mixed
{
if ($name === 'magic_property') {
return 'value';
}

return null;
}

public function __isset(string $name): bool
{
return $name === 'magic_property';
}
};

$this->assertSame('value', $test('magic_property'), 'Could not extract value by magic method');
}
}

0 comments on commit 4e368d4

Please sign in to comment.