-
-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add NoValueObjectInServiceConstructorRule (#152)
- Loading branch information
1 parent
7beae59
commit 3cb4dda
Showing
2 changed files
with
77 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,72 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Symplify\PHPStanRules\Rules; | ||
|
||
use PhpParser\Node; | ||
use PhpParser\Node\Name; | ||
use PhpParser\Node\Stmt\ClassMethod; | ||
use PHPStan\Analyser\Scope; | ||
use PHPStan\Rules\Rule; | ||
use PHPStan\Rules\RuleErrorBuilder; | ||
use Symplify\PHPStanRules\Enum\RuleIdentifier; | ||
|
||
/** | ||
* @implements Rule<ClassMethod> | ||
*/ | ||
final class NoValueObjectInServiceConstructorRule implements Rule | ||
{ | ||
public function getNodeType(): string | ||
{ | ||
return ClassMethod::class; | ||
} | ||
|
||
/** | ||
* @param ClassMethod $node | ||
*/ | ||
public function processNode(Node $node, Scope $scope): array | ||
{ | ||
if ($node->name->toString() !== '__construct') { | ||
return []; | ||
} | ||
|
||
if (! $scope->isInClass()) { | ||
return []; | ||
} | ||
|
||
$classReflection = $scope->getClassReflection(); | ||
|
||
// value objects can accept value objects | ||
if ($this->isValueObject($classReflection->getName())) { | ||
return []; | ||
} | ||
|
||
$ruleErrors = []; | ||
|
||
foreach ($node->params as $param) { | ||
if (! $param->type instanceof Name) { | ||
continue; | ||
} | ||
|
||
$paramType = $param->type->toString(); | ||
if (! $this->isValueObject($paramType)) { | ||
continue; | ||
} | ||
|
||
$ruleErrors[] = RuleErrorBuilder::message(sprintf( | ||
'Value object "%s" cannot be passed to constructor of a service. Pass it as a method argument instead', | ||
$paramType | ||
)) | ||
->identifier(RuleIdentifier::NO_VALUE_OBJECT_IN_SERVICE_CONSTRUCTOR) | ||
->build(); | ||
} | ||
|
||
return $ruleErrors; | ||
} | ||
|
||
private function isValueObject(string $className): bool | ||
{ | ||
return preg_match('#(ValueObject|DataObject|Models)#', $className) === 1; | ||
} | ||
} |