From 70d8807f3872a744fc58b61d77f66c5a49710b34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=91cze=20Bence?= Date: Thu, 25 Jun 2020 20:24:37 +0200 Subject: [PATCH] MAPG-156 extend PDM to be able to return with Generator --- src/PersistentData/PersistentDataManager.php | 65 +++++++++++++------- 1 file changed, 42 insertions(+), 23 deletions(-) diff --git a/src/PersistentData/PersistentDataManager.php b/src/PersistentData/PersistentDataManager.php index 3965066..3f2c817 100644 --- a/src/PersistentData/PersistentDataManager.php +++ b/src/PersistentData/PersistentDataManager.php @@ -1,5 +1,6 @@ createSelect($select, $type, $withRelations); - $select->from($table); - - //TODO: only with some relations? - if ($withRelations) { - $relations = call_user_func([$type, 'getRelations']); - - $columns = []; - - foreach ($fields as $field) { - $columns[] = [$table, $field]; - } - - $columns = array_merge($columns, $this->getRelationColumns($relations)); - - $this->leftJoinRelations($select, $table, $relations); - $select->columns($columns); - } else { - $select->columns($fields); - } - - //TODO: return with array? $data = $select->execute()->fetch(IResultSet::FETCH_ASSOC); if ($data === null) { @@ -45,6 +24,18 @@ class PersistentDataManager return $model; } + public function selectMultipleFromDb(Select $select, string $type, bool $withRelations = false): Generator + { + $select = $this->createSelect($select, $type, $withRelations); + + while ($data = $select->execute()->fetch(IResultSet::FETCH_ASSOC)) { + $model = new $type(); + $this->fillWithData($data, $model); + + yield $model; + } + } + public function selectFromDbById($id, string $type, bool $withRelations = false): ?Model { $select = new Select(\Container::$dbConnection); @@ -136,6 +127,34 @@ class PersistentDataManager $model->resetSnapshot(); } + private function createSelect(Select $select, string $type, bool $withRelations = false): Select + { + $table = call_user_func([$type, 'getTable']); + $fields = call_user_func([$type, 'getFields']); + + $select->from($table); + + //TODO: only with some relations? + if ($withRelations) { + $relations = call_user_func([$type, 'getRelations']); + + $columns = []; + + foreach ($fields as $field) { + $columns[] = [$table, $field]; + } + + $columns = array_merge($columns, $this->getRelationColumns($relations)); + + $this->leftJoinRelations($select, $table, $relations); + $select->columns($columns); + } else { + $select->columns($fields); + } + + return $select; + } + private function getRelationColumns(array $relations): array { $columns = [];