1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Node;
4:
5: use Override;
6: use PhpParser\Node;
7: use PhpParser\NodeAbstract;
8: use PHPStan\Analyser\ResultCache\LazyCollectedData;
9: use PHPStan\Collectors\CollectedData;
10: use PHPStan\Collectors\Collector;
11: use function is_array;
12:
13: /**
14: * @api
15: * @phpstan-import-type CollectorData from CollectedData
16: */
17: final class CollectedDataNode extends NodeAbstract implements VirtualNode
18: {
19:
20: private LazyCollectedData $collectedData;
21:
22: /**
23: * @param CollectorData|LazyCollectedData $collectedData
24: */
25: public function __construct(array|LazyCollectedData $collectedData, private bool $onlyFiles, private ?CollectedDataNodeReads $reads = null)
26: {
27: parent::__construct([]);
28: $this->collectedData = is_array($collectedData) ? LazyCollectedData::fromArray($collectedData) : $collectedData;
29: }
30:
31: /**
32: * @template TCollector of Collector<Node, TValue>
33: * @template TValue
34: * @param class-string<TCollector> $collectorType
35: * @return array<string, list<TValue>>
36: */
37: public function get(string $collectorType): array
38: {
39: $this->reads?->addCollectorType($collectorType);
40:
41: $result = [];
42: foreach ($this->collectedData->iterate($collectorType) as $filePath => $collectedValues) {
43: foreach ($collectedValues as $rawData) {
44: $result[$filePath][] = $rawData;
45: }
46: }
47:
48: return $result;
49: }
50:
51: /**
52: * Like get(), but yields the data of one analysed file at a time instead of returning all of it.
53: * On a large project, a rule that processes each file's data and keeps only what it derives from
54: * it does not hold the whole collected data in memory.
55: *
56: * Every call reads the data again.
57: *
58: * @template TCollector of Collector<Node, TValue>
59: * @template TValue
60: * @param class-string<TCollector> $collectorType
61: * @return iterable<string, list<TValue>>
62: */
63: public function iterate(string $collectorType): iterable
64: {
65: $this->reads?->addCollectorType($collectorType);
66:
67: return $this->collectedData->iterate($collectorType);
68: }
69:
70: /**
71: * Indicates that only files were passed to the analyser, not directory paths.
72: *
73: * True being returned strongly suggests that it's a partial analysis, not full project analysis.
74: */
75: public function isOnlyFilesAnalysis(): bool
76: {
77: $this->reads?->addOnlyFiles();
78:
79: return $this->onlyFiles;
80: }
81:
82: #[Override]
83: public function getType(): string
84: {
85: return 'PHPStan_Node_CollectedDataNode';
86: }
87:
88: /**
89: * @return array{}
90: */
91: #[Override]
92: public function getSubNodeNames(): array
93: {
94: return [];
95: }
96:
97: }
98: