Skip to content

Add exists() method in PropertyAccesor class #60271

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

Open
maixal opened this issue Apr 25, 2025 · 2 comments
Open

Add exists() method in PropertyAccesor class #60271

maixal opened this issue Apr 25, 2025 · 2 comments

Comments

@maixal
Copy link

maixal commented Apr 25, 2025

Description

Hi,

Is it possible to add exists() method in Symfony\Component\PropertyAccess\PropertyAccessor class please ?

Thanks

Example

I use it like this :

private PropertyAccessor $pa;

public function __construct()
{
    $this->pa = PropertyAccess::createPropertyAccessorBuilder()
            ->enableExceptionOnInvalidIndex()
            ->getPropertyAccessor();
}

public function propertyExists(array $objectOrArray, string $propertyPath): bool
    {
        try {
            $this->pa->getValue($objectOrArray, $propertyPath);
            return true;
        } catch(NoSuchIndexException $e) {
            return false;
        }
    }
@maixal maixal changed the title Add exists() methos in PropertyAccesor class Add exists() method in PropertyAccesor class Apr 25, 2025
@Brajk19
Copy link
Contributor

Brajk19 commented Apr 26, 2025

Hello, is isReadable method what you are looking for?

/**
* Returns whether a property path can be read from an object graph.
*
* Whenever this method returns true, {@link getValue()} is guaranteed not
* to throw an exception when called with the same arguments.
*
* @throws Exception\InvalidArgumentException If the property path is invalid
*/
public function isReadable(object|array $objectOrArray, string|PropertyPathInterface $propertyPath): bool;

It basically does the same thing as propertyExists you provided, it wraps logic for reading in try-catch and returns false if exception is caught.

@maixal
Copy link
Author

maixal commented Apr 30, 2025

unfortunally isReadable is not working like array_key_exists() PHP function...

I need to use this code to check if array key exits :

private PropertyAccessor $pa;

public function __construct()
{
    $this->pa = PropertyAccess::createPropertyAccessorBuilder()
            ->enableExceptionOnInvalidIndex()
            ->getPropertyAccessor();
}

public function propertyExists(array $objectOrArray, string $propertyPath): bool
    {
        try {
            $this->pa->getValue($objectOrArray, $propertyPath);
            return true;
        } catch(NoSuchIndexException $e) {
            return false;
        }
    }

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

No branches or pull requests

3 participants