Skip to content

Instantly share code, notes, and snippets.

@zhwei
Last active March 31, 2022 13:08
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 zhwei/c8652483e72d5586542322f65f973132 to your computer and use it in GitHub Desktop.
Save zhwei/c8652483e72d5586542322f65f973132 to your computer and use it in GitHub Desktop.
<?php namespace Scripts;
use PhpParser\Builder\Use_;
use PhpParser\Node\Stmt\Class_;
require __DIR__ . '/../vendor/autoload.php';
/**
* @param Use_[] $uses
* @param Class_ $class
* @return void
*/
function _get_uses(array $uses, Class_ $class)
{
$used = [];
foreach ($uses as $use) {
$useClassName = array_reverse($use->uses[0]->name->parts)[0];
if (false !== strpos($class->getComments()[0]->getText(), $useClassName)) {
$used[] = $use;
}
}
return $used;
}
function split_model_helpers(string $base)
{
$base = realpath($base) . '/';
$splitedBase = realpath($base) . '_splited/';
file_exists($splitedBase) || mkdir($splitedBase, 0777, true);
$splited = '_ide_helper_models_splited_';
$existedFiles = [];
foreach (scandir($base) as $existed) {
if (starts_with($existed, $splited)) {
$existedFiles[$existed] = true;
}
}
$input = $base . '_ide_helper_models.php';
if (false === file_exists($input)) {
echo "ERROR: $input not exits\n";
return 1;
}
$content = file_get_contents($input);
$parser = (new \PhpParser\ParserFactory())->create(\PhpParser\ParserFactory::PREFER_PHP7);
$printer = new \PhpParser\PrettyPrinter\Standard;
$ast = $parser->parse($content);
foreach ($ast as $namespace) {
$uses = $classes = [];
foreach ($namespace->stmts as $idx => $stmt) {
if ($stmt instanceof \PhpParser\Node\Stmt\Class_) {
$classes[] = $stmt;
} elseif ($stmt instanceof \PhpParser\Node\Stmt\Use_) {
$uses[] = $stmt;
}
}
foreach ($classes as $class) {
$namespace->stmts = array_merge(_get_uses($uses, $class), [$class]);
$content = "<?php\n\n" . $printer->prettyPrint([$namespace]);
$filename = $splited . join('_', $namespace->name->parts ?? []) . '_' . $class->name . '.php';
$filepath = $splitedBase . $filename;
if (file_exists($filepath) && $content === file_get_contents($filepath)) {
unset($existedFiles[$filename]);
// echo "> skip: {$filename}\n";
continue;
} else {
file_put_contents($filepath, $content);
unset($existedFiles[$filename]);
echo "> generated: {$filename}\n";
}
}
}
foreach ($existedFiles as $uslessFile) {
if (file_exists($base . $uslessFile)) {
//unlink($base . $uslessFile);
echo "> unlink: {$uslessFile}\n";
}
}
unlink($input);
echo "> unlink: {$input}\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment