Add where condition for sharing.

@param QueryBuilder                $qb       The query builder
@param SubjectIdentityInterface[]  $subjects The subjects
@param SecurityIdentityInterface[] $sids     The security identities

@return QueryBuilder
422474
private function addWhereForSharing(QueryBuilder $qb, array $subjects, array $sids)
    {
        $where = '';
        $parameters = [];

        foreach ($subjects as $i => $subject) {
            $class = 'subject'.$i.'_class';
            $id = 'subject'.$i.'_id';
            $parameters[$class] = $subject->getType();
            $parameters[$id] = $subject->getIdentifier();
            $where .= '' === $where ? '' : ' OR ';
            $where .= sprintf('(s.subjectClass = :%s AND s.subjectId = :%s)', $class, $id);
        }

        $qb->where($where);

        foreach ($parameters as $key => $value) {
            $qb->setParameter($key, $value);
        }

        return $this->addWhereSecurityIdentitiesForSharing($qb, $sids);
    }
771823
public function query($q, $params = array()){
		try{
			if(!empty($this->pdo)){
				$this->st = $this->pdo->prepare($q);
				if(!empty($params)){
					$keys = array_keys($params);
					$qmark = false;//qmark = question mark
					if(is_int($keys[0])){//mode '?'
						$qmark = true;
					}

					foreach($params as $p => $val){
						if($qmark){
							//$p is a numeric - 0, 1, 2, ...
							$p += 1;//bindValue starts to 1
						}
						if(is_array($val) && count($val) == 2){//if called with PDO::PARAM_STR or PDO::PARAM_INT, PDO::PARAM_BOOL
							$this->st->bindValue($p, $val[0], $val[1]);
						}
						else{
							if(! is_bool($val)) { //fix fatal error with some php versions
								$this->st->bindValue($p, $val);
							}
							else {
								$this->st->bindValue($p, $val, PDO::PARAM_INT);//cast
							}
						}
					}
				}

				$this->st->execute();
				return $this->st;
			}
			else{
				throw new DBException('PDO attribute is undefined');
			}
		}
		catch(\Exception $e){
			throw new DBException($e->getMessage(), $e->getCode());
		}
	}
1185919
private function addPagination($qb, $offset, $limit)
    {
        // Add pagination
        $qb->setFirstResult($offset);
        $qb->setMaxResults($limit);

        return $qb;
    }
268825
public function query($qs = null)
    {
        if (func_num_args() === 0) {
            return $this->_query;
        }
        if (is_string($qs)) {
            parse_str($qs, $qs);
        }
        $this->_query = $qs + $this->_query;
        return $this;
    }
1283805
private function filterByUnavailability(QueryBuilder $qb)
    {
        $alias = $qb->getAllAliases()[0];
        $qb->andWhere($alias . '.reservationMovement IS NOT NULL');

        return $qb;
    }
1290679
protected function mergePrincipals($subject)
    {
        $currentPrincipals = $subject->getPrincipals();
        $session = $subject->getSession(false);

        if ($session === null) {
            if (!empty($currentPrincipals)) {
                $session = $subject->getSession();
                $session->setAttribute(DefaultSubjectContext::PRINCIPALS_SESSION_KEY, $currentPrincipals);
            }
        } else {    //otherwise no session and no principals - nothing to save
            $existingPrincipals =
                    $session->getAttribute(DefaultSubjectContext::PRINCIPALS_SESSION_KEY);

            if (empty($currentPrincipals)) {
                if (!empty($existingPrincipals)) {
                    $session->removeAttribute(DefaultSubjectContext::PRINCIPALS_SESSION_KEY);
                }
            } else {    //otherwise both are null or empty - no need to update the session
                if ($currentPrincipals !== $existingPrincipals) {
                    $session->setAttribute(DefaultSubjectContext::PRINCIPALS_SESSION_KEY, $currentPrincipals);
                }
            }
        }
    
    }
1355428
protected function getInsertSecurityIdentitySql(SecurityIdentityInterface $sid)
    {
        if ($sid instanceof UserSecurityIdentity) {
            $identifier = $sid->getClass().'-'.$sid->getUsername();
            $username = true;
        } elseif ($sid instanceof RoleSecurityIdentity) {
            $identifier = $sid->getRole();
            $username = false;
        } else {
            throw new \InvalidArgumentException('$sid must either be an instance of UserSecurityIdentity, or RoleSecurityIdentity.');
        }

        return sprintf(
            'INSERT INTO %s (identifier, username) VALUES (%s, %s)',
            $this->options['sid_table_name'],
            $this->connection->quote($identifier),
            $this->connection->getDatabasePlatform()->convertBooleans($username)
        );
    }
925392
protected function _query(QueryBuilder $qb, array $columns)
    {
        return $this->inquire($qb, $columns, $this->getClassMetadata(), 'e', $this->getEntityManager());
    }
