Skip to content

Commit

Permalink
Rule for checking whether a class extends Nette\Object
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jan 21, 2017
1 parent 062a2e3 commit d1279c0
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ This extension provides following features:
* Magic [Nette\Object and Nette\SmartObject](https://doc.nette.org/en/2.4/php-language-enhancements) properties
* Event listeners through the `on*` properties

It also contains this framework-specific rule (can be enabled separately):

* Do not extend Nette\Object, use Nette\SmartObject trait instead

## Usage

To use this extension, require it in [Composer](https://getcomposer.org/):
Expand All @@ -27,3 +31,9 @@ And include extension.neon in your project's PHPStan config:
includes:
- vendor/phpstan/phpstan-nette/extension.neon
```

To perform framework-specific checks, include also this file:

```
- vendor/phpstan/phpstan-nette/rules.neon
```
5 changes: 5 additions & 0 deletions rules.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
services:
-
class: PHPStan\Rule\Nette\DoNotExtendNetteObjectRule
tags:
- phpstan.rules.rule
60 changes: 60 additions & 0 deletions src/Rule/Nette/DoNotExtendNetteObjectRule.php
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 [];
}

}

0 comments on commit d1279c0

Please sign in to comment.