Skip to content

Commit

Permalink
All of these should be a violation
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Apr 17, 2022
1 parent f7cd97a commit 18930cc
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 24 deletions.
17 changes: 0 additions & 17 deletions src/Rules/Methods/IllegalConstructorMethodCallRule.php
Expand Up @@ -24,27 +24,10 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

if ($this->isCollectCallingConstructor($node, $scope)) {
return [];
}

return [
RuleErrorBuilder::message('Call to __construct() on an existing object is not allowed.')
->build(),
];
}

private function isCollectCallingConstructor(Node $node, Scope $scope): bool
{
if (!$node instanceof Node\Expr\MethodCall) {
return true;
}
// __construct should be called from inside constructor
if ($scope->getFunction() !== null && $scope->getFunction()->getName() !== '__construct') {
return false;
}
// In constructor, method call is allowed with 'this';
return $node->var instanceof Node\Expr\Variable && $node->var->name === 'this';
}

}
8 changes: 1 addition & 7 deletions src/Rules/Methods/IllegalConstructorStaticCallRule.php
Expand Up @@ -52,13 +52,7 @@ private function isCollectCallingConstructor(Node $node, Scope $scope): bool
return false;
}

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

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

return $className === $scope->getClassReflection()->getName();
return $node->class->toLowerString() === 'parent';
}

}
Expand Up @@ -19,6 +19,10 @@ protected function getRule(): Rule
public function testMethods(): void
{
$this->analyse([__DIR__ . '/data/illegal-constructor-call-rule-test.php'], [
[
'Call to __construct() on an existing object is not allowed.',
13,
],
[
'Call to __construct() on an existing object is not allowed.',
18,
Expand Down
Expand Up @@ -23,6 +23,14 @@ public function testMethods(): void
'Static call to __construct() is only allowed on a parent class in the constructor.',
31,
],
[
'Static call to __construct() is only allowed on a parent class in the constructor.',
43,
],
[
'Static call to __construct() is only allowed on a parent class in the constructor.',
44,
],
[
'Static call to __construct() is only allowed on a parent class in the constructor.',
49,
Expand Down

0 comments on commit 18930cc

Please sign in to comment.