Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ValueExtractorTrait does not extract from public methods with same name as private properties #122

Open
fvdb opened this issue Apr 24, 2023 · 0 comments
Labels

Comments

@fvdb
Copy link

fvdb commented Apr 24, 2023

Description

When AbstractCollection contains objects which have both a method and property with the same name, the value can never be extracted from the method through ValueExtractorTrait::extractValue().

Steps to reproduce

class Person
{
    public function __construct(private string $name)
    {
    }

    public function name(): string
    {
        return $this->name;
    }
}

$collection = new Ramsey\Collection\Collection();
$collection->add(new Person('Bob'));

print_r($collection->columns('name'));

The above triggers an error:

Error: Cannot access private property Person::$name

Expected behavior

Array
(
    [0] => Bob
)

Environment details

  • version of this package: 2.0.0
  • PHP version: 8.2.5

Cause

This seems to be because ValueExtractorTrait::extractValue() does not check if the property is actually accessible before trying to access it. It then proceeds to access it, causing the error, and then it never gets to checking whether a method exists with that same name which actually is accessible.

Possible solutions

One option would be to verify accessibility before attempting to access the property or method, but this would require use of reflection with obvious performance downsides.

Alternatively if it is detected that both the method and property exist of the same name, one could use a try/catch block to attempt to access them and then only throw an exception if both attempts failed.

Finally another "fix" could be to swap the position of accessing the property with that of accessing the method, which would work for the above use case (which is probably the most common). However, this would then cause a similar issue for objects with a private method and public property with the same name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant