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.
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.
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.
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.
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”.
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
Alessandro is right but the exact method hasField()
exists:
$metaCar = $em->getClassMetadata(Car::class)
if ($metaCar->hasField('foo')) {
//property exists
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With