Skip to content

Instantly share code, notes, and snippets.

@grom358
Created April 28, 2014 23:40
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 grom358/11387145 to your computer and use it in GitHub Desktop.
Save grom358/11387145 to your computer and use it in GitHub Desktop.
Convert from old array syntax array(...) to the new shorter array syntax [...]
<?php
require_once 'vendor/autoload.php';
// Import the Pharborist classes
use Pharborist\Filter;
use Pharborist\Node;
use Pharborist\Parser;
use Pharborist\TokenNode;
use Pharborist\TopNode;
function processTree(TopNode $tree) {
/**
* Tracks if we made a change to the tree.
* @var bool $modified
*/
$modified = FALSE;
/**
* Loop over array nodes in the tree.
* @var \Pharborist\ArrayNode $array
*/
foreach ($tree->find(Filter::isInstanceOf('\Pharborist\ArrayNode')) as $array) {
// Test if using old syntax.
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(); // remove T_ARRAY token.
$array->firstChild()->replaceWith(new TokenNode('[', '[')); // replace ( with [ .
$array->lastChild()->replaceWith(new TokenNode(']', ']')); // replace ) with ] .
$modified = TRUE;
}
}
return $modified;
}
/**
* Process a drupal php file.
*/
function processFile($filename) {
if (substr($filename, 0, strlen('./core/vendor/')) === './core/vendor/') {
// Ignore vendor files
return;
}
try {
$tree = Parser::parseFile($filename);
$modified = processTree($tree);
if ($modified) {
file_put_contents($filename, $tree->getText());
}
} catch (\Pharborist\ParserException $e) {
die($filename . ': ' . $e->getMessage() . PHP_EOL);
}
}
// Find drupal php files.
$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);
}
@notslang
Copy link

This fails with multidimensional arrays However, I've fixed that here: https://github.com/slang800/php-array-syntax-converter

@grom358
Copy link
Author

grom358 commented Sep 1, 2014

@slang800 there was a bug with handling of whitespace with multidimensional arrays. This issue should be fixed now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment