Skip to content

Commit

Permalink
Extract model creation into method and always return model if it exists
Browse files Browse the repository at this point in the history
  • Loading branch information
stevebauman committed Oct 10, 2024
1 parent 1f77c5c commit c153717
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions src/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,11 @@ public function find(?string $id): ?Model
return $this->whereKey($id)->first();
}

$hash = $this->model->getBaseHashWithKey($id);
$attributes = $this->cache->getAttributes($hash);

if (empty($attributes)) {
if (! $this->cache->exists($hash = $this->model->getBaseHashWithKey($id))) {
return null;
}

return $this->model->newFromBuilder([
...$attributes,
$this->model->getKeyName() => $this->getKeyValue($hash),
]);
return $this->newModelFromHash($hash);
}

/**
Expand Down Expand Up @@ -232,10 +226,7 @@ public function chunk(int $count, Closure $callback): void
$models = $this->model->newCollection();

foreach ($chunk as $hash) {
$models->add($this->model->newFromBuilder([
...$this->cache->getAttributes($hash),
$this->model->getKeyName() => $this->getKeyValue($hash),
]));
$models->add($this->newModelFromHash($hash));
}

if ($callback($models) === false) {
Expand All @@ -244,6 +235,17 @@ public function chunk(int $count, Closure $callback): void
}
}

/**
* Create a new model instance from the given hash.
*/
protected function newModelFromHash(string $hash): Model
{
return $this->model->newFromBuilder([
...$this->cache->getAttributes($hash),
$this->model->getKeyName() => $this->getKeyValue($hash),
]);
}

/**
* Get the model key's value from the given hash.
*/
Expand Down

0 comments on commit c153717

Please sign in to comment.