Skip to content

Instantly share code, notes, and snippets.

@hackzilla
Created December 11, 2013 15:29
Show Gist options
  • Save hackzilla/7912411 to your computer and use it in GitHub Desktop.
Save hackzilla/7912411 to your computer and use it in GitHub Desktop.
Split a file with loads on classes into individual files. Uses namespace to figure out where in the file system to put them. Was useful for Microsofts bing api, and splitting files out of composer to autoload.
<?php
# ini_set('memory_limit', '256M');
$directory = '/directory/where your php files are';
chdir($directory);
$files = glob($directory.'/*.php');
foreach($files as $file)
{
$classes = array();
$namespace = false;
$fileContents = file_get_contents($file);
$lines = explode("\r\n", $fileContents);
$currentClass = '';
$inClass = false;
$className = '';
$lastClassLine = 2;
foreach($lines as $i => $line) {
if (strpos($line, 'namespace') !== false) {
$namespace = getNamespace($line);
} else if ($line == '}') {
$currentClass .= $line . PHP_EOL;
$class = array(
'name' => $className,
'definition' => $currentClass,
);
$classes[] = $class;
$currentClass = '';
$inClass = false;
$lastClassLine = $i;
} else if (strpos($line, 'final class ') === 0 || strpos($line, 'class ') === 0) {
$inClass = true;
$currentClass = $line . PHP_EOL;
$className = findClassname($line);
if ($i > ($lastClassLine +2)) {
$range = range($i-1, $lastClassLine + 2);
foreach ($range as $number) {
if ($lines[$number]) {
$currentClass = $lines[$number] . PHP_EOL . $currentClass;
}
}
}
} else if ($inClass) {
$currentClass .= $line . PHP_EOL;
}
}
$folder = str_replace('\\', '/', $namespace);
if (!file_exists($folder)) {
mkdir($folder, 0755, true);
}
foreach($classes as $class) {
makeFile($folder, $namespace, $class['name'], $class['definition']);
}
}
function makeFile($folder, $namespace, $className, $classDefinition) {
$class = '<?php
namespace ' . $namespace . ';
' . $classDefinition;
file_put_contents($folder.'/'.$className . '.php', $class);
}
function findClassname($text)
{
#echo $text . PHP_EOL;
if (preg_match('/class (.*)/', $text, $matches) == 1) {
list($className) = explode(" ", $matches[1]);
return $className;
}
return '';
}
function getNamespace($text)
{
if (preg_match('/namespace (.*);/', $text, $matches) == 1) {
return $matches[1];
}
return '';
}
@hackzilla
Copy link
Author

This file should be easy to adapt for your specific case, but at the moment requires very well formatted classes.

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