/** * Prepare the next item in our collection. * @return null */ public function next() { // If, after moving to the next item in $models we end up with a blank, then // try looking at the next queued element next($this->models); if (!current($this->models)) { // See if a queue element is already active if ($this->active !== null) { // It's a normal array so move the whole lot into $models. We can't use // array_merge here is the unique flag is set as we need to prevent // duplicates from being added to $this->models, so need to check the // persistent IDs. if (is_array($this->active)) { if ($this->isUnique) { foreach ($this->active as $m) { if ($m->isInDatabase()) { $pId = $m->getPersistentId(); if (!isset($this->persistentModels[$pId])) { $this->models[] = $this->persistentModels[$pId] = $m; } } else { $this->models[] = $m; } } } else { $this->models = array_merge($this->models, $this->active); } $this->active = null; } else { if ($this->active instanceof \stdClass) { if ($record = $this->active->stmt->fetch(\PDO::FETCH_ASSOC)) { $model = Model::create($this->active->modelName); $model->populateFromArray($record); $model->isInDatabase(true); $model->hasChanged(false); $pId = $model->isInDatabase() ? $model->getPersistentId() : null; if ($this->isUnique && $pId !== null && isset($this->persistentModels[$pId])) { return $this->next(); } else { $this->models[] = $model; } } else { $this->active->stmt->closeCursor(); $this->active->stmt = null; $this->active = null; } } else { if ($this->active instanceof ModelCollection) { if ($this->active->valid() && ($data = $this->active->current())) { $this->active->next(); $pId = $data->isInDatabase() ? $data->getPersistentId() : null; if ($this->isUnique && $pId !== null && isset($this->persistentModels[$pId])) { $this->next(); return null; } else { $this->models[] = $data; } } else { $this->active = null; $this->next(); } } } } } else { if (!empty($this->queue)) { $this->active = array_shift($this->queue); $this->next(); } } } return null; }