Lines 98.24% 56 / 57
Methods 87.50% 7 / 8
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 getNodeType 100.00% 1 / 1 100.00% 1 / 1 1
 processNode 100.00% 11 / 11 100.00% 1 / 1 9
 checkActionNames 100.00% 9 / 9 100.00% 1 / 1 4
 checkEntityActions 100.00% 9 / 9 100.00% 1 / 1 5
 findEntityDomain 91.66% 11 / 12 0.00% 0 / 1 7.03
 listLiterals 100.00% 5 / 5 100.00% 1 / 1 3
 buildUnknownActionError 100.00% 9 / 9 100.00% 1 / 1 2
28final readonly class ActionNameArgumentRule implements Rule
29{
30    private const string IDENTIFIER = 'stewart.actionName';
31
32    private const array ACTION_METHODS = ['callAction', 'callActionForResponse'];
33
34    public function __construct(
35        private ManifestCatalogLoader $manifests,
36        private EntityIdLiterals $literals,
37        private TestCodeScope $testCode,
38        private GeneratedHandles $handles,
39        private ClosestNameFinder $names,
40    ) {}
41
42    public function getNodeType(): string
43    {
44        return CallLike::class;
45    }
46
47    /**
48     * @param Scope&DependencyTracker $scope
49     * @return list<IdentifierRuleError>
50     */
51    public function processNode(Node $node, Scope $scope): array
52    {
53        $called = CalledMethod::findForCall($node, $scope);
54
55        if ($called === null || $this->testCode->isInTestCode($scope)) {
56            return [];
57        }
58
59        foreach (self::ACTION_METHODS as $method) {
60            if ($called->isCallTo(HaContext::class, $method)) {
61                $catalog = $this->manifests->findCatalogTrackedBy($scope);
62
63                return $catalog === null ? [] : $this->checkActionNames($called, $scope, $catalog);
64            }
65
66            if ($called->isCallTo(Entity::class, $method) && $node instanceof MethodCall) {
67                $catalog = $this->manifests->findCatalogTrackedBy($scope);
68
69                return $catalog === null ? [] : $this->checkEntityActions($called, $scope, $catalog, $this->findEntityDomain($node->var, $scope));
70            }
71        }
72
73        return [];
74    }
75
76    /** @return list<IdentifierRuleError> */
77    private function checkActionNames(CalledMethod $called, Scope $scope, ManifestCatalog $catalog): array
78    {
79        $errors = [];
80
81        foreach ($this->listLiterals($called, $scope) as $actionName) {
82            try {
83                new ActionName($actionName);
84            } catch (ActionCallException $e) {
85                $errors[] = RuleErrorBuilder::message($e->getMessage())->identifier(self::IDENTIFIER)->build();
86
87                continue;
88            }
89
90            if (!$catalog->knowsAction($actionName)) {
91                $errors[] = $this->buildUnknownActionError($actionName, $catalog);
92            }
93        }
94
95        return $errors;
96    }
97
98    /** @return list<IdentifierRuleError> */
99    private function checkEntityActions(CalledMethod $called, Scope $scope, ManifestCatalog $catalog, ?string $domain): array
100    {
101        $errors = [];
102
103        foreach ($this->listLiterals($called, $scope) as $action) {
104            if (str_contains($action, '.')) {
105                $errors[] = RuleErrorBuilder::message(\sprintf('Entity::%s() takes the action alone, such as "turn_on", not "%s".', $called->method, $action))
106                    ->identifier(self::IDENTIFIER)
107                    ->build();
108            } elseif ($domain !== null && !$catalog->knowsAction($domain . '.' . $action)) {
109                $errors[] = $this->buildUnknownActionError($domain . '.' . $action, $catalog);
110            }
111        }
112
113        return $errors;
114    }
115
116    // Only a receiver that names its entity right there, $ha->getEntity('light.hall') or a generated handle, has a known domain.
117    private function findEntityDomain(Expr $receiver, Scope $scope): ?string
118    {
119        if (!$receiver instanceof MethodCall) {
120            return null;
121        }
122
123        $called = CalledMethod::findForCall($receiver, $scope);
124
125        if ($called?->isCallTo(HaContext::class, 'getEntity') === true) {
126            $entityIds = [];
127
128            foreach ($called->listArgumentValues(0, 'entityId') as $value) {
129                $entityIds = [...$entityIds, ...$this->literals->listEntityIds($scope->getType($value))];
130            }
131
132            return \count($entityIds) === 1 ? new EntityId($entityIds[0])->domain : null;
133        }
134
135        if ($called?->isCallTo(TypedEntity::class, 'getEntity') === true) {
136            $handleClasses = $called->callerType->getObjectClassNames();
137
138            return \count($handleClasses) === 1 ? $this->handles->findDomain($handleClasses[0]) : null;
139        }
140
141        return null;
142    }
143
144    /** @return list<string> */
145    private function listLiterals(CalledMethod $called, Scope $scope): array
146    {
147        $literals = [];
148
149        foreach ($called->listArgumentValues(0, 'action') as $value) {
150            foreach ($scope->getType($value)->getConstantStrings() as $string) {
151                $literals[] = $string->getValue();
152            }
153        }
154
155        return $literals;
156    }
157
158    private function buildUnknownActionError(string $actionName, ManifestCatalog $catalog): IdentifierRuleError
159    {
160        $suggestion = $this->names->findClosestName($actionName, $catalog->listActionNames());
161
162        return RuleErrorBuilder::message(\sprintf(
163            'Action "%s" was not in Home Assistant at the last stewart generate.%s',
164            $actionName,
165            $suggestion === null ? '' : \sprintf(' Did you mean "%s"?', $suggestion),
166        ))
167            ->identifier(self::IDENTIFIER)
168            ->tip('Run make generate if the action is new, such as one from a script or an integration added since.')
169            ->build();
170    }
171}