Example #1
0
 /**
  * Iterates over each result of a query, calling a callback for each one. The
  * items are processed in an unspecified order. The query may not have any
  * sort order, and may not use limit or skip.
  *
  * @param callable $callback     Callback that will be called with each result
  *                               of the query.
  * @param bool     $useMasterKey
  * @param int      $batchSize
  *
  * @throws \Exception If query has sort, skip, or limit.
  */
 public function each($callback, $useMasterKey = false, $batchSize = 100)
 {
     if ($this->orderBy || $this->skip || $this->limit >= 0) {
         throw new Exception('Cannot iterate on a query with sort, skip, or limit.');
     }
     $query = new self($this->className);
     $query->where = $this->where;
     $query->includes = $this->includes;
     $query->limit = $batchSize;
     $query->ascending('objectId');
     $finished = false;
     while (!$finished) {
         $results = $query->find($useMasterKey);
         $length = count($results);
         for ($i = 0; $i < $length; $i++) {
             $callback($results[$i]);
         }
         if ($length == $query->limit) {
             $query->greaterThan('objectId', $results[$length - 1]->getObjectId());
         } else {
             $finished = true;
         }
     }
 }