Skip to content

Instantly share code, notes, and snippets.

@igorw
Created July 11, 2012 19:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save igorw/3092750 to your computer and use it in GitHub Desktop.
Save igorw/3092750 to your computer and use it in GitHub Desktop.
Extract classes into their own files.
<?php
if ($argc < 3) {
echo "Usage: php extract.php src dest\n";
exit;
}
$src = $argv[1];
$dest = $argv[2];
$it = new RegexIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($src)), '#\.php$#');
foreach ($it as $file) {
$contents = file_get_contents($file);
$tokens = new ArrayIterator(token_get_all($contents));
$abstract = $final = false;
foreach ($tokens as $token) {
if (is_array($token)) {
list($type, $data) = $token;
if (is_token_type($token, T_ABSTRACT)) {
$abstract = true;
}
if (is_token_type($token, T_FINAL)) {
$final = true;
}
switch ($type) {
case T_CLASS:
case T_INTERFACE:
$nesting = 0;
if ($abstract) {
$data = "abstract $data";
}
if ($final) {
$data = "final $data";
}
do {
$tokens->next();
$name = get_token_data($tokens->current());
$data .= $name;
} while (preg_match('#\s#', $name));
$tokens->next();
while ($tokens->current()) {
$token = $tokens->current();
$data .= get_token_data($token);
if ('{' === get_token_data($token)) {
$nesting++;
}
if ('}' === get_token_data($token)) {
$nesting--;
if (0 === $nesting) {
break;
}
}
$tokens->next();
}
$filename = $dest.'/'.str_replace('_', '/', $name).'.php';
if (!is_dir(dirname($filename))) {
mkdir(dirname($filename), 0755, true);
}
file_put_contents($filename, "<?php\n\n".$data."\n");
$abstract = $final = false;
break;
}
}
}
}
function is_token_type($token, $type)
{
return is_array($token) && $type === $token[0];
}
function get_token_data($token)
{
return is_array($token) ? $token[1] : $token;
}
@cordoval
Copy link

nice little php script, neat. So this is to use with gists or files where all is clamped into a single file.

@igorw
Copy link
Author

igorw commented Jul 12, 2012

Yeah, in my case it was a library with multiple classes per file. So I ran this script to extract the classes (and become PSR-0 compat), then ran the CS fixer for PSR-1 and 2.

@alexandruserban
Copy link

Thank you 👍

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