Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastianbergmann/38b138b5254cc39a7c1136dc5a0ce315 to your computer and use it in GitHub Desktop.
Save sebastianbergmann/38b138b5254cc39a7c1136dc5a0ce315 to your computer and use it in GitHub Desktop.
Analyze implicit nullable parameter types
<?php declare(strict_types=1);
error_reporting(-1);
ini_set('memory_limit', -1);
require __DIR__ . '/vendor/autoload.php';
use PhpParser\Node;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\UnionType;
use PhpParser\NodeVisitorAbstract;
use PhpParser\ParserFactory;
$visitor = new class extends NodeVisitorAbstract {
public $path;
public $code;
public function enterNode(Node $node) {
if (!$node instanceof Param) {
return;
}
if (!$node->type || !$node->default) {
return;
}
if ($node->default instanceof ConstFetch === false || $node->default->name->toLowerString() !== "null") {
return;
}
if ($node->type instanceof NullableType) {
return;
}
if ($node->type instanceof UnionType) {
foreach ($node->type->types as $type) {
if ($type instanceof NullableType) {
return;
}
}
}
if ($node->type instanceof Node\Identifier && $node->type->toLowerString() === "mixed") {
return;
}
echo $this->path . ":" . $node->getStartLine() . "\n";
}
};
$traverser = new PhpParser\NodeTraverser;
$traverser->addVisitor($visitor);
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/usr/local/src/phpunit/src'),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($it as $f) {
$path = $f->getPathName();
if (!preg_match('/\.php$/', $path)) {
continue;
}
$code = file_get_contents($path);
try {
$stmts = (new ParserFactory)->createForHostVersion()->parse($code);
} catch (PhpParser\Error $e) {
echo $path . "\n";
echo "Parse error: " . $e->getMessage() . "\n";
continue;
}
$visitor->path = $path;
$visitor->code = $code;
$traverser->traverse($stmts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment