Guest User

Untitled

a guest
Feb 9th, 2020
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. <?php
  2.  
  3. require_once __DIR__ . '/vendor/autoload.php';
  4.  
  5. class Preloader
  6. {
  7. private array $ignores = [];
  8.  
  9. private static int $count = 0;
  10.  
  11. private array $paths;
  12.  
  13. private array $fileMap;
  14.  
  15. private array $classMap;
  16.  
  17. public function __construct(string ...$paths)
  18. {
  19. $this->paths = $paths;
  20. $this->classMap = require __DIR__ . '/vendor/composer/autoload_classmap.php';
  21. $this->fileMap = array_flip($this->classMap);
  22. }
  23.  
  24. public function paths(string ...$paths): Preloader
  25. {
  26. $this->paths = array_merge(
  27. $this->paths,
  28. $paths
  29. );
  30.  
  31. return $this;
  32. }
  33.  
  34. public function ignore(string ...$names): Preloader
  35. {
  36. $this->ignores = array_merge(
  37. $this->ignores,
  38. $names
  39. );
  40.  
  41. return $this;
  42. }
  43.  
  44. public function load(): void
  45. {
  46. foreach ($this->paths as $path) {
  47. $path = $this->classMap[$path] ?? $path;
  48.  
  49. $this->loadPath(rtrim($path, '/'));
  50. }
  51.  
  52. $count = self::$count;
  53.  
  54. echo "[Preloader] Preloaded {$count} classes" . PHP_EOL;
  55. }
  56.  
  57. private function loadPath(string $path): void
  58. {
  59. if (is_dir($path)) {
  60. $this->loadDir($path);
  61.  
  62. return;
  63. }
  64.  
  65. $this->loadFile($path);
  66. }
  67.  
  68. private function loadDir(string $path): void
  69. {
  70. $handle = opendir($path);
  71.  
  72. while ($file = readdir($handle)) {
  73. if (in_array($file, ['.', '..'])) {
  74. continue;
  75. }
  76.  
  77. $this->loadPath("{$path}/{$file}");
  78. }
  79.  
  80. closedir($handle);
  81. }
  82.  
  83. private function loadFile(string $path): void
  84. {
  85. $class = $this->fileMap[$path] ?? null;
  86.  
  87. if (! $class) {
  88. return;
  89. }
  90.  
  91. if ($this->shouldIgnore($class)) {
  92. echo "[Preloader] Ignored `{$class}`" . PHP_EOL;
  93.  
  94. return;
  95. }
  96.  
  97. require_once($path);
  98.  
  99. self::$count++;
  100.  
  101. echo "[Preloader] Preloaded `{$class}`" . PHP_EOL;
  102. }
  103.  
  104. private function shouldIgnore(?string $name): bool
  105. {
  106. if (! $name) {
  107. return true;
  108. }
  109.  
  110. foreach ($this->ignores as $ignore) {
  111. if (strpos($name, $ignore) === 0) {
  112. return true;
  113. }
  114. }
  115.  
  116. return false;
  117. }
  118. }
  119.  
  120. (new Preloader())
  121. ->paths(
  122. __DIR__ . '/Core'
  123. __DIR__ . '/App'
  124. )
  125. ->ignore()
  126. ->load();
Add Comment
Please, Sign In to add comment