Skip to content

Instantly share code, notes, and snippets.

@OndraM
Last active December 5, 2016 23:26
Show Gist options
  • Save OndraM/d2bb284065f58799d27aa21035b015cb to your computer and use it in GitHub Desktop.
Save OndraM/d2bb284065f58799d27aa21035b015cb to your computer and use it in GitHub Desktop.
Basic PHPStan extension for beberlei/assertion library
<?php declare(strict_types = 1);
namespace PHPStan;
use Assert\Assertion;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\MethodsClassReflectionExtension;
class AssertionClassExtension implements MethodsClassReflectionExtension
{
public function hasMethod(ClassReflection $classReflection, string $methodName): bool
{
return $this->isAssertionClass($classReflection) && $this->isMagicAssertionMethod($methodName);
}
public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection
{
return new AssertionMethodExtension($methodName, $classReflection);
}
/**
* @param ClassReflection $classReflection
* @return bool
*/
private function isAssertionClass(ClassReflection $classReflection)
{
return $classReflection->getName() === Assertion::class || $classReflection->isSubclassOf(Assertion::class);
}
/**
* @param string $methodName
* @return bool
*/
private function isMagicAssertionMethod(string $methodName)
{
return strpos($methodName, 'nullOr') === 0 || strpos($methodName, 'all') === 0;
}
}
<?php declare(strict_types = 1);
namespace PHPStan;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\BooleanType;
use PHPStan\Type\Type;
class AssertionMethodExtension implements MethodReflection
{
/** @var string */
private $methodName;
/** @var ClassReflection */
private $declaringClass;
/**
* @param string $methodName
* @param ClassReflection $declaringClass
*/
public function __construct(string $methodName, ClassReflection $declaringClass)
{
$this->methodName = $methodName;
$this->declaringClass = $declaringClass;
}
public function getDeclaringClass(): ClassReflection
{
return $this->declaringClass;
}
public function isStatic(): bool
{
return true;
}
public function isPrivate(): bool
{
return false;
}
public function isPublic(): bool
{
return true;
}
public function getName(): string
{
return $this->methodName;
}
public function getParameters(): array
{
return [];
}
public function isVariadic(): bool
{
return true;
}
public function getReturnType(): Type
{
return new BooleanType(false);
}
}
services:
-
class: PHPStan\AssertionClassExtension
tags:
- phpstan.broker.methodsClassReflectionExtension
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment