4  * Change the second argument of "addOption" to null.
 
   6  * Copyright (C) 2017  Antonio Ospite <ao2@ao2.it>
 
  10  * php-parse is installed with:
 
  11  *  composer global require nikic/php-parser
 
  13 include getenv('HOME') . '/.config/composer/vendor/autoload.php';
 
  16 use PhpParser\NodeTraverser;
 
  17 use PhpParser\NodeVisitorAbstract;
 
  18 use PhpParser\ParserFactory;
 
  19 use PhpParser\PrettyPrinter;
 
  21 class AddOptionSecondArgumentVisitor extends NodeVisitorAbstract {
 
  23   public function leaveNode(Node $node) {
 
  24     if ($node instanceof Node\Expr\MethodCall && $node->name === "addOption") {
 
  26       $shortname_arg = $node->args[1];
 
  28       // If it's a constant expression (e.g. false or null) make it null.
 
  29       if ($shortname_arg->value instanceof Node\Expr\ConstFetch) {
 
  30         $shortname_arg->value->name = new Node\Name("null");
 
  32       elseif ($shortname_arg->value instanceof Node\Scalar\String_) {
 
  33         // If it's an empty string, make it null keeping the attributes.
 
  34         if (empty($shortname_arg->value->value)) {
 
  35           $old_attributes = $shortname_arg->value->getAttributes();
 
  36           $shortname_arg->value = new Node\Expr\ConstFetch(new Node\Name("null"), $old_attributes);
 
  40         echo "UNEXPECTED argument type\n";
 
  47 $parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
 
  48 $traverser = new NodeTraverser();
 
  49 $prettyPrinter = new PrettyPrinter\Standard();
 
  51 $traverser->addVisitor(new AddOptionSecondArgumentVisitor());
 
  54   $code = file_get_contents($argv[1]);
 
  55   $stmts = $parser->parse($code);
 
  56   $stmts = $traverser->traverse($stmts);
 
  58   // $stmts is an array of statement nodes.
 
  59   $code = $prettyPrinter->prettyPrintFile($stmts);
 
  64   echo 'Parse Error: ', $e->getMessage();