Search code examples
phpsymfonydoctrine-ormdoctrinedoctrine-query

Is it safe to provide variable to Doctirne Expr static methods (e.g. expr()->eq('p.var', $var))?


Is it safe to provide variables to Doctirne Expr static methods?

And if it is mandatory to set them as parameters is there an easier way to do so e.g. in the $or->add() method?

So can it be like:

$or = $qb->expr()->orx();
if (!empty($sessionId)) {
    $or->add($qb->expr()->eq('up.session_id', $sessionId));
}
if ($user instanceof User) {
    $or->add($qb->expr()->eq('up.user_id', $user->getId()));
}

My ugly solution so far is:

$qb = $this->getEntityManager()->createQueryBuilder();

$or = $qb->expr()->orx();
if (!empty($sessionId)) {
    $or->add($qb->expr()->eq('up.session_id', ':session_id'));
}
if ($user instanceof User) {
    $or->add($qb->expr()->eq('up.user_id', ':user_id'));
}

$qb->select('up')
    ->from('SCCatalogBundle:UserProject', 'up')
    ->where($or)
    ->OrderBy('up.updated', 'DESC');

if (!empty($sessionId)) {
    $qb->setParameter('session_id', $sessionId);
}
if ($user instanceof User) {
    $qb->setParameter('user_id', $user->getId());
}

$query = $qb->getQuery();

Solution

  • As far as I know you should use setParameter to avoid SQL-Injection. I think I is not necessary to set the parameters in that order. Therefore you could write your code like this:

    $qb = $this->getEntityManager()->createQueryBuilder();
    
    $or = $qb->expr()->orx();
    if (!empty($sessionId)) {
        $or->add($qb->expr()->eq('up.session_id', ':session_id'));
        $qb->setParameter('session_id', $sessionId);
    }
    if ($user instanceof User) {
        $or->add($qb->expr()->eq('up.user_id', ':user_id'));
        $qb->setParameter('user_id', $user->getId());
    }
    
    $qb->select('up')
        ->from('SCCatalogBundle:UserProject', 'up')
        ->where($or)
        ->OrderBy('up.updated', 'DESC');
    
    
    $query = $qb->getQuery();