db = $db; } /** * Set project for migration. */ public function setProject(Document $project, Database $projectDB): Migration { $this->project = $project; $this->projectDB = $projectDB; $this->projectDB->setNamespace('app_' . $project->getId()); return $this; } /** * Iterates through every document. * * @param callable(Document):Document $callback */ public function forEachDocument(callable $callback) { $sum = 30; $offset = 0; while ($sum >= 30) { $all = $this->projectDB->getCollection([ 'limit' => $this->limit, 'offset' => $offset, 'orderType' => 'DESC', ]); $sum = \count($all); Console::log('Migrating: ' . $offset . ' / ' . $this->projectDB->getSum()); foreach ($all as $document) { $document = call_user_func($callback, $document); if (empty($document->getId())) { throw new Exception('Missing ID'); } try { $new = $this->projectDB->overwriteDocument($document->getArrayCopy()); } catch (\Throwable $th) { var_dump($document); Console::error('Failed to update document: ' . $th->getMessage()); continue; } if ($new->getId() !== $document->getId()) { throw new Exception('Duplication Error'); } } $offset += $this->limit; } } /** * Executes migration for set project. */ abstract public function execute(): void; }