Get field type in Symfony2 repository

1.9k Views Asked by At

I have function in symfony repository

        public function getAllSites($criteria = null)
{
    $qb = $this->createQueryBuilder('s')
               ->select('s')
               ->orderBy('s.root', 'ASC')
               ->addOrderBy('s.lft', 'ASC');

        if($criteria !== null):
            foreach ($criteria as $field => $value):
                if (!$this->getClassMetadata()->hasField($field)):
                    continue; // Make sure we only use existing fields (avoid any injection)                        
                endif;
                $qb ->andWhere($qb->expr()->eq('s.'.$field, ':s_'.$field))
                    ->setParameter('s_'.$field, $value);
            endforeach;
        endif;

    return $qb->getQuery()->getResult();
} 

I would like to check the type of field and then use search LIKE %word% if the field type is string (or text) and andWhere for other fields.

Do you know which function return fieldType in symfony repository?

2

There are 2 best solutions below

1
On

I think you are looking for PHP's getType() function. See the PHP docs for more info on how to use it.

$var = "abc";
$type = getType($var)
// returns 'string'
0
On

I found an answer now. The function is $this->getClassMetadata()->getTypeOfField($field).

Example:

public function getAllSites($criteria = null)
{
    $qb = $this->createQueryBuilder('s')
               ->select('s')
               ->orderBy('s.root', 'ASC')
               ->addOrderBy('s.lft', 'ASC');

        if($criteria !== null):
            foreach ($criteria as $field => $value):
                if (!$this->getClassMetadata()->hasField($field)):
                    continue; // Make sure we only use existing fields (avoid any injection)                        
                endif;                    
                if ($this->getClassMetadata()->getTypeOfField($field) === 'string'
                    || $this->getClassMetadata()->getTypeOfField($field) === 'text'):
                    $qb ->andWhere($qb->expr()->like('s.'.$field, ':s_'.$field))
                        ->setParameter('s_'.$field, '%'.$value.'%');    // search LIKE %value%
                else:    
                    $qb ->andWhere($qb->expr()->eq('s.'.$field, ':s_'.$field))
                        ->setParameter('s_'.$field, $value);
                endif;
            endforeach;
        endif;

    return $qb->getQuery()->getResult();
}

More functions about ClassMetadata you can find here.