move_namespaces_to_top.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. // for each file that has a namespace declaration
  3. $dir = __DIR__;
  4. $filesWithNamespaceDeclaration = explode("\n", `grep -r '^namespace' $dir --include=*.php --exclude=vendor -l`);
  5. // echo implode("\n", $filesWithNamespaceDeclaration);
  6. foreach ($filesWithNamespaceDeclaration as $file) {
  7. moveNamespaceToTop($file);
  8. }
  9. function moveNamespaceToTop($file) {
  10. if (!is_file($file)) {
  11. return;
  12. }
  13. $contents = file_get_contents($file);
  14. $lines = explode("\n", $contents);
  15. $nsDeclarationPosition = findPositionOfNamespaceDeclaration($lines);
  16. if ($nsDeclarationPosition == -1) {
  17. return;
  18. }
  19. $declaration = $lines[$nsDeclarationPosition];
  20. // echo "$declaration\n";
  21. unset($lines[$nsDeclarationPosition]);
  22. array_splice($lines, 1, 0, $declaration);
  23. $newContents = implode("\n", $lines) . "\n";
  24. file_put_contents($file, $newContents);
  25. }
  26. function findPositionOfNamespaceDeclaration($lines) {
  27. $position = -1;
  28. foreach ($lines as $pos => $lineContent) {
  29. if (isNamespaceDeclaration($lineContent)) {
  30. $position = $pos;
  31. }
  32. }
  33. return $position;
  34. }
  35. function isNamespaceDeclaration($lineContent) {
  36. return strpos($lineContent, "namespace ") === 0;
  37. }
  38. // get the contents of that file and split into lines
  39. // find the line with the namespace declaration and remove it
  40. // insert it into the second position
  41. // write all the lines back to the file