4 * Class CRM_Core_CodeGen_Util_ArraySyntaxConverter
6 * @link https://github.com/thomasbachem/php-short-array-syntax-converter
8 * @license http://www.gnu.org/licenses/lgpl.html
9 * @author Thomas Bachem <mail@thomasbachem.com>
11 class CRM_Core_CodeGen_Util_ArraySyntaxConverter
{
17 public static function convert($code) {
18 $tokens = token_get_all($code);
20 // - - - - - PARSE CODE - - - - -
21 $replacements = array();
23 for ($i = 0; $i < count($tokens); ++
$i) {
24 // Keep track of the current byte offset in the source code
25 $offset +
= strlen(is_array($tokens[$i]) ?
$tokens[$i][1] : $tokens[$i]);
26 // T_ARRAY could either mean the "array(...)" syntax we're looking for
27 // or a type hinting statement ("function(array $foo) { ... }")
28 if (is_array($tokens[$i]) && $tokens[$i][0] === T_ARRAY
) {
29 // Look for a subsequent opening bracket ("(") to be sure we're actually
30 // looking at an "array(...)" statement
31 $isArraySyntax = FALSE;
33 for ($j = $i +
1; $j < count($tokens); ++
$j) {
34 $subOffset +
= strlen(is_array($tokens[$j]) ?
$tokens[$j][1] : $tokens[$j]);
35 if (is_string($tokens[$j]) && $tokens[$j] == '(') {
36 $isArraySyntax = TRUE;
39 elseif (!is_array($tokens[$j]) ||
$tokens[$j][0] !== T_WHITESPACE
) {
40 $isArraySyntax = FALSE;
45 // Replace "array" and the opening bracket (including preceeding whitespace) with "["
46 $replacements[] = array(
47 'start' => $offset - strlen($tokens[$i][1]),
51 // Look for matching closing bracket (")")
53 $openBracketsCount = 0;
54 for ($j = $i +
1; $j < count($tokens); ++
$j) {
55 $subOffset +
= strlen(is_array($tokens[$j]) ?
$tokens[$j][1] : $tokens[$j]);
56 if (is_string($tokens[$j]) && $tokens[$j] == '(') {
59 elseif (is_string($tokens[$j]) && $tokens[$j] == ')') {
61 if ($openBracketsCount == 0) {
62 // Replace ")" with "]"
63 $replacements[] = array(
64 'start' => $subOffset - 1,
76 // - - - - - UPDATE CODE - - - - -
77 // Apply the replacements to the source code
79 foreach ($replacements as $replacement) {
80 $code = substr_replace(
82 $replacement['string'],
83 $replacement['start'] +
$offsetChange,
84 $replacement['end'] - $replacement['start']
86 $offsetChange +
= strlen($replacement['string']) - ($replacement['end'] - $replacement['start']);