vendor/doctrine/orm/lib/Doctrine/ORM/QueryBuilder.php line 53

Open in your IDE?
  1. <?php
  2. /*
  3.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5.  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6.  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7.  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9.  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10.  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11.  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13.  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14.  *
  15.  * This software consists of voluntary contributions made by many individuals
  16.  * and is licensed under the MIT license. For more information, see
  17.  * <http://www.doctrine-project.org>.
  18.  */
  19. namespace Doctrine\ORM;
  20. use Doctrine\Common\Collections\ArrayCollection;
  21. use Doctrine\Common\Collections\Criteria;
  22. use Doctrine\ORM\Query\Expr;
  23. use Doctrine\ORM\Query\QueryExpressionVisitor;
  24. use InvalidArgumentException;
  25. use RuntimeException;
  26. use function array_keys;
  27. use function array_merge;
  28. use function array_unshift;
  29. use function assert;
  30. use function func_get_args;
  31. use function func_num_args;
  32. use function implode;
  33. use function in_array;
  34. use function is_array;
  35. use function is_numeric;
  36. use function is_object;
  37. use function is_string;
  38. use function key;
  39. use function reset;
  40. use function sprintf;
  41. use function strpos;
  42. use function strrpos;
  43. use function substr;
  44. /**
  45.  * This class is responsible for building DQL query strings via an object oriented
  46.  * PHP interface.
  47.  */
  48. class QueryBuilder
  49. {
  50.     /* The query types. */
  51.     public const SELECT 0;
  52.     public const DELETE 1;
  53.     public const UPDATE 2;
  54.     /* The builder states. */
  55.     public const STATE_DIRTY 0;
  56.     public const STATE_CLEAN 1;
  57.     /**
  58.      * The EntityManager used by this QueryBuilder.
  59.      *
  60.      * @var EntityManagerInterface
  61.      */
  62.     private $_em;
  63.     /**
  64.      * The array of DQL parts collected.
  65.      *
  66.      * @psalm-var array<string, mixed>
  67.      */
  68.     private $_dqlParts = [
  69.         'distinct' => false,
  70.         'select'  => [],
  71.         'from'    => [],
  72.         'join'    => [],
  73.         'set'     => [],
  74.         'where'   => null,
  75.         'groupBy' => [],
  76.         'having'  => null,
  77.         'orderBy' => [],
  78.     ];
  79.     /**
  80.      * The type of query this is. Can be select, update or delete.
  81.      *
  82.      * @var int
  83.      */
  84.     private $_type self::SELECT;
  85.     /**
  86.      * The state of the query object. Can be dirty or clean.
  87.      *
  88.      * @var int
  89.      */
  90.     private $_state self::STATE_CLEAN;
  91.     /**
  92.      * The complete DQL string for this query.
  93.      *
  94.      * @var string
  95.      */
  96.     private $_dql;
  97.     /**
  98.      * The query parameters.
  99.      *
  100.      * @var ArrayCollection
  101.      */
  102.     private $parameters;
  103.     /**
  104.      * The index of the first result to retrieve.
  105.      *
  106.      * @var int|null
  107.      */
  108.     private $_firstResult null;
  109.     /**
  110.      * The maximum number of results to retrieve.
  111.      *
  112.      * @var int|null
  113.      */
  114.     private $_maxResults null;
  115.     /**
  116.      * Keeps root entity alias names for join entities.
  117.      *
  118.      * @psalm-var array<string, string>
  119.      */
  120.     private $joinRootAliases = [];
  121.      /**
  122.       * Whether to use second level cache, if available.
  123.       *
  124.       * @var bool
  125.       */
  126.     protected $cacheable false;
  127.     /**
  128.      * Second level cache region name.
  129.      *
  130.      * @var string|null
  131.      */
  132.     protected $cacheRegion;
  133.     /**
  134.      * Second level query cache mode.
  135.      *
  136.      * @var int|null
  137.      */
  138.     protected $cacheMode;
  139.     /** @var int */
  140.     protected $lifetime 0;
  141.     /**
  142.      * Initializes a new <tt>QueryBuilder</tt> that uses the given <tt>EntityManager</tt>.
  143.      *
  144.      * @param EntityManagerInterface $em The EntityManager to use.
  145.      */
  146.     public function __construct(EntityManagerInterface $em)
  147.     {
  148.         $this->_em        $em;
  149.         $this->parameters = new ArrayCollection();
  150.     }
  151.     /**
  152.      * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
  153.      * This producer method is intended for convenient inline usage. Example:
  154.      *
  155.      * <code>
  156.      *     $qb = $em->createQueryBuilder();
  157.      *     $qb
  158.      *         ->select('u')
  159.      *         ->from('User', 'u')
  160.      *         ->where($qb->expr()->eq('u.id', 1));
  161.      * </code>
  162.      *
  163.      * For more complex expression construction, consider storing the expression
  164.      * builder object in a local variable.
  165.      *
  166.      * @return Query\Expr
  167.      */
  168.     public function expr()
  169.     {
  170.         return $this->_em->getExpressionBuilder();
  171.     }
  172.     /**
  173.      * Enable/disable second level query (result) caching for this query.
  174.      *
  175.      * @param bool $cacheable
  176.      *
  177.      * @return self
  178.      */
  179.     public function setCacheable($cacheable)
  180.     {
  181.         $this->cacheable = (bool) $cacheable;
  182.         return $this;
  183.     }
  184.     /**
  185.      * @return bool TRUE if the query results are enable for second level cache, FALSE otherwise.
  186.      */
  187.     public function isCacheable()
  188.     {
  189.         return $this->cacheable;
  190.     }
  191.     /**
  192.      * @param string $cacheRegion
  193.      *
  194.      * @return self
  195.      */
  196.     public function setCacheRegion($cacheRegion)
  197.     {
  198.         $this->cacheRegion = (string) $cacheRegion;
  199.         return $this;
  200.     }
  201.     /**
  202.      * Obtain the name of the second level query cache region in which query results will be stored
  203.      *
  204.      * @return string|null The cache region name; NULL indicates the default region.
  205.      */
  206.     public function getCacheRegion()
  207.     {
  208.         return $this->cacheRegion;
  209.     }
  210.     /**
  211.      * @return int
  212.      */
  213.     public function getLifetime()
  214.     {
  215.         return $this->lifetime;
  216.     }
  217.     /**
  218.      * Sets the life-time for this query into second level cache.
  219.      *
  220.      * @param int $lifetime
  221.      *
  222.      * @return self
  223.      */
  224.     public function setLifetime($lifetime)
  225.     {
  226.         $this->lifetime = (int) $lifetime;
  227.         return $this;
  228.     }
  229.     /**
  230.      * @return int
  231.      */
  232.     public function getCacheMode()
  233.     {
  234.         return $this->cacheMode;
  235.     }
  236.     /**
  237.      * @param int $cacheMode
  238.      *
  239.      * @return self
  240.      */
  241.     public function setCacheMode($cacheMode)
  242.     {
  243.         $this->cacheMode = (int) $cacheMode;
  244.         return $this;
  245.     }
  246.     /**
  247.      * Gets the type of the currently built query.
  248.      *
  249.      * @return int
  250.      */
  251.     public function getType()
  252.     {
  253.         return $this->_type;
  254.     }
  255.     /**
  256.      * Gets the associated EntityManager for this query builder.
  257.      *
  258.      * @return EntityManager
  259.      */
  260.     public function getEntityManager()
  261.     {
  262.         return $this->_em;
  263.     }
  264.     /**
  265.      * Gets the state of this query builder instance.
  266.      *
  267.      * @return int Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
  268.      */
  269.     public function getState()
  270.     {
  271.         return $this->_state;
  272.     }
  273.     /**
  274.      * Gets the complete DQL string formed by the current specifications of this QueryBuilder.
  275.      *
  276.      * <code>
  277.      *     $qb = $em->createQueryBuilder()
  278.      *         ->select('u')
  279.      *         ->from('User', 'u');
  280.      *     echo $qb->getDql(); // SELECT u FROM User u
  281.      * </code>
  282.      *
  283.      * @return string The DQL query string.
  284.      */
  285.     public function getDQL()
  286.     {
  287.         if ($this->_dql !== null && $this->_state === self::STATE_CLEAN) {
  288.             return $this->_dql;
  289.         }
  290.         switch ($this->_type) {
  291.             case self::DELETE:
  292.                 $dql $this->getDQLForDelete();
  293.                 break;
  294.             case self::UPDATE:
  295.                 $dql $this->getDQLForUpdate();
  296.                 break;
  297.             case self::SELECT:
  298.             default:
  299.                 $dql $this->getDQLForSelect();
  300.                 break;
  301.         }
  302.         $this->_state self::STATE_CLEAN;
  303.         $this->_dql   $dql;
  304.         return $dql;
  305.     }
  306.     /**
  307.      * Constructs a Query instance from the current specifications of the builder.
  308.      *
  309.      * <code>
  310.      *     $qb = $em->createQueryBuilder()
  311.      *         ->select('u')
  312.      *         ->from('User', 'u');
  313.      *     $q = $qb->getQuery();
  314.      *     $results = $q->execute();
  315.      * </code>
  316.      *
  317.      * @return Query
  318.      */
  319.     public function getQuery()
  320.     {
  321.         $parameters = clone $this->parameters;
  322.         $query      $this->_em->createQuery($this->getDQL())
  323.             ->setParameters($parameters)
  324.             ->setFirstResult($this->_firstResult)
  325.             ->setMaxResults($this->_maxResults);
  326.         if ($this->lifetime) {
  327.             $query->setLifetime($this->lifetime);
  328.         }
  329.         if ($this->cacheMode) {
  330.             $query->setCacheMode($this->cacheMode);
  331.         }
  332.         if ($this->cacheable) {
  333.             $query->setCacheable($this->cacheable);
  334.         }
  335.         if ($this->cacheRegion) {
  336.             $query->setCacheRegion($this->cacheRegion);
  337.         }
  338.         return $query;
  339.     }
  340.     /**
  341.      * Finds the root entity alias of the joined entity.
  342.      *
  343.      * @param string $alias       The alias of the new join entity
  344.      * @param string $parentAlias The parent entity alias of the join relationship
  345.      *
  346.      * @return string
  347.      */
  348.     private function findRootAlias($alias$parentAlias)
  349.     {
  350.         $rootAlias null;
  351.         if (in_array($parentAlias$this->getRootAliases())) {
  352.             $rootAlias $parentAlias;
  353.         } elseif (isset($this->joinRootAliases[$parentAlias])) {
  354.             $rootAlias $this->joinRootAliases[$parentAlias];
  355.         } else {
  356.             // Should never happen with correct joining order. Might be
  357.             // thoughtful to throw exception instead.
  358.             $rootAlias $this->getRootAlias();
  359.         }
  360.         $this->joinRootAliases[$alias] = $rootAlias;
  361.         return $rootAlias;
  362.     }
  363.     /**
  364.      * Gets the FIRST root alias of the query. This is the first entity alias involved
  365.      * in the construction of the query.
  366.      *
  367.      * <code>
  368.      * $qb = $em->createQueryBuilder()
  369.      *     ->select('u')
  370.      *     ->from('User', 'u');
  371.      *
  372.      * echo $qb->getRootAlias(); // u
  373.      * </code>
  374.      *
  375.      * @deprecated Please use $qb->getRootAliases() instead.
  376.      *
  377.      * @return string
  378.      *
  379.      * @throws RuntimeException
  380.      */
  381.     public function getRootAlias()
  382.     {
  383.         $aliases $this->getRootAliases();
  384.         if (! isset($aliases[0])) {
  385.             throw new RuntimeException('No alias was set before invoking getRootAlias().');
  386.         }
  387.         return $aliases[0];
  388.     }
  389.     /**
  390.      * Gets the root aliases of the query. This is the entity aliases involved
  391.      * in the construction of the query.
  392.      *
  393.      * <code>
  394.      *     $qb = $em->createQueryBuilder()
  395.      *         ->select('u')
  396.      *         ->from('User', 'u');
  397.      *
  398.      *     $qb->getRootAliases(); // array('u')
  399.      * </code>
  400.      *
  401.      * @return mixed[]
  402.      * @psalm-return list<mixed>
  403.      */
  404.     public function getRootAliases()
  405.     {
  406.         $aliases = [];
  407.         foreach ($this->_dqlParts['from'] as &$fromClause) {
  408.             if (is_string($fromClause)) {
  409.                 $spacePos strrpos($fromClause' ');
  410.                 $from     substr($fromClause0$spacePos);
  411.                 $alias    substr($fromClause$spacePos 1);
  412.                 $fromClause = new Query\Expr\From($from$alias);
  413.             }
  414.             $aliases[] = $fromClause->getAlias();
  415.         }
  416.         return $aliases;
  417.     }
  418.     /**
  419.      * Gets all the aliases that have been used in the query.
  420.      * Including all select root aliases and join aliases
  421.      *
  422.      * <code>
  423.      *     $qb = $em->createQueryBuilder()
  424.      *         ->select('u')
  425.      *         ->from('User', 'u')
  426.      *         ->join('u.articles','a');
  427.      *
  428.      *     $qb->getAllAliases(); // array('u','a')
  429.      * </code>
  430.      *
  431.      * @return mixed[]
  432.      * @psalm-return list<mixed>
  433.      */
  434.     public function getAllAliases()
  435.     {
  436.         return array_merge($this->getRootAliases(), array_keys($this->joinRootAliases));
  437.     }
  438.     /**
  439.      * Gets the root entities of the query. This is the entity aliases involved
  440.      * in the construction of the query.
  441.      *
  442.      * <code>
  443.      *     $qb = $em->createQueryBuilder()
  444.      *         ->select('u')
  445.      *         ->from('User', 'u');
  446.      *
  447.      *     $qb->getRootEntities(); // array('User')
  448.      * </code>
  449.      *
  450.      * @return mixed[]
  451.      * @psalm-return list<mixed>
  452.      */
  453.     public function getRootEntities()
  454.     {
  455.         $entities = [];
  456.         foreach ($this->_dqlParts['from'] as &$fromClause) {
  457.             if (is_string($fromClause)) {
  458.                 $spacePos strrpos($fromClause' ');
  459.                 $from     substr($fromClause0$spacePos);
  460.                 $alias    substr($fromClause$spacePos 1);
  461.                 $fromClause = new Query\Expr\From($from$alias);
  462.             }
  463.             $entities[] = $fromClause->getFrom();
  464.         }
  465.         return $entities;
  466.     }
  467.     /**
  468.      * Sets a query parameter for the query being constructed.
  469.      *
  470.      * <code>
  471.      *     $qb = $em->createQueryBuilder()
  472.      *         ->select('u')
  473.      *         ->from('User', 'u')
  474.      *         ->where('u.id = :user_id')
  475.      *         ->setParameter('user_id', 1);
  476.      * </code>
  477.      *
  478.      * @param string|int      $key   The parameter position or name.
  479.      * @param mixed           $value The parameter value.
  480.      * @param string|int|null $type  PDO::PARAM_* or \Doctrine\DBAL\Types\Type::* constant
  481.      *
  482.      * @return self
  483.      */
  484.     public function setParameter($key$value$type null)
  485.     {
  486.         $existingParameter $this->getParameter($key);
  487.         if ($existingParameter !== null) {
  488.             $existingParameter->setValue($value$type);
  489.             return $this;
  490.         }
  491.         $this->parameters->add(new Query\Parameter($key$value$type));
  492.         return $this;
  493.     }
  494.     /**
  495.      * Sets a collection of query parameters for the query being constructed.
  496.      *
  497.      * <code>
  498.      *     $qb = $em->createQueryBuilder()
  499.      *         ->select('u')
  500.      *         ->from('User', 'u')
  501.      *         ->where('u.id = :user_id1 OR u.id = :user_id2')
  502.      *         ->setParameters(new ArrayCollection(array(
  503.      *             new Parameter('user_id1', 1),
  504.      *             new Parameter('user_id2', 2)
  505.      *        )));
  506.      * </code>
  507.      *
  508.      * @param ArrayCollection|mixed[] $parameters The query parameters to set.
  509.      *
  510.      * @return self
  511.      */
  512.     public function setParameters($parameters)
  513.     {
  514.         // BC compatibility with 2.3-
  515.         if (is_array($parameters)) {
  516.             /** @psalm-var ArrayCollection<int, Query\Parameter> $parameterCollection */
  517.             $parameterCollection = new ArrayCollection();
  518.             foreach ($parameters as $key => $value) {
  519.                 $parameter = new Query\Parameter($key$value);
  520.                 $parameterCollection->add($parameter);
  521.             }
  522.             $parameters $parameterCollection;
  523.         }
  524.         $this->parameters $parameters;
  525.         return $this;
  526.     }
  527.     /**
  528.      * Gets all defined query parameters for the query being constructed.
  529.      *
  530.      * @return ArrayCollection The currently defined query parameters.
  531.      */
  532.     public function getParameters()
  533.     {
  534.         return $this->parameters;
  535.     }
  536.     /**
  537.      * Gets a (previously set) query parameter of the query being constructed.
  538.      *
  539.      * @param mixed $key The key (index or name) of the bound parameter.
  540.      *
  541.      * @return Query\Parameter|null The value of the bound parameter.
  542.      */
  543.     public function getParameter($key)
  544.     {
  545.         $key Query\Parameter::normalizeName($key);
  546.         $filteredParameters $this->parameters->filter(
  547.             static function (Query\Parameter $parameter) use ($key): bool {
  548.                 $parameterName $parameter->getName();
  549.                 return $key === $parameterName;
  550.             }
  551.         );
  552.         return ! $filteredParameters->isEmpty() ? $filteredParameters->first() : null;
  553.     }
  554.     /**
  555.      * Sets the position of the first result to retrieve (the "offset").
  556.      *
  557.      * @param int|null $firstResult The first result to return.
  558.      *
  559.      * @return self
  560.      */
  561.     public function setFirstResult($firstResult)
  562.     {
  563.         $this->_firstResult $firstResult;
  564.         return $this;
  565.     }
  566.     /**
  567.      * Gets the position of the first result the query object was set to retrieve (the "offset").
  568.      * Returns NULL if {@link setFirstResult} was not applied to this QueryBuilder.
  569.      *
  570.      * @return int|null The position of the first result.
  571.      */
  572.     public function getFirstResult()
  573.     {
  574.         return $this->_firstResult;
  575.     }
  576.     /**
  577.      * Sets the maximum number of results to retrieve (the "limit").
  578.      *
  579.      * @param int|null $maxResults The maximum number of results to retrieve.
  580.      *
  581.      * @return self
  582.      */
  583.     public function setMaxResults($maxResults)
  584.     {
  585.         $this->_maxResults $maxResults;
  586.         return $this;
  587.     }
  588.     /**
  589.      * Gets the maximum number of results the query object was set to retrieve (the "limit").
  590.      * Returns NULL if {@link setMaxResults} was not applied to this query builder.
  591.      *
  592.      * @return int|null Maximum number of results.
  593.      */
  594.     public function getMaxResults()
  595.     {
  596.         return $this->_maxResults;
  597.     }
  598.     /**
  599.      * Either appends to or replaces a single, generic query part.
  600.      *
  601.      * The available parts are: 'select', 'from', 'join', 'set', 'where',
  602.      * 'groupBy', 'having' and 'orderBy'.
  603.      *
  604.      * @param string $dqlPartName The DQL part name.
  605.      * @param bool   $append      Whether to append (true) or replace (false).
  606.      * @psalm-param string|object|list<string>|array{join: array<int|string, object>} $dqlPart     An Expr object.
  607.      *
  608.      * @return self
  609.      */
  610.     public function add($dqlPartName$dqlPart$append false)
  611.     {
  612.         if ($append && ($dqlPartName === 'where' || $dqlPartName === 'having')) {
  613.             throw new InvalidArgumentException(
  614.                 "Using \$append = true does not have an effect with 'where' or 'having' " .
  615.                 'parts. See QueryBuilder#andWhere() for an example for correct usage.'
  616.             );
  617.         }
  618.         $isMultiple is_array($this->_dqlParts[$dqlPartName])
  619.             && ! ($dqlPartName === 'join' && ! $append);
  620.         // Allow adding any part retrieved from self::getDQLParts().
  621.         if (is_array($dqlPart) && $dqlPartName !== 'join') {
  622.             $dqlPart reset($dqlPart);
  623.         }
  624.         // This is introduced for backwards compatibility reasons.
  625.         // TODO: Remove for 3.0
  626.         if ($dqlPartName === 'join') {
  627.             $newDqlPart = [];
  628.             foreach ($dqlPart as $k => $v) {
  629.                 $k is_numeric($k) ? $this->getRootAlias() : $k;
  630.                 $newDqlPart[$k] = $v;
  631.             }
  632.             $dqlPart $newDqlPart;
  633.         }
  634.         if ($append && $isMultiple) {
  635.             if (is_array($dqlPart)) {
  636.                 $key key($dqlPart);
  637.                 $this->_dqlParts[$dqlPartName][$key][] = $dqlPart[$key];
  638.             } else {
  639.                 $this->_dqlParts[$dqlPartName][] = $dqlPart;
  640.             }
  641.         } else {
  642.             $this->_dqlParts[$dqlPartName] = $isMultiple ? [$dqlPart] : $dqlPart;
  643.         }
  644.         $this->_state self::STATE_DIRTY;
  645.         return $this;
  646.     }
  647.     /**
  648.      * Specifies an item that is to be returned in the query result.
  649.      * Replaces any previously specified selections, if any.
  650.      *
  651.      * <code>
  652.      *     $qb = $em->createQueryBuilder()
  653.      *         ->select('u', 'p')
  654.      *         ->from('User', 'u')
  655.      *         ->leftJoin('u.Phonenumbers', 'p');
  656.      * </code>
  657.      *
  658.      * @param mixed $select The selection expressions.
  659.      *
  660.      * @return self
  661.      */
  662.     public function select($select null)
  663.     {
  664.         $this->_type self::SELECT;
  665.         if (empty($select)) {
  666.             return $this;
  667.         }
  668.         $selects is_array($select) ? $select func_get_args();
  669.         return $this->add('select', new Expr\Select($selects), false);
  670.     }
  671.     /**
  672.      * Adds a DISTINCT flag to this query.
  673.      *
  674.      * <code>
  675.      *     $qb = $em->createQueryBuilder()
  676.      *         ->select('u')
  677.      *         ->distinct()
  678.      *         ->from('User', 'u');
  679.      * </code>
  680.      *
  681.      * @param bool $flag
  682.      *
  683.      * @return self
  684.      */
  685.     public function distinct($flag true)
  686.     {
  687.         $this->_dqlParts['distinct'] = (bool) $flag;
  688.         return $this;
  689.     }
  690.     /**
  691.      * Adds an item that is to be returned in the query result.
  692.      *
  693.      * <code>
  694.      *     $qb = $em->createQueryBuilder()
  695.      *         ->select('u')
  696.      *         ->addSelect('p')
  697.      *         ->from('User', 'u')
  698.      *         ->leftJoin('u.Phonenumbers', 'p');
  699.      * </code>
  700.      *
  701.      * @param mixed $select The selection expression.
  702.      *
  703.      * @return self
  704.      */
  705.     public function addSelect($select null)
  706.     {
  707.         $this->_type self::SELECT;
  708.         if (empty($select)) {
  709.             return $this;
  710.         }
  711.         $selects is_array($select) ? $select func_get_args();
  712.         return $this->add('select', new Expr\Select($selects), true);
  713.     }
  714.     /**
  715.      * Turns the query being built into a bulk delete query that ranges over
  716.      * a certain entity type.
  717.      *
  718.      * <code>
  719.      *     $qb = $em->createQueryBuilder()
  720.      *         ->delete('User', 'u')
  721.      *         ->where('u.id = :user_id')
  722.      *         ->setParameter('user_id', 1);
  723.      * </code>
  724.      *
  725.      * @param string $delete The class/type whose instances are subject to the deletion.
  726.      * @param string $alias  The class/type alias used in the constructed query.
  727.      *
  728.      * @return self
  729.      */
  730.     public function delete($delete null$alias null)
  731.     {
  732.         $this->_type self::DELETE;
  733.         if (! $delete) {
  734.             return $this;
  735.         }
  736.         return $this->add('from', new Expr\From($delete$alias));
  737.     }
  738.     /**
  739.      * Turns the query being built into a bulk update query that ranges over
  740.      * a certain entity type.
  741.      *
  742.      * <code>
  743.      *     $qb = $em->createQueryBuilder()
  744.      *         ->update('User', 'u')
  745.      *         ->set('u.password', '?1')
  746.      *         ->where('u.id = ?2');
  747.      * </code>
  748.      *
  749.      * @param string $update The class/type whose instances are subject to the update.
  750.      * @param string $alias  The class/type alias used in the constructed query.
  751.      *
  752.      * @return self
  753.      */
  754.     public function update($update null$alias null)
  755.     {
  756.         $this->_type self::UPDATE;
  757.         if (! $update) {
  758.             return $this;
  759.         }
  760.         return $this->add('from', new Expr\From($update$alias));
  761.     }
  762.     /**
  763.      * Creates and adds a query root corresponding to the entity identified by the given alias,
  764.      * forming a cartesian product with any existing query roots.
  765.      *
  766.      * <code>
  767.      *     $qb = $em->createQueryBuilder()
  768.      *         ->select('u')
  769.      *         ->from('User', 'u');
  770.      * </code>
  771.      *
  772.      * @param string $from    The class name.
  773.      * @param string $alias   The alias of the class.
  774.      * @param string $indexBy The index for the from.
  775.      *
  776.      * @return self
  777.      */
  778.     public function from($from$alias$indexBy null)
  779.     {
  780.         return $this->add('from', new Expr\From($from$alias$indexBy), true);
  781.     }
  782.     /**
  783.      * Updates a query root corresponding to an entity setting its index by. This method is intended to be used with
  784.      * EntityRepository->createQueryBuilder(), which creates the initial FROM clause and do not allow you to update it
  785.      * setting an index by.
  786.      *
  787.      * <code>
  788.      *     $qb = $userRepository->createQueryBuilder('u')
  789.      *         ->indexBy('u', 'u.id');
  790.      *
  791.      *     // Is equivalent to...
  792.      *
  793.      *     $qb = $em->createQueryBuilder()
  794.      *         ->select('u')
  795.      *         ->from('User', 'u', 'u.id');
  796.      * </code>
  797.      *
  798.      * @param string $alias   The root alias of the class.
  799.      * @param string $indexBy The index for the from.
  800.      *
  801.      * @return self
  802.      *
  803.      * @throws Query\QueryException
  804.      */
  805.     public function indexBy($alias$indexBy)
  806.     {
  807.         $rootAliases $this->getRootAliases();
  808.         if (! in_array($alias$rootAliases)) {
  809.             throw new Query\QueryException(
  810.                 sprintf('Specified root alias %s must be set before invoking indexBy().'$alias)
  811.             );
  812.         }
  813.         foreach ($this->_dqlParts['from'] as &$fromClause) {
  814.             assert($fromClause instanceof Expr\From);
  815.             if ($fromClause->getAlias() !== $alias) {
  816.                 continue;
  817.             }
  818.             $fromClause = new Expr\From($fromClause->getFrom(), $fromClause->getAlias(), $indexBy);
  819.         }
  820.         return $this;
  821.     }
  822.     /**
  823.      * Creates and adds a join over an entity association to the query.
  824.      *
  825.      * The entities in the joined association will be fetched as part of the query
  826.      * result if the alias used for the joined association is placed in the select
  827.      * expressions.
  828.      *
  829.      * <code>
  830.      *     $qb = $em->createQueryBuilder()
  831.      *         ->select('u')
  832.      *         ->from('User', 'u')
  833.      *         ->join('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
  834.      * </code>
  835.      *
  836.      * @param string      $join          The relationship to join.
  837.      * @param string      $alias         The alias of the join.
  838.      * @param string|null $conditionType The condition type constant. Either ON or WITH.
  839.      * @param string|null $condition     The condition for the join.
  840.      * @param string|null $indexBy       The index for the join.
  841.      *
  842.      * @return self
  843.      */
  844.     public function join($join$alias$conditionType null$condition null$indexBy null)
  845.     {
  846.         return $this->innerJoin($join$alias$conditionType$condition$indexBy);
  847.     }
  848.     /**
  849.      * Creates and adds a join over an entity association to the query.
  850.      *
  851.      * The entities in the joined association will be fetched as part of the query
  852.      * result if the alias used for the joined association is placed in the select
  853.      * expressions.
  854.      *
  855.      *     [php]
  856.      *     $qb = $em->createQueryBuilder()
  857.      *         ->select('u')
  858.      *         ->from('User', 'u')
  859.      *         ->innerJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
  860.      *
  861.      * @param string      $join          The relationship to join.
  862.      * @param string      $alias         The alias of the join.
  863.      * @param string|null $conditionType The condition type constant. Either ON or WITH.
  864.      * @param string|null $condition     The condition for the join.
  865.      * @param string|null $indexBy       The index for the join.
  866.      *
  867.      * @return self
  868.      */
  869.     public function innerJoin($join$alias$conditionType null$condition null$indexBy null)
  870.     {
  871.         $parentAlias substr($join0strpos($join'.'));
  872.         $rootAlias $this->findRootAlias($alias$parentAlias);
  873.         $join = new Expr\Join(
  874.             Expr\Join::INNER_JOIN,
  875.             $join,
  876.             $alias,
  877.             $conditionType,
  878.             $condition,
  879.             $indexBy
  880.         );
  881.         return $this->add('join', [$rootAlias => $join], true);
  882.     }
  883.     /**
  884.      * Creates and adds a left join over an entity association to the query.
  885.      *
  886.      * The entities in the joined association will be fetched as part of the query
  887.      * result if the alias used for the joined association is placed in the select
  888.      * expressions.
  889.      *
  890.      * <code>
  891.      *     $qb = $em->createQueryBuilder()
  892.      *         ->select('u')
  893.      *         ->from('User', 'u')
  894.      *         ->leftJoin('u.Phonenumbers', 'p', Expr\Join::WITH, 'p.is_primary = 1');
  895.      * </code>
  896.      *
  897.      * @param string      $join          The relationship to join.
  898.      * @param string      $alias         The alias of the join.
  899.      * @param string|null $conditionType The condition type constant. Either ON or WITH.
  900.      * @param string|null $condition     The condition for the join.
  901.      * @param string|null $indexBy       The index for the join.
  902.      *
  903.      * @return self
  904.      */
  905.     public function leftJoin($join$alias$conditionType null$condition null$indexBy null)
  906.     {
  907.         $parentAlias substr($join0strpos($join'.'));
  908.         $rootAlias $this->findRootAlias($alias$parentAlias);
  909.         $join = new Expr\Join(
  910.             Expr\Join::LEFT_JOIN,
  911.             $join,
  912.             $alias,
  913.             $conditionType,
  914.             $condition,
  915.             $indexBy
  916.         );
  917.         return $this->add('join', [$rootAlias => $join], true);
  918.     }
  919.     /**
  920.      * Sets a new value for a field in a bulk update query.
  921.      *
  922.      * <code>
  923.      *     $qb = $em->createQueryBuilder()
  924.      *         ->update('User', 'u')
  925.      *         ->set('u.password', '?1')
  926.      *         ->where('u.id = ?2');
  927.      * </code>
  928.      *
  929.      * @param string $key   The key/field to set.
  930.      * @param mixed  $value The value, expression, placeholder, etc.
  931.      *
  932.      * @return self
  933.      */
  934.     public function set($key$value)
  935.     {
  936.         return $this->add('set', new Expr\Comparison($keyExpr\Comparison::EQ$value), true);
  937.     }
  938.     /**
  939.      * Specifies one or more restrictions to the query result.
  940.      * Replaces any previously specified restrictions, if any.
  941.      *
  942.      * <code>
  943.      *     $qb = $em->createQueryBuilder()
  944.      *         ->select('u')
  945.      *         ->from('User', 'u')
  946.      *         ->where('u.id = ?');
  947.      *
  948.      *     // You can optionally programmatically build and/or expressions
  949.      *     $qb = $em->createQueryBuilder();
  950.      *
  951.      *     $or = $qb->expr()->orX();
  952.      *     $or->add($qb->expr()->eq('u.id', 1));
  953.      *     $or->add($qb->expr()->eq('u.id', 2));
  954.      *
  955.      *     $qb->update('User', 'u')
  956.      *         ->set('u.password', '?')
  957.      *         ->where($or);
  958.      * </code>
  959.      *
  960.      * @param mixed $predicates The restriction predicates.
  961.      *
  962.      * @return self
  963.      */
  964.     public function where($predicates)
  965.     {
  966.         if (! (func_num_args() === && $predicates instanceof Expr\Composite)) {
  967.             $predicates = new Expr\Andx(func_get_args());
  968.         }
  969.         return $this->add('where'$predicates);
  970.     }
  971.     /**
  972.      * Adds one or more restrictions to the query results, forming a logical
  973.      * conjunction with any previously specified restrictions.
  974.      *
  975.      * <code>
  976.      *     $qb = $em->createQueryBuilder()
  977.      *         ->select('u')
  978.      *         ->from('User', 'u')
  979.      *         ->where('u.username LIKE ?')
  980.      *         ->andWhere('u.is_active = 1');
  981.      * </code>
  982.      *
  983.      * @see where()
  984.      *
  985.      * @param mixed $where The query restrictions.
  986.      *
  987.      * @return self
  988.      */
  989.     public function andWhere()
  990.     {
  991.         $args  func_get_args();
  992.         $where $this->getDQLPart('where');
  993.         if ($where instanceof Expr\Andx) {
  994.             $where->addMultiple($args);
  995.         } else {
  996.             array_unshift($args$where);
  997.             $where = new Expr\Andx($args);
  998.         }
  999.         return $this->add('where'$where);
  1000.     }
  1001.     /**
  1002.      * Adds one or more restrictions to the query results, forming a logical
  1003.      * disjunction with any previously specified restrictions.
  1004.      *
  1005.      * <code>
  1006.      *     $qb = $em->createQueryBuilder()
  1007.      *         ->select('u')
  1008.      *         ->from('User', 'u')
  1009.      *         ->where('u.id = 1')
  1010.      *         ->orWhere('u.id = 2');
  1011.      * </code>
  1012.      *
  1013.      * @see where()
  1014.      *
  1015.      * @param mixed $where The WHERE statement.
  1016.      *
  1017.      * @return self
  1018.      */
  1019.     public function orWhere()
  1020.     {
  1021.         $args  func_get_args();
  1022.         $where $this->getDQLPart('where');
  1023.         if ($where instanceof Expr\Orx) {
  1024.             $where->addMultiple($args);
  1025.         } else {
  1026.             array_unshift($args$where);
  1027.             $where = new Expr\Orx($args);
  1028.         }
  1029.         return $this->add('where'$where);
  1030.     }
  1031.     /**
  1032.      * Specifies a grouping over the results of the query.
  1033.      * Replaces any previously specified groupings, if any.
  1034.      *
  1035.      * <code>
  1036.      *     $qb = $em->createQueryBuilder()
  1037.      *         ->select('u')
  1038.      *         ->from('User', 'u')
  1039.      *         ->groupBy('u.id');
  1040.      * </code>
  1041.      *
  1042.      * @param string $groupBy The grouping expression.
  1043.      *
  1044.      * @return self
  1045.      */
  1046.     public function groupBy($groupBy)
  1047.     {
  1048.         return $this->add('groupBy', new Expr\GroupBy(func_get_args()));
  1049.     }
  1050.     /**
  1051.      * Adds a grouping expression to the query.
  1052.      *
  1053.      * <code>
  1054.      *     $qb = $em->createQueryBuilder()
  1055.      *         ->select('u')
  1056.      *         ->from('User', 'u')
  1057.      *         ->groupBy('u.lastLogin')
  1058.      *         ->addGroupBy('u.createdAt');
  1059.      * </code>
  1060.      *
  1061.      * @param string $groupBy The grouping expression.
  1062.      *
  1063.      * @return self
  1064.      */
  1065.     public function addGroupBy($groupBy)
  1066.     {
  1067.         return $this->add('groupBy', new Expr\GroupBy(func_get_args()), true);
  1068.     }
  1069.     /**
  1070.      * Specifies a restriction over the groups of the query.
  1071.      * Replaces any previous having restrictions, if any.
  1072.      *
  1073.      * @param mixed $having The restriction over the groups.
  1074.      *
  1075.      * @return self
  1076.      */
  1077.     public function having($having)
  1078.     {
  1079.         if (! (func_num_args() === && ($having instanceof Expr\Andx || $having instanceof Expr\Orx))) {
  1080.             $having = new Expr\Andx(func_get_args());
  1081.         }
  1082.         return $this->add('having'$having);
  1083.     }
  1084.     /**
  1085.      * Adds a restriction over the groups of the query, forming a logical
  1086.      * conjunction with any existing having restrictions.
  1087.      *
  1088.      * @param mixed $having The restriction to append.
  1089.      *
  1090.      * @return self
  1091.      */
  1092.     public function andHaving($having)
  1093.     {
  1094.         $args   func_get_args();
  1095.         $having $this->getDQLPart('having');
  1096.         if ($having instanceof Expr\Andx) {
  1097.             $having->addMultiple($args);
  1098.         } else {
  1099.             array_unshift($args$having);
  1100.             $having = new Expr\Andx($args);
  1101.         }
  1102.         return $this->add('having'$having);
  1103.     }
  1104.     /**
  1105.      * Adds a restriction over the groups of the query, forming a logical
  1106.      * disjunction with any existing having restrictions.
  1107.      *
  1108.      * @param mixed $having The restriction to add.
  1109.      *
  1110.      * @return self
  1111.      */
  1112.     public function orHaving($having)
  1113.     {
  1114.         $args   func_get_args();
  1115.         $having $this->getDQLPart('having');
  1116.         if ($having instanceof Expr\Orx) {
  1117.             $having->addMultiple($args);
  1118.         } else {
  1119.             array_unshift($args$having);
  1120.             $having = new Expr\Orx($args);
  1121.         }
  1122.         return $this->add('having'$having);
  1123.     }
  1124.     /**
  1125.      * Specifies an ordering for the query results.
  1126.      * Replaces any previously specified orderings, if any.
  1127.      *
  1128.      * @param string|Expr\OrderBy $sort  The ordering expression.
  1129.      * @param string              $order The ordering direction.
  1130.      *
  1131.      * @return self
  1132.      */
  1133.     public function orderBy($sort$order null)
  1134.     {
  1135.         $orderBy $sort instanceof Expr\OrderBy $sort : new Expr\OrderBy($sort$order);
  1136.         return $this->add('orderBy'$orderBy);
  1137.     }
  1138.     /**
  1139.      * Adds an ordering to the query results.
  1140.      *
  1141.      * @param string|Expr\OrderBy $sort  The ordering expression.
  1142.      * @param string              $order The ordering direction.
  1143.      *
  1144.      * @return self
  1145.      */
  1146.     public function addOrderBy($sort$order null)
  1147.     {
  1148.         $orderBy $sort instanceof Expr\OrderBy $sort : new Expr\OrderBy($sort$order);
  1149.         return $this->add('orderBy'$orderBytrue);
  1150.     }
  1151.     /**
  1152.      * Adds criteria to the query.
  1153.      *
  1154.      * Adds where expressions with AND operator.
  1155.      * Adds orderings.
  1156.      * Overrides firstResult and maxResults if they're set.
  1157.      *
  1158.      * @return self
  1159.      *
  1160.      * @throws Query\QueryException
  1161.      */
  1162.     public function addCriteria(Criteria $criteria)
  1163.     {
  1164.         $allAliases $this->getAllAliases();
  1165.         if (! isset($allAliases[0])) {
  1166.             throw new Query\QueryException('No aliases are set before invoking addCriteria().');
  1167.         }
  1168.         $visitor = new QueryExpressionVisitor($this->getAllAliases());
  1169.         $whereExpression $criteria->getWhereExpression();
  1170.         if ($whereExpression) {
  1171.             $this->andWhere($visitor->dispatch($whereExpression));
  1172.             foreach ($visitor->getParameters() as $parameter) {
  1173.                 $this->parameters->add($parameter);
  1174.             }
  1175.         }
  1176.         if ($criteria->getOrderings()) {
  1177.             foreach ($criteria->getOrderings() as $sort => $order) {
  1178.                 $hasValidAlias false;
  1179.                 foreach ($allAliases as $alias) {
  1180.                     if (strpos($sort '.'$alias '.') === 0) {
  1181.                         $hasValidAlias true;
  1182.                         break;
  1183.                     }
  1184.                 }
  1185.                 if (! $hasValidAlias) {
  1186.                     $sort $allAliases[0] . '.' $sort;
  1187.                 }
  1188.                 $this->addOrderBy($sort$order);
  1189.             }
  1190.         }
  1191.         // Overwrite limits only if they was set in criteria
  1192.         $firstResult $criteria->getFirstResult();
  1193.         if ($firstResult !== null) {
  1194.             $this->setFirstResult($firstResult);
  1195.         }
  1196.         $maxResults $criteria->getMaxResults();
  1197.         if ($maxResults !== null) {
  1198.             $this->setMaxResults($maxResults);
  1199.         }
  1200.         return $this;
  1201.     }
  1202.     /**
  1203.      * Gets a query part by its name.
  1204.      *
  1205.      * @param string $queryPartName
  1206.      *
  1207.      * @return mixed $queryPart
  1208.      */
  1209.     public function getDQLPart($queryPartName)
  1210.     {
  1211.         return $this->_dqlParts[$queryPartName];
  1212.     }
  1213.     /**
  1214.      * Gets all query parts.
  1215.      *
  1216.      * @psalm-return array<string, mixed> $dqlParts
  1217.      */
  1218.     public function getDQLParts()
  1219.     {
  1220.         return $this->_dqlParts;
  1221.     }
  1222.     /**
  1223.      * @return string
  1224.      */
  1225.     private function getDQLForDelete()
  1226.     {
  1227.          return 'DELETE'
  1228.               $this->getReducedDQLQueryPart('from', ['pre' => ' ''separator' => ', '])
  1229.               . $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
  1230.               . $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ''separator' => ', ']);
  1231.     }
  1232.     /**
  1233.      * @return string
  1234.      */
  1235.     private function getDQLForUpdate()
  1236.     {
  1237.          return 'UPDATE'
  1238.               $this->getReducedDQLQueryPart('from', ['pre' => ' ''separator' => ', '])
  1239.               . $this->getReducedDQLQueryPart('set', ['pre' => ' SET ''separator' => ', '])
  1240.               . $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
  1241.               . $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ''separator' => ', ']);
  1242.     }
  1243.     /**
  1244.      * @return string
  1245.      */
  1246.     private function getDQLForSelect()
  1247.     {
  1248.         $dql 'SELECT'
  1249.              . ($this->_dqlParts['distinct'] === true ' DISTINCT' '')
  1250.              . $this->getReducedDQLQueryPart('select', ['pre' => ' ''separator' => ', ']);
  1251.         $fromParts   $this->getDQLPart('from');
  1252.         $joinParts   $this->getDQLPart('join');
  1253.         $fromClauses = [];
  1254.         // Loop through all FROM clauses
  1255.         if (! empty($fromParts)) {
  1256.             $dql .= ' FROM ';
  1257.             foreach ($fromParts as $from) {
  1258.                 $fromClause = (string) $from;
  1259.                 if ($from instanceof Expr\From && isset($joinParts[$from->getAlias()])) {
  1260.                     foreach ($joinParts[$from->getAlias()] as $join) {
  1261.                         $fromClause .= ' ' . ((string) $join);
  1262.                     }
  1263.                 }
  1264.                 $fromClauses[] = $fromClause;
  1265.             }
  1266.         }
  1267.         $dql .= implode(', '$fromClauses)
  1268.               . $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
  1269.               . $this->getReducedDQLQueryPart('groupBy', ['pre' => ' GROUP BY ''separator' => ', '])
  1270.               . $this->getReducedDQLQueryPart('having', ['pre' => ' HAVING '])
  1271.               . $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ''separator' => ', ']);
  1272.         return $dql;
  1273.     }
  1274.     /**
  1275.      * @psalm-param array<string, mixed> $options
  1276.      */
  1277.     private function getReducedDQLQueryPart(string $queryPartName, array $options = []): string
  1278.     {
  1279.         $queryPart $this->getDQLPart($queryPartName);
  1280.         if (empty($queryPart)) {
  1281.             return $options['empty'] ?? '';
  1282.         }
  1283.         return ($options['pre'] ?? '')
  1284.              . (is_array($queryPart) ? implode($options['separator'], $queryPart) : $queryPart)
  1285.              . ($options['post'] ?? '');
  1286.     }
  1287.     /**
  1288.      * Resets DQL parts.
  1289.      *
  1290.      * @psalm-param list<string>|null $parts
  1291.      *
  1292.      * @return self
  1293.      */
  1294.     public function resetDQLParts($parts null)
  1295.     {
  1296.         if ($parts === null) {
  1297.             $parts array_keys($this->_dqlParts);
  1298.         }
  1299.         foreach ($parts as $part) {
  1300.             $this->resetDQLPart($part);
  1301.         }
  1302.         return $this;
  1303.     }
  1304.     /**
  1305.      * Resets single DQL part.
  1306.      *
  1307.      * @param string $part
  1308.      *
  1309.      * @return self
  1310.      */
  1311.     public function resetDQLPart($part)
  1312.     {
  1313.         $this->_dqlParts[$part] = is_array($this->_dqlParts[$part]) ? [] : null;
  1314.         $this->_state           self::STATE_DIRTY;
  1315.         return $this;
  1316.     }
  1317.     /**
  1318.      * Gets a string representation of this QueryBuilder which corresponds to
  1319.      * the final DQL query being constructed.
  1320.      *
  1321.      * @return string The string representation of this QueryBuilder.
  1322.      */
  1323.     public function __toString()
  1324.     {
  1325.         return $this->getDQL();
  1326.     }
  1327.     /**
  1328.      * Deep clones all expression objects in the DQL parts.
  1329.      *
  1330.      * @return void
  1331.      */
  1332.     public function __clone()
  1333.     {
  1334.         foreach ($this->_dqlParts as $part => $elements) {
  1335.             if (is_array($this->_dqlParts[$part])) {
  1336.                 foreach ($this->_dqlParts[$part] as $idx => $element) {
  1337.                     if (is_object($element)) {
  1338.                         $this->_dqlParts[$part][$idx] = clone $element;
  1339.                     }
  1340.                 }
  1341.             } elseif (is_object($elements)) {
  1342.                 $this->_dqlParts[$part] = clone $elements;
  1343.             }
  1344.         }
  1345.         $parameters = [];
  1346.         foreach ($this->parameters as $parameter) {
  1347.             $parameters[] = clone $parameter;
  1348.         }
  1349.         $this->parameters = new ArrayCollection($parameters);
  1350.     }
  1351. }