-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Rule for checking whether a class extends Nette\Object
- Loading branch information
1 parent
062a2e3
commit d1279c0
Showing
3 changed files
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
services: | ||
- | ||
class: PHPStan\Rule\Nette\DoNotExtendNetteObjectRule | ||
tags: | ||
- phpstan.rules.rule |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
<?php declare(strict_types = 1); | ||
|
||
namespace PHPStan\Rule\Nette; | ||
|
||
use PhpParser\Node; | ||
use PhpParser\Node\Stmt\Class_; | ||
use PHPStan\Analyser\Scope; | ||
use PHPStan\Broker\Broker; | ||
|
||
class DoNotExtendNetteObjectRule implements \PHPStan\Rules\Rule | ||
{ | ||
|
||
/** @var \PHPStan\Broker\Broker */ | ||
private $broker; | ||
|
||
public function __construct(Broker $broker) | ||
{ | ||
$this->broker = $broker; | ||
} | ||
|
||
public function getNodeType(): string | ||
{ | ||
return Class_::class; | ||
} | ||
|
||
/** | ||
* @param \PhpParser\Node\Stmt\Class_ $node | ||
* @param \PHPStan\Analyser\Scope $scope | ||
* @return string[] errors | ||
*/ | ||
public function processNode(Node $node, Scope $scope): array | ||
{ | ||
if (!isset($node->namespacedName)) { | ||
// anonymous class - will be possible to inspect | ||
// with node visitor and special ClassBody node | ||
// because $scope will contain the anonymous class reflection | ||
return []; | ||
} | ||
|
||
$className = (string) $node->namespacedName; | ||
if (!$this->broker->hasClass($className)) { | ||
return []; | ||
} | ||
|
||
$classReflection = $this->broker->getClass($className); | ||
if ($classReflection->isSubclassOf(\Nette\Object::class)) { | ||
return [ | ||
sprintf( | ||
"Class %s extends %s - it's better to use %s trait.", | ||
$className, | ||
\Nette\Object::class, | ||
\Nette\SmartObject::class | ||
), | ||
]; | ||
} | ||
|
||
return []; | ||
} | ||
|
||
} |