Lines 97.05% 66 / 68
Methods 83.33% 5 / 6
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 22 / 22 100.00% 1 / 1 1
 getNodeType 100.00% 1 / 1 100.00% 1 / 1 1
 processNode 89.47% 17 / 19 0.00% 0 / 1 11.14
 listGeneratedHandleClasses 100.00% 4 / 4 100.00% 1 / 1 3
 checkGeneratedGetter 100.00% 13 / 13 100.00% 1 / 1 7
 buildUnknownEntityError 100.00% 9 / 9 100.00% 1 / 1 2
29final readonly class EntityIdArgumentRule implements Rule
30{
31    private const string IDENTIFIER = 'stewart.entityId';
32
33    private const string GENERATED_GETTER = 'getEntity';
34
35    /** @var list<EntityIdParameter> */
36    private array $parameters;
37
38    public function __construct(
39        private ManifestCatalogLoader $manifests,
40        private EntityIdLiterals $literals,
41        private TestCodeScope $testCode,
42        private GeneratedHandles $handles,
43        private ClosestNameFinder $names,
44    ) {
45        $this->parameters = [
46            new EntityIdParameter(HaContext::class, 'getState', 'entityId'),
47            new EntityIdParameter(HaContext::class, 'requireState', 'entityId'),
48            new EntityIdParameter(HaContext::class, 'getHeldStateDuration', 'entityId'),
49            new EntityIdParameter(HaContext::class, 'hasHeldStateFor', 'entityId'),
50            new EntityIdParameter(HaContext::class, 'getEntity', 'entityId'),
51            new EntityIdParameter(HaContext::class, 'getHistory', 'entityId'),
52            new EntityIdParameter(HaContext::class, 'waitForState', 'entityId'),
53            new EntityIdParameter(HaContext::class, 'listStates', 'selector'),
54            new EntityIdParameter(HaContext::class, 'watchStateChanges', 'selector'),
55            new EntityIdParameter(ActionTarget::class, 'forEntities', 'entityIds', variadic: true),
56            new EntityIdParameter(Scheduler::class, 'runAtEntityTime', 'entity'),
57            new EntityIdParameter(HaTrigger::class, 'atTime', 'time'),
58            new EntityIdParameter(HaTrigger::class, 'onZoneTransition', 'entity'),
59            new EntityIdParameter(HaTrigger::class, 'onZoneTransition', 'zone', position: 1),
60            new EntityIdParameter(Registry::class, 'findEntity', 'entityId'),
61            new EntityIdParameter(Registry::class, 'findEntityPlacement', 'entityId'),
62            new EntityIdParameter(RegistryEditor::class, 'updateEntity', 'entityId'),
63            new EntityIdParameter(EntityId::class, '__construct', 'value'),
64            new EntityIdParameter(EntityId::class, 'fromStringOrId', 'id'),
65            new EntityIdParameter(EntityId::class, 'tryFromString', 'value'),
66        ];
67    }
68
69    public function getNodeType(): string
70    {
71        return CallLike::class;
72    }
73
74    /**
75     * @param Scope&DependencyTracker $scope
76     * @return list<IdentifierRuleError>
77     */
78    public function processNode(Node $node, Scope $scope): array
79    {
80        $called = CalledMethod::findForCall($node, $scope);
81
82        if ($called === null || $this->testCode->isInTestCode($scope)) {
83            return [];
84        }
85
86        $parameters = array_values(array_filter($this->parameters, static fn(EntityIdParameter $parameter): bool => $called->isCallTo($parameter->class, $parameter->method)));
87        $handleClasses = $this->listGeneratedHandleClasses($node, $called, $scope);
88
89        if ($parameters === [] && $handleClasses === []) {
90            return [];
91        }
92
93        $catalog = $this->manifests->findCatalogTrackedBy($scope);
94
95        if ($catalog === null) {
96            return [];
97        }
98
99        $errors = [];
100
101        foreach ($parameters as $parameter) {
102            foreach ($called->listArgumentValues($parameter->position, $parameter->name, $parameter->variadic) as $value) {
103                foreach ($this->literals->listEntityIds($scope->getType($value)) as $entityId) {
104                    if (!$catalog->knowsEntity($entityId)) {
105                        $errors[] = $this->buildUnknownEntityError($entityId, $catalog);
106                    }
107                }
108            }
109        }
110
111        foreach ($handleClasses as $handleClass) {
112            $errors = [...$errors, ...$this->checkGeneratedGetter($handleClass, $called, $scope, $catalog)];
113        }
114
115        return $errors;
116    }
117
118    /** @return list<string> */
119    private function listGeneratedHandleClasses(CallLike $node, CalledMethod $called, Scope $scope): array
120    {
121        $handle = $scope->getType($node);
122
123        if (strcasecmp($called->method, self::GENERATED_GETTER) !== 0 || !new ObjectType(TypedEntity::class)->isSuperTypeOf($handle)->yes()) {
124            return [];
125        }
126
127        return array_values(array_filter($handle->getObjectClassNames(), $this->handles->isHandle(...)));
128    }
129
130    // A generated <Domain>Entities::getEntity() throws EntityNotGenerated for anything its domain did not generate.
131    /** @return list<IdentifierRuleError> */
132    private function checkGeneratedGetter(string $handleClass, CalledMethod $called, Scope $scope, ManifestCatalog $catalog): array
133    {
134        $errors = [];
135
136        foreach ($called->listArgumentValues(0, 'id') as $value) {
137            foreach ($this->literals->listEntityIds($scope->getType($value)) as $entityId) {
138                if ($this->handles->isGeneratedEntityId($handleClass, $entityId)) {
139                    continue;
140                }
141
142                $errors[] = match (true) {
143                    $catalog->isIgnoredEntity($entityId) => RuleErrorBuilder::message(\sprintf('Entity ID "%s" is left out of the generated classes, so getEntity() throws EntityNotGenerated.', $entityId))
144                        ->identifier(self::IDENTIFIER)
145                        ->tip('Use HaContext::getEntity() for it, or include it in codegen.')
146                        ->build(),
147                    $catalog->knowsEntity($entityId) => RuleErrorBuilder::message(\sprintf('Entity ID "%s" is not a %s entity, so this getEntity() throws EntityNotGenerated.', $entityId, $this->handles->findDomain($handleClass)))
148                        ->identifier(self::IDENTIFIER)
149                        ->build(),
150                    default => $this->buildUnknownEntityError($entityId, $catalog),
151                };
152            }
153        }
154
155        return $errors;
156    }
157
158    private function buildUnknownEntityError(string $entityId, ManifestCatalog $catalog): IdentifierRuleError
159    {
160        $suggestion = $this->names->findClosestName($entityId, $catalog->listKnownEntityIds());
161
162        return RuleErrorBuilder::message(\sprintf(
163            'Entity ID "%s" was not in Home Assistant at the last stewart generate.%s',
164            $entityId,
165            $suggestion === null ? '' : \sprintf(' Did you mean "%s"?', $suggestion),
166        ))
167            ->identifier(self::IDENTIFIER)
168            ->tip('Run make generate if the entity is new.')
169            ->build();
170    }
171}