Ensure size is calculated once

This commit is contained in:
Andrea Marco Sartori 2023-01-22 09:47:38 +10:00
parent 7b7e3af470
commit a3f24d3e96

View File

@ -27,6 +27,14 @@ abstract class Source implements IteratorAggregate
*/
protected ?int $size;
/**
* Whether the size was already calculated.
* Avoid re-calculations when the size is NULL (not computable).
*
* @var bool
*/
protected bool $sizeWasSet = false;
/**
* Retrieve the JSON fragments
*
@ -76,6 +84,11 @@ abstract class Source implements IteratorAggregate
*/
public function size(): ?int
{
return $this->size ??= $this->calculateSize();
if(!$this->sizeWasSet) {
$this->size = $this->calculateSize();
$this->sizeWasSet = true;
}
return $this->size;
}
}