Skip to content

Instantly share code, notes, and snippets.

@JacobSanford
Created January 29, 2018 12:34
Show Gist options
  • Save JacobSanford/53c26cc7ffaa94f1c42739e26bfd3ca4 to your computer and use it in GitHub Desktop.
Save JacobSanford/53c26cc7ffaa94f1c42739e26bfd3ca4 to your computer and use it in GitHub Desktop.
Migrate old PHP array syntax (arrray()) to new ([])
<?php
# composer require grom358/pharborist:dev-master
require_once 'vendor/autoload.php';
use Pharborist\Filter;
use Pharborist\Node;
use Pharborist\Parser;
use Pharborist\ParserException;
use Pharborist\TokenNode;
use Pharborist\RootNode;
function processTree(RootNode $tree) {
/**
* Tracks if we made a change to the tree.
* @var bool $modified
*/
$modified = FALSE;
foreach ($tree->find(Filter::isInstanceOf('\Pharborist\Types\ArrayNode')) as $array) {
if ($array->firstChild()->getText() === 'array') {
// Remove any hidden tokens between T_ARRAY and ( .
$array->firstChild()->nextUntil(function (Node $node) {
return $node instanceof TokenNode && $node->getType() === '(';
})->remove();
$array->firstChild()->remove();
$array->firstChild()->replaceWith(new TokenNode('[', '['));
$array->lastChild()->replaceWith(new TokenNode(']', ']'));
$modified = TRUE;
}
}
return $modified;
}
/**
* Process a drupal php file.
*/
function processFile($filename) {
if (substr($filename, 0, strlen('./core/vendor/')) === './core/vendor/') {
return;
}
try {
$tree = Parser::parseFile($filename);
$modified = processTree($tree);
if ($modified) {
file_put_contents($filename, $tree->getText());
}
}
catch (ParserException $e) {
die($filename . ': ' . $e->getMessage() . PHP_EOL);
}
}
$extensions = array('php', 'inc', 'module', 'install', 'theme');
$directory = new \RecursiveDirectoryIterator('.');
$iterator = new \RecursiveIteratorIterator($directory);
$pattern = '/^.+\.(' . implode('|', $extensions) . ')$/i';
$regex = new \RegexIterator($iterator, $pattern, \RecursiveRegexIterator::GET_MATCH);
foreach ($regex as $name => $object) {
processFile($name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment