From 7cc03783820f8ea4a64aad358221ac57d1e51c1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Vo=C5=99=C3=AD=C5=A1ek?= Date: Mon, 17 Jan 2022 12:53:06 +0100 Subject: [PATCH] prefer limit 2 and getRows() --- src/Persistence/Array_.php | 12 +++++++----- src/Persistence/Array_/Action.php | 1 + 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Persistence/Array_.php b/src/Persistence/Array_.php index 32b8f9dbe5..637f1bdb7d 100644 --- a/src/Persistence/Array_.php +++ b/src/Persistence/Array_.php @@ -215,18 +215,20 @@ public function tryLoad(Model $model, $id): ?array if ($id === self::ID_LOAD_ONE || $id === self::ID_LOAD_ANY) { $action = $this->action($model, 'select'); - $selectRow = $action->getRow(); - if ($selectRow === null) { + $action->limit($id === self::ID_LOAD_ANY ? 1 : 2); + + $rowsRaw = $action->getRows(); + if (count($rowsRaw) === 0) { return null; - } elseif ($id === self::ID_LOAD_ONE && $action->getRow() !== null) { + } elseif (count($rowsRaw) !== 1) { throw (new Exception('Ambiguous conditions, more than one record can be loaded.')) ->addMoreInfo('model', $model) ->addMoreInfo('id', null); } - $id = $selectRow[$model->id_field]; + $idRaw = reset($rowsRaw)[$model->id_field]; - $row = $this->tryLoad($model, $id); + $row = $this->tryLoad($model, $idRaw); return $row; } diff --git a/src/Persistence/Array_/Action.php b/src/Persistence/Array_/Action.php index e5af81c756..e4f83323dd 100644 --- a/src/Persistence/Array_/Action.php +++ b/src/Persistence/Array_/Action.php @@ -296,6 +296,7 @@ public function getRows(): array */ public function getRow(): ?array { + $this->generator->rewind(); // TODO alternatively allow to fetch only once $row = $this->generator->current(); $this->generator->next();