8

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.

gp_sflover
  • 3,460
  • 5
  • 38
  • 48
Michon
  • 95
  • 1
  • 5
  • There is a [property_exists](http://php.net/manual/fr/function.property-exists.php) function in php. – fxbt May 31 '18 at 09:35

2 Answers2

10

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

tr05t
  • 47
  • 1
  • 10
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
10

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

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

if ($metaCar->hasField('foo')) {
   //property exists
}
Gautier
  • 1,066
  • 1
  • 13
  • 24