From 7e84f108026cdac7f65a7a3e369d8cc4cb7d2b3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Vo=C5=99=C3=AD=C5=A1ek?= Date: Sun, 29 May 2022 16:17:48 +0200 Subject: [PATCH] Model::tryLoad returns null when not found --- composer.json | 2 +- src/Model.php | 36 +++++++++++++++++++++--------------- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/composer.json b/composer.json index afb9af6e0..c64d9500f 100644 --- a/composer.json +++ b/composer.json @@ -50,7 +50,7 @@ "friendsofphp/php-cs-fixer": "^3.0", "johnkary/phpunit-speedtrap": "^3.3", "phpstan/extension-installer": "^1.1", - "phpstan/phpstan": "^1.0", + "phpstan/phpstan": "^1.6", "phpstan/phpstan-deprecation-rules": "^1.0", "phpunit/phpunit": "^9.5.5" }, diff --git a/src/Model.php b/src/Model.php index 92ea673ce..6df8dbae2 100644 --- a/src/Model.php +++ b/src/Model.php @@ -1234,9 +1234,9 @@ private function remapIdLoadToPersistence($id) /** * @param mixed $id * - * @return $this + * @return ($fromTryLoad is true ? $this|null : $this) */ - private function _loadThis(bool $isTryLoad, $id) + private function _loadThis(bool $fromTryLoad, $id) { $this->assertIsEntity(); if ($this->isLoaded()) { @@ -1250,21 +1250,27 @@ private function _loadThis(bool $isTryLoad, $id) return $this; } $dataRef = &$this->getDataRef(); - $dataRef = $this->persistence->{$isTryLoad ? 'tryLoad' : 'load'}($this->getModel(), $this->remapIdLoadToPersistence($id)); - if ($isTryLoad && $dataRef === null) { - $dataRef = []; - $this->unload(); - } else { - if ($this->id_field) { - $this->setId($this->getId()); - } + $dataRef = $this->persistence->{$fromTryLoad ? 'tryLoad' : 'load'}($this->getModel(), $this->remapIdLoadToPersistence($id)); - $ret = $this->hook(self::HOOK_AFTER_LOAD); - if ($ret === false) { - $this->unload(); - } elseif (is_object($ret)) { - return $ret; // @phpstan-ignore-line + if ($dataRef === null) { + // $fromTryLoad is true here + + return null; + } + + if ($this->id_field) { + $this->setId($this->getId()); + } + + $ret = $this->hook(self::HOOK_AFTER_LOAD); + if ($ret === false) { + if ($fromTryLoad) { + return null; } + + $this->unload(); + } elseif (is_object($ret)) { + return $ret; // @phpstan-ignore-line } return $this;