Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions src/Parser/CachedParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ final class CachedParser implements Parser

private int $cachedNodesByStringCount = 0;

/** @var array<string, true> */
private array $parsedByString = [];
/** @var array<string, Node\Stmt[]>*/
private array $cachedNodesByFile = [];

private int $cachedNodesByFileCount = 0;

public function __construct(
private Parser $originalParser,
Expand All @@ -30,24 +32,22 @@ public function __construct(
*/
public function parseFile(string $file): array
{
if ($this->cachedNodesByStringCountMax !== 0 && $this->cachedNodesByStringCount >= $this->cachedNodesByStringCountMax) {
$this->cachedNodesByString = array_slice(
$this->cachedNodesByString,
if ($this->cachedNodesByFileCount !== 0 && $this->cachedNodesByFileCount >= $this->cachedNodesByStringCountMax) {
$this->cachedNodesByFile = array_slice(
$this->cachedNodesByFile,
1,
preserve_keys: true,
);

--$this->cachedNodesByStringCount;
--$this->cachedNodesByFileCount;
}

$sourceCode = FileReader::read($file);
if (!isset($this->cachedNodesByString[$sourceCode]) || isset($this->parsedByString[$sourceCode])) {
$this->cachedNodesByString[$sourceCode] = $this->originalParser->parseFile($file);
$this->cachedNodesByStringCount++;
unset($this->parsedByString[$sourceCode]);
if (!isset($this->cachedNodesByFile[$file])) {
$this->cachedNodesByFile[$file] = $this->originalParser->parseFile($file);
$this->cachedNodesByFileCount++;
}

return $this->cachedNodesByString[$sourceCode];
return $this->cachedNodesByFile[$file];
}

/**
Expand All @@ -68,7 +68,6 @@ public function parseString(string $sourceCode): array
if (!isset($this->cachedNodesByString[$sourceCode])) {
$this->cachedNodesByString[$sourceCode] = $this->originalParser->parseString($sourceCode);
$this->cachedNodesByStringCount++;
$this->parsedByString[$sourceCode] = true;
}

return $this->cachedNodesByString[$sourceCode];
Expand Down
Loading