Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if entity property exists

I have an URL like example.org/overview/<column>/<value> (example: example.org/overview/color/red) which will cause a search in a column "color" for the value "red". This is the entity:

<?php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

// @ORM\Entity(repositoryClass="App\Repository\CarRepository")
class Car
{
    // @ORM\Column(type="string", length=255)
    private $name;
    private $color;

    [...]

I think I should check if an entity property exists before I start a db query. How can I check when someone calls example.org/overview/foo/bar if foo is a valid db column (= entity property)? Does Symfony offer a simple solution here? If this might not be the case I think I have to use a hard coded white list.

like image 218
Michon Avatar asked May 31 '18 09:05

Michon


People also ask

How do you check if a property of an object exists?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.

How do you check if a property exists in an object TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.

How do you check if an object has a specific property in JavaScript?

The static Reflect.has() method works like the in operator as a function. If the property does not exist on the object, it will return the string undefined. Else it will return the appropriate property type.

How do you check if the object exists in JavaScript?

Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.


2 Answers

you can use getClassMetadata like this:

$columns = $em->getClassMetadata(Car::class)->getColumnNames();

if (in_array($property, $columns)) {
   //property exists, code here
}

You can try also: getFieldNames instead of getColumnNames

like image 79
Alessandro Minoccheri Avatar answered Oct 13 '22 22:10

Alessandro Minoccheri


Alessandro is right but the exact method hasField() exists:

$metaCar = $em->getClassMetadata(Car::class)

if ($metaCar->hasField('foo')) {
   //property exists
}
like image 39
Gautier Avatar answered Oct 13 '22 21:10

Gautier