Skip to content

Commit

Permalink
Behave the same way with "self" like with the actual class name
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Apr 17, 2022
1 parent 72a3a3d commit 4daa27c
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 5 deletions.
19 changes: 16 additions & 3 deletions src/Rules/Methods/IllegalConstructorStaticCallRule.php
Expand Up @@ -6,7 +6,6 @@
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use function in_array;

/**
* @implements Rule<Node\Expr\StaticCall>
Expand Down Expand Up @@ -44,8 +43,22 @@ private function isCollectCallingConstructor(Node $node, Scope $scope): bool
if ($scope->getFunction() !== null && $scope->getFunction()->getName() !== '__construct') {
return false;
}
// In constructor, static call is allowed with 'self' or 'parent;
return $node->class instanceof Node\Name && in_array($node->class->getFirst(), ['self', 'parent'], true);

if (!$scope->isInClass()) {
return false;
}

if (!$node->class instanceof Node\Name) {
return false;
}

if ($node->class->toLowerString() === 'parent') {
return true;
}

$className = $scope->resolveName($node->class);

return $className === $scope->getClassReflection()->getName();
}

}
Expand Up @@ -25,7 +25,7 @@ public function testMethods(): void
],
[
'Call to __construct() on an existing object is not allowed.',
56,
58,
],
]);
}
Expand Down
Expand Up @@ -25,7 +25,11 @@ public function testMethods(): void
],
[
'Static call to __construct() is only allowed on a parent class in the constructor.',
46,
47,
],
[
'Static call to __construct() is only allowed on a parent class in the constructor.',
48,
],
]);
}
Expand Down
Expand Up @@ -39,11 +39,13 @@ public function __construct(string $datetime = "now", ?DateTimeZone $timezone =
return;
}
self::__construct($datetime, $timezone);
ExtendedDateTimeWithSelfCall::__construct($datetime, $timezone);
}

public function mutate(string $datetime = "now", ?DateTimeZone $timezone = null): void
{
self::__construct($datetime, $timezone);
ExtendedDateTimeWithSelfCall::__construct($datetime, $timezone);
}
}

Expand Down

0 comments on commit 4daa27c

Please sign in to comment.