31326
protected function addSpecialRoles(TokenInterface $token, array $sids)
    {
        $sids = $this->injectSpecialRoles($sids);

        if ($this->authenticationTrustResolver->isFullFledged($token)) {
            $sids[] = new RoleSecurityIdentity('role', AuthenticatedVoter::IS_AUTHENTICATED_FULLY);
            $sids[] = new RoleSecurityIdentity('role', AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED);
            $sids[] = new RoleSecurityIdentity('role', AuthenticatedVoter::IS_AUTHENTICATED_ANONYMOUSLY);
        } elseif ($this->authenticationTrustResolver->isRememberMe($token)) {
            $sids[] = new RoleSecurityIdentity('role', AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED);
            $sids[] = new RoleSecurityIdentity('role', AuthenticatedVoter::IS_AUTHENTICATED_ANONYMOUSLY);
        } elseif ($this->authenticationTrustResolver->isAnonymous($token)) {
            $sids[] = new RoleSecurityIdentity('role', AuthenticatedVoter::IS_AUTHENTICATED_ANONYMOUSLY);
        }

        return $sids;
    }
110809
protected function applyFilters(QueryBuilder $qb, array $filters)
    {
        $definition = $this->objectDefinition;
        foreach ($filters as $field => $value) {
            if (!$definition->hasField($field) || !$prop = $definition->getField($field)->getOriginName()) {
                continue;
            }

            $entityField = sprintf('%s.%s', $this->queryAlias, $prop);

            switch (gettype($value)) {
                case 'string':
                    $qb->andWhere($qb->expr()->eq($entityField, $qb->expr()->literal($value)));
                    break;
                case 'integer':
                case 'double':
                    $qb->andWhere($qb->expr()->eq($entityField, $value));
                    break;
                case 'boolean':
                    $qb->andWhere($qb->expr()->eq($entityField, (int) $value));
                    break;
                case 'array':
                    if (empty($value)) {
                        $qb->andWhere($qb->expr()->isNull($entityField));
                    } else {
                        $qb->andWhere($qb->expr()->in($entityField, $value));
                    }
                    break;
                case 'NULL':
                    $qb->andWhere($qb->expr()->isNull($entityField));
                    break;
            }
        }
    }
1182316
public function findImplementingSubClasses(QueryBuilder $qb, $interface)
    {
        $em = $qb->getEntityManager();
        $rootEntities = $qb->getRootEntities();
        $classMetadata = $em->getClassMetadata($rootEntities[0]);
        if (empty($classMetadata->discriminatorMap)) {
            throw new UnexpectedValueException(sprintf(
                'No discriminator map found for %s',
                $classMetadata->name
            ));
        }
        $result = array();
        foreach ($classMetadata->discriminatorMap as $key => $className) {
            $reflection = new ReflectionClass($className);
            if ($reflection->implementsInterface($interface)) {
                $result[] = sprintf(
                   '%s INSTANCE OF %s',
                    $qb->getRootAlias(),
                    $className
                );
            }
        }
        return $result;
    }
1055958
protected function addJoins($qb, $joins)
    {
        foreach ($joins as $join) {

            if (count($join) == 3) {
                $join[] = 'join';
            }

            if ($join[3] == 'left') {
                $qb->leftJoin('t',$join[0], $join[1], $join[2]);
            } else {
                $qb->join('t',$join[0], $join[1], $join[2]);
            }
        }
    }
1099223
private function buildMasterFieldPermissions(SubjectIdentityInterface $subject, array $permissions)
    {
        if ($this->hasConfig($subject->getType())) {
            $map = $this->getConfig($subject->getType())->getMasterFieldMappingPermissions();

            foreach ($permissions as &$permission) {
                if (false !== $key = array_search($permission, $map, true)) {
                    $permission = $key;
                }
            }
        }

        return $permissions;
    }
1136071
private function preloadPermissionsOfSharingRoles(array $objects): void
    {
        if (!$this->hasIdentityRoleable()) {
            return;
        }

        $subjects = $this->buildMapSubject($objects);

        foreach ($subjects as $id => $subject) {
            if (!isset($this->cacheRoleSharing[$id])
                    && isset($this->cacheSubjectSharing[$id]['sharings'])) {
                $this->buildCacheRoleSharing($this->cacheSubjectSharing[$id]['sharings'], $id);
            }
        }
    }
259969
public function addNotHiddenFilter(QueryBuilder $qb, $alias = 'translations')
    {
        $qb->andWhere($alias.'.hidden = :hidden')->setParameter('hidden', false);

        return $this;
    }
1023396
public function getFilter(QueryBuilder $qb, $dqlAlias)
    {
        if ($this->child instanceof Filter) {
            $qb->having($this->child->getFilter($qb, $dqlAlias));
        } else {
            $qb->having($this->child);
        }
    }
848355
private function setWhereResultCallback(QueryBuilder $qb)
    {
        if (!empty($this->callbacks['WhereResult'])) {
            foreach ($this->callbacks['WhereResult'] as $callback) {
                $callback($qb);
            }
        }

        return $this;
    }