From 4e368d4a59d2e520c0aa7d30ad68936c1855e374 Mon Sep 17 00:00:00 2001 From: Tom Carrio Date: Thu, 22 Aug 2024 16:23:13 -0400 Subject: [PATCH] feat: support for magic methods registered via __get and __isset Ref: #125 --- src/Tool/ValueExtractorTrait.php | 4 ++++ tests/Tool/ValueExtractorTraitTest.php | 31 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/Tool/ValueExtractorTrait.php b/src/Tool/ValueExtractorTrait.php index 44c4222..185eba1 100644 --- a/src/Tool/ValueExtractorTrait.php +++ b/src/Tool/ValueExtractorTrait.php @@ -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, diff --git a/tests/Tool/ValueExtractorTraitTest.php b/tests/Tool/ValueExtractorTraitTest.php index a459b12..c8dff56 100644 --- a/tests/Tool/ValueExtractorTraitTest.php +++ b/tests/Tool/ValueExtractorTraitTest.php @@ -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'); + } }