Skip to content

Instantly share code, notes, and snippets.

@ondrejmirtes
Created September 9, 2017 17:32
Show Gist options
  • Save ondrejmirtes/7beb3c8abd17f74eb68f7da51136b490 to your computer and use it in GitHub Desktop.
Save ondrejmirtes/7beb3c8abd17f74eb68f7da51136b490 to your computer and use it in GitHub Desktop.
<?php declare(strict_types = 1);
namespace Slevomat\PHPStan\Rules;
class BooleanInBooleanAndRule implements \PHPStan\Rules\Rule
{
public function getNodeType(): string
{
return \PhpParser\Node\Expr\BinaryOp\BooleanAnd::class;
}
/**
* @param \PhpParser\Node\Expr\BinaryOp\BooleanAnd $node
* @param \PHPStan\Analyser\Scope $scope
* @return string[] errors
*/
public function processNode(\PhpParser\Node $node, \PHPStan\Analyser\Scope $scope): array
{
$leftType = $scope->getType($node->left);
if (!BooleanRuleHelper::passesAsBoolean($leftType)) {
return [
sprintf(
'Only booleans are allowed in &&, %s given on the left side.',
$leftType->describe()
),
];
}
$rightType = $scope->getType($node->right);
if (!BooleanRuleHelper::passesAsBoolean($rightType)) {
return [
sprintf(
'Only booleans are allowed in &&, %s given on the right side.',
$rightType->describe()
),
];
}
return [];
}
}
<?php declare(strict_types = 1);
namespace Slevomat\PHPStan\Rules;
class BooleanRuleHelper
{
public static function passesAsBoolean(\PHPStan\Type\Type $type): bool
{
if ($type instanceof \PHPStan\Type\BooleanType) {
return true;
}
if (
$type instanceof \PHPStan\Type\MixedType
&& !$type->isExplicitMixed()
) {
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment