Skip to content

Composer integration, PSR coding standards #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ Command-line script to convert PHP's `array()` syntax to PHP 5.4's short array s

By relying on the PHP tokenizer, nothing but the array syntax itself will be altered. The script was successfully tested against code bases with more than 5.000 PHP files.

Installation via Composer
===========
Just add `"thomasbachem/php-short-array-syntax-converter": "dev-master"` to your require(-dev) section and run update command on Composer.

Usage
================================

Usage: php convert.php [-w] <file>
Usage: php array-converter.php [-w] <file>

Run the script with the path of the PHP file you wish to convert as argument. This will print the converted source code to STDOUT.

Expand All @@ -19,7 +22,7 @@ In case of any error, an error message is written to STDERR and the script exits

Use `find` to convert a whole directory recursively:

find <directory> -name "*.php" -exec php "convert.php" -w "{}" \;
find <directory> -name "*.php" -exec php "array-converter.php" -w "{}" \;

In case you don't trust the script yet, you can even perform a syntax check after conversion:

Expand Down
147 changes: 147 additions & 0 deletions array-converter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
<?php

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use git mv to move this file.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

git mv might not do what you think it does. He likely made enough changes to the file that it's no longer recognized as a rename.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@evanpurkhiser Thank you)


/**
* PHP 5.4 Short Array Syntax Converter
*
* Command-line script to convert PHP's "array()" syntax to PHP 5.4's
* short array syntax "[]" using PHP's built-in tokenizer.
*
* This script is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License (LGPL) as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* @link https://github.com/thomasbachem/php-short-array-syntax-converter
*
* @link http://php.net/manual/en/language.types.array.php
*
* @license http://www.gnu.org/licenses/lgpl.html
* @author Thomas Bachem <[email protected]>
*/


// - - - - - HANDLE COMMAND LINE ARGUMENTS - - - - -

$filePath = null;
$saveFile = false;

if ($argc > 3) {
file_put_contents('php://stderr', 'Usage: php convert.php [-w] <file>' . "\n");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'Usage: php array-converter.php…'

exit(1);
}
for ($i = 1; $i < $argc; ++$i) {
if ($argv[$i] && $argv[$i][0] == '-') {
$saveFile = ($argv[$i] == '-w');
} else {
$filePath = $argv[$i];
}
}

if (!$filePath) {
file_put_contents('php://stderr', 'Usage: php array-converter.php [-w] <file>' . "\n");
exit(1);
} elseif (!file_exists($filePath)) {
file_put_contents('php://stderr', 'File "' . $filePath . '" not found.' . "\n");
exit(1);
}


// - - - - - READ ORIGINAL CODE - - - - -

$code = file_get_contents($filePath);
$tokens = token_get_all($code);


// - - - - - PARSE CODE - - - - -

$replacements = array();
$offset = 0;
for ($i = 0; $i < count($tokens); ++$i) {
// Keep track of the current byte offset in the source code
$offset += strlen(is_array($tokens[$i]) ? $tokens[$i][1] : $tokens[$i]);

// T_ARRAY could either mean the "array(...)" syntax we're looking for
// or a type hinting statement ("function(array $foo) { ... }")
if (is_array($tokens[$i]) && $tokens[$i][0] === T_ARRAY) {
// Look for a subsequent opening bracket ("(") to be sure we're actually
// looking at an "array(...)" statement
$isArraySyntax = false;
$subOffset = $offset;
for ($j = $i + 1; $j < count($tokens); ++$j) {
$subOffset += strlen(is_array($tokens[$j]) ? $tokens[$j][1] : $tokens[$j]);

if (is_string($tokens[$j]) && $tokens[$j] == '(') {
$isArraySyntax = true;
break;
} elseif (!is_array($tokens[$j]) || $tokens[$j][0] !== T_WHITESPACE) {
$isArraySyntax = false;
break;
}
}

if ($isArraySyntax) {
// Replace "array" and the opening bracket (including preceeding whitespace) with "["
$replacements[] = array(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe you could use short syntax array in this short syntax array converter? 😉

'start' => $offset - strlen($tokens[$i][1]),
'end' => $subOffset,
'string' => '[',
);

// Look for matching closing bracket (")")
$subOffset = $offset;
$openBracketsCount = 0;
for ($j = $i + 1; $j < count($tokens); ++$j) {
$subOffset += strlen(is_array($tokens[$j]) ? $tokens[$j][1] : $tokens[$j]);

if (is_string($tokens[$j]) && $tokens[$j] == '(') {
++$openBracketsCount;
} elseif (is_string($tokens[$j]) && $tokens[$j] == ')') {
--$openBracketsCount;

if ($openBracketsCount == 0) {
// Replace ")" with "]"
$replacements[] = array(
'start' => $subOffset - 1,
'end' => $subOffset,
'string' => ']',
);
break;
}
}
}
}
}
}


// - - - - - UPDATE CODE - - - - -

// Apply the replacements to the source code
$offsetChange = 0;
foreach ($replacements as $replacement) {
$code = substr_replace(
$code,
$replacement['string'],
$replacement['start'] + $offsetChange,
$replacement['end'] - $replacement['start']
);
$offsetChange += strlen($replacement['string']) - ($replacement['end'] - $replacement['start']);
}


// - - - - - OUTPUT/WRITE NEW CODE - - - - -

if ($saveFile) {
file_put_contents($filePath, $code);
} else {
print $code;
}
Copy link

@vincentchalamon vincentchalamon Feb 17, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EOF break line missing

4 changes: 4 additions & 0 deletions bin/array-converter
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env php
<?php

include(__DIR__ . '/../array-converter.php');
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

include is a special language construct

include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR  . 'array-converter.php';

31 changes: 31 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "thomasbachem/php-short-array-syntax-converter",
"description": "Command-line script to convert PHP's array() syntax to PHP 5.4's short array syntax [] using PHP's built-in tokenizer.",
"type": "library",
"homepage": "https://github.com/a-vasyliev/php-short-array-syntax-converter",
"keywords": [
"short",
"array",
"converter",
"php"
],
"authors": [
{
"name": "Thomas Bachem",
"email": "[email protected]",
"homepage": "http://thomasbachem.com"
},
{
"name": "Andrii Vasyliev",
"email": "[email protected]",
"homepage": "http://andrey-vasiliev.com"
}
],
"minimum-stability": "dev",
"require": {
"php": ">=5.4"
},
"bin": [
"bin/array-converter"
]
}
144 changes: 0 additions & 144 deletions convert.php

This file was deleted.