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

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