Skip to content

Commit

Permalink
Model::tryLoad returns null when not found
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek committed May 29, 2022
1 parent d5554c3 commit 7e84f10
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
36 changes: 21 additions & 15 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand All @@ -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;
Expand Down

0 comments on commit 7e84f10

Please sign in to comment.