Lines 90.00% 18 / 20
Functions and Methods 75.00% 3 / 4
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
CalledMethod 90.00% 18 / 20 75.00% 3 / 4 19.36 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 findForCall 80.00% 8 / 10 0.00% 0 / 1 10.80
 isCallTo 100.00% 1 / 1 100.00% 1 / 1 2
 listArgumentValues 100.00% 8 / 8 100.00% 1 / 1 6
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\PHPStan\Rule;
6
7use PhpParser\Node\Arg;
8use PhpParser\Node\Expr;
9use PhpParser\Node\Expr\CallLike;
10use PhpParser\Node\Expr\MethodCall;
11use PhpParser\Node\Expr\New_;
12use PhpParser\Node\Expr\NullsafeMethodCall;
13use PhpParser\Node\Expr\StaticCall;
14use PhpParser\Node\Identifier;
15use PhpParser\Node\Name;
16use PHPStan\Analyser\Scope;
17use PHPStan\Type\ObjectType;
18use PHPStan\Type\Type;
19use PHPStan\Type\TypeCombinator;
20
21final readonly class CalledMethod
22{
23    /** @param list<Arg> $arguments */
24    private function __construct(
25        public Type $callerType,
26        public string $method,
27        private array $arguments,
28    ) {}
29
30    public static function findForCall(CallLike $call, Scope $scope): ?self
31    {
32        if ($call->isFirstClassCallable()) {
33            return null;
34        }
35
36        $arguments = array_values($call->getArgs());
37
38        if (($call instanceof MethodCall || $call instanceof NullsafeMethodCall) && $call->name instanceof Identifier) {
39            return new self(TypeCombinator::removeNull($scope->getType($call->var)), $call->name->toString(), $arguments);
40        }
41
42        if ($call instanceof StaticCall && $call->class instanceof Name && $call->name instanceof Identifier) {
43            return new self(new ObjectType($scope->resolveName($call->class)), $call->name->toString(), $arguments);
44        }
45
46        if ($call instanceof New_ && $call->class instanceof Name) {
47            return new self(new ObjectType($scope->resolveName($call->class)), '__construct', $arguments);
48        }
49
50        return null;
51    }
52
53    public function isCallTo(string $class, string $method): bool
54    {
55        return strcasecmp($this->method, $method) === 0 && new ObjectType($class)->isSuperTypeOf($this->callerType)->yes();
56    }
57
58    /** @return list<Expr> */
59    public function listArgumentValues(int $position, string $name, bool $variadic = false): array
60    {
61        $values = [];
62
63        foreach ($this->arguments as $index => $argument) {
64            $matches = $argument->name === null
65                ? $index === $position || ($variadic && $index > $position)
66                : $argument->name->toString() === $name;
67
68            if ($matches) {
69                $values[] = $argument->value;
70            }
71        }
72
73        return $values;
74    }
75}