Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions conf/config.level2.neon
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ rules:
- PHPStan\Rules\Generics\MethodTemplateTypeRule
- PHPStan\Rules\Generics\MethodSignatureVarianceRule
- PHPStan\Rules\Generics\TraitTemplateTypeRule
- PHPStan\Rules\Methods\FriendMethodCallRule
- PHPStan\Rules\Methods\IncompatibleDefaultParameterTypeRule
- PHPStan\Rules\Operators\InvalidBinaryOperationRule
- PHPStan\Rules\Operators\InvalidUnaryOperationRule
- PHPStan\Rules\Operators\InvalidComparisonOperationRule
- PHPStan\Rules\PhpDoc\IncompatiblePhpDocTypeRule
- PHPStan\Rules\PhpDoc\IncompatiblePropertyPhpDocTypeRule
- PHPStan\Rules\PhpDoc\InvalidFriendTagTargetRule
- PHPStan\Rules\PhpDoc\InvalidPhpDocTagValueRule
- PHPStan\Rules\PhpDoc\InvalidPHPStanDocTagRule
- PHPStan\Rules\PhpDoc\InvalidThrowsPhpDocValueRule
Expand Down
33 changes: 33 additions & 0 deletions src/PhpDoc/PhpDocNodeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use PHPStan\Analyser\NameScope;
use PHPStan\PhpDoc\Tag\DeprecatedTag;
use PHPStan\PhpDoc\Tag\ExtendsTag;
use PHPStan\PhpDoc\Tag\FriendTag;
use PHPStan\PhpDoc\Tag\ImplementsTag;
use PHPStan\PhpDoc\Tag\MethodTag;
use PHPStan\PhpDoc\Tag\MethodTagParameter;
Expand All @@ -17,17 +18,21 @@
use PHPStan\PhpDoc\Tag\UsesTag;
use PHPStan\PhpDoc\Tag\VarTag;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\MixinTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\ThrowsTagValueNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\Reflection\PassedByReference;
use PHPStan\Type\ErrorType;
use PHPStan\Type\Generic\TemplateTypeVariance;
use PHPStan\Type\MixedType;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeWithClassName;

class PhpDocNodeResolver
{
Expand Down Expand Up @@ -373,6 +378,34 @@ public function resolveIsFinal(PhpDocNode $phpDocNode): bool
return count($finalTags) > 0;
}

/**
* @return array<FriendTag>
*/
public function resolveFriends(PhpDocNode $phpDocNode, NameScope $nameScope): array
{
$potentialFriends = array_map(function (PhpDocTagNode $node) use ($nameScope): ?FriendTag {
$genericTagValue = $node->value;
if (!$genericTagValue instanceof GenericTagValueNode) {
return null;
}
$type = $genericTagValue->value;
if ($type === '') {
return null;
}
$method = null;
if (strpos($type, '::') !== false) {
[$type, $method] = explode('::', $type, 2);
}
$type = $this->typeNodeResolver->resolve(new IdentifierTypeNode($type), $nameScope);
if (!$type instanceof TypeWithClassName) {
return null;
}
return new FriendTag($type, $method);
}, $phpDocNode->getTagsByName('@friend'));

return array_values(array_filter($potentialFriends));
}

private function shouldSkipType(string $tagName, Type $type): bool
{
if (strpos($tagName, '@psalm-') !== 0) {
Expand Down
40 changes: 40 additions & 0 deletions src/PhpDoc/ResolvedPhpDocBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PHPStan\PhpDoc;

use PHPStan\Analyser\NameScope;
use PHPStan\PhpDoc\Tag\FriendTag;
use PHPStan\PhpDoc\Tag\MixinTag;
use PHPStan\PhpDoc\Tag\ParamTag;
use PHPStan\PhpDoc\Tag\ReturnTag;
Expand Down Expand Up @@ -70,6 +71,9 @@ class ResolvedPhpDocBlock

private ?bool $isFinal = null;

/** @var array<FriendTag>|false */
private $friends = false;

private function __construct()
{
}
Expand Down Expand Up @@ -129,6 +133,7 @@ public static function createEmpty(): self
$self->isDeprecated = false;
$self->isInternal = false;
$self->isFinal = false;
$self->friends = [];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This property should be mentioned in merge method too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume it should also read $result->friends = [] as friendship is not inherited? That's what I'm going with now

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or prolly not, added some cases to the test and turns out this way it should be inherited :)


return $self;
}
Expand Down Expand Up @@ -164,6 +169,7 @@ public function merge(array $parents, array $parentPhpDocBlocks): self
$result->isDeprecated = $result->deprecatedTag !== null;
$result->isInternal = $this->isInternal();
$result->isFinal = $this->isFinal();
$result->friends = self::mergeFriendsTags($this->getFriends(), $parents);
return $result;
}

Expand Down Expand Up @@ -204,6 +210,7 @@ public function changeParameterNamesByMapping(array $parameterNameMapping): self
$self->isDeprecated = $this->isDeprecated;
$self->isInternal = $this->isInternal;
$self->isFinal = $this->isFinal;
$self->friends = $this->friends;

return $self;
}
Expand Down Expand Up @@ -402,6 +409,20 @@ public function isFinal(): bool
return $this->isFinal;
}

/**
* @return array<FriendTag>
*/
public function getFriends(): array
{
if ($this->friends === false) {
$this->friends = $this->phpDocNodeResolver->resolveFriends(
$this->phpDocNode,
$this->nameScope
);
}
return $this->friends;
}

public function getTemplateTypeMap(): TemplateTypeMap
{
return $this->templateTypeMap;
Expand Down Expand Up @@ -544,6 +565,25 @@ private static function mergeThrowsTags(?ThrowsTag $throwsTag, array $parents):
return null;
}

/**
* @param array<int, FriendTag> $friendsTag
* @param array<int, self> $parents
* @return array<int, FriendTag>
*/
private static function mergeFriendsTags(array $friendsTag, array $parents): array
{
$merged = [];
foreach ($friendsTag as $friendTag) {
$merged[(string) $friendTag] = $friendTag;
}
foreach ($parents as $parent) {
foreach ($parent->getFriends() as $inheritedFriend) {
$merged[(string) $inheritedFriend] = $inheritedFriend;
}
}
return array_values($merged);
}

/**
* @template T of \PHPStan\PhpDoc\Tag\TypedTag
* @param T $tag
Expand Down
40 changes: 40 additions & 0 deletions src/PhpDoc/Tag/FriendTag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php declare(strict_types = 1);

namespace PHPStan\PhpDoc\Tag;

use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\VerbosityLevel;

class FriendTag
{

private \PHPStan\Type\TypeWithClassName $type;

private ?string $method;

public function __construct(TypeWithClassName $type, ?string $method)
{
$this->type = $type;
$this->method = $method;
}

public function getType(): TypeWithClassName
{
return $this->type;
}

public function getMethod(): ?string
{
return $this->method;
}

public function __toString(): string
{
$string = $this->type->describe(VerbosityLevel::precise());
if ($this->method !== null) {
$string .= '::' . $this->method;
}
return $string;
}

}
92 changes: 92 additions & 0 deletions src/Rules/Methods/FriendMethodCallRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Methods;

use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\FileTypeMapper;

/**
* @implements \PHPStan\Rules\Rule<\PhpParser\Node\Expr\MethodCall>
*/
class FriendMethodCallRule implements \PHPStan\Rules\Rule
{

private FileTypeMapper $fileTypeMapper;

public function __construct(FileTypeMapper $fileTypeMapper)
{
$this->fileTypeMapper = $fileTypeMapper;
}

public function getNodeType(): string
{
return MethodCall::class;
}

public function processNode(Node $node, Scope $scope): array
{
if (!$node->name instanceof Node\Identifier) {
return [];
}
$methodName = $node->name->name;
$callee = $scope->getType($node->var);
if (!$callee->hasMethod($methodName)->yes()) {
return [];
}
$method = $callee->getMethod($methodName, $scope);
if (!$scope->canCallMethod($method)) {
return [];
}
$docComment = $method->getDocComment();
if ($docComment === null || $method->getDeclaringClass()->getFileName() === false) {
return [];
}
$friends = $this->fileTypeMapper->getResolvedPhpDoc(
$method->getDeclaringClass()->getFileName(),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how to approach that this can be false. Should it also result in an early exit?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it means you're calling some internal PHP method.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense :)

$method->getDeclaringClass()->getName(),
null,
$method->getName(),
$docComment
)->getFriends();
if (\count($friends) === 0) {
return [];
}

if (!$scope->isInClass()) {
return [
RuleErrorBuilder::message(sprintf(
'You may not not call %s::%s() from the global scope as the method lists allowed callers through friends.',
$method->getDeclaringClass()->getName(),
$method->getName()
))->build(),
];
}

$callerClass = $scope->getClassReflection();
$callerMethod = $scope->getFunctionName();
foreach ($friends as $friend) {
$type = $friend->getType();
if ($callerClass->getName() !== $type->getClassName()) {
continue;
}
if ($friend->getMethod() !== null && $friend->getMethod() !== $callerMethod) {
continue;
}
return []; // caller is whitelisted
}

return [
RuleErrorBuilder::message(sprintf(
'%s::%s() may not call %s::%s() as it is not listed as a friend.',
$callerClass->getName(),
$callerMethod,
$method->getDeclaringClass()->getName(),
$method->getName()
))->build(),
];
}

}
69 changes: 69 additions & 0 deletions src/Rules/PhpDoc/InvalidFriendTagTargetRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\PhpDoc;

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\FileTypeMapper;

/**
* @implements \PHPStan\Rules\Rule<\PhpParser\Node\Stmt\ClassMethod>
*/
class InvalidFriendTagTargetRule implements \PHPStan\Rules\Rule
{

private FileTypeMapper $fileTypeMapper;

private ReflectionProvider $reflectionProvider;

public function __construct(FileTypeMapper $fileTypeMapper, ReflectionProvider $reflectionProvider)
{
$this->fileTypeMapper = $fileTypeMapper;
$this->reflectionProvider = $reflectionProvider;
}

public function getNodeType(): string
{
return \PhpParser\Node\Stmt\ClassMethod::class;
}

public function processNode(Node $node, Scope $scope): array
{
$docComment = $node->getDocComment();
if ($docComment === null) {
return [];
}
$resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc(
$scope->getFile(),
$scope->isInClass() ? $scope->getClassReflection()->getName() : null,
$scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,
$node->name->name,
$docComment->getText()
);
$errors = [];
foreach ($resolvedPhpDoc->getFriends() as $friendTag) {
$className = $friendTag->getType()->getClassName();
if (!$this->reflectionProvider->hasClass($className)) {
$errors[] = RuleErrorBuilder::message(sprintf(
'Class %s specified by a @friend tag does not exist.',
$className
))->build();
continue;
}
$reflection = $this->reflectionProvider->getClass($className);
$methodName = $friendTag->getMethod();
if ($methodName === null || $reflection->hasMethod($methodName)) {
continue;
}
$errors[] = RuleErrorBuilder::message(sprintf(
'Method %s::%s() specified by a @friend tag does not exist.',
$className,
$methodName
))->build();
}
return $errors;
}

}
Loading