WorksDirectoryLoader.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace Mmoreramerino\GearmanBundle\Module;
  3. use Symfony\Component\Config\FileLocator;
  4. use Symfony\Component\Config\Loader\FileLoader;
  5. use Symfony\Component\Config\Resource\DirectoryResource;
  6. /**
  7. * Worker directory loader class
  8. *
  9. * @author Marc Morera <marc@ulabox.com>
  10. */
  11. class WorksDirectoryLoader extends FileLoader
  12. {
  13. /**
  14. * Load files into path with .php extension.
  15. * This algorythm acts recursively and only return leaves.
  16. *
  17. * @param string $path
  18. * @param string $type
  19. * @return Array
  20. */
  21. public function load($path, $type = null)
  22. {
  23. $dir = $this->locator->locate($path);
  24. $files = array();
  25. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  26. if (!$file->isFile() || '.php' !== substr($file->getFilename(), -4)) {
  27. continue;
  28. }
  29. $class = $this->findClass($file);
  30. if ($class) {
  31. $files[] = array(
  32. 'path' => $file,
  33. 'class' => $class
  34. );
  35. }
  36. }
  37. return $files;
  38. }
  39. /**
  40. * Returns true if this class supports the given resource.
  41. *
  42. * @param mixed $resource A resource
  43. * @param string $type The resource type
  44. *
  45. * @return Boolean True if this class supports the given resource, false otherwise
  46. */
  47. public function supports($resource, $type = null)
  48. {
  49. return is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'annotation' === $type);
  50. }
  51. /**
  52. * Returns the full class name for the first class in the file.
  53. *
  54. * @param string $file A PHP file path
  55. *
  56. * @return string|false Full class name if found, false otherwise
  57. */
  58. protected function findClass($file)
  59. {
  60. $class = false;
  61. $namespace = false;
  62. $tokens = token_get_all(file_get_contents($file));
  63. for ($i = 0, $count = count($tokens); $i < $count; $i++) {
  64. $token = $tokens[$i];
  65. if (!is_array($token)) {
  66. continue;
  67. }
  68. if (true === $class && T_STRING === $token[0]) {
  69. return $namespace.'\\'.$token[1];
  70. }
  71. if (true === $namespace && T_STRING === $token[0]) {
  72. $namespace = '';
  73. do {
  74. $namespace .= $token[1];
  75. $token = $tokens[++$i];
  76. } while ($i < $count && is_array($token) && in_array($token[0], array(T_NS_SEPARATOR, T_STRING)));
  77. }
  78. if (T_CLASS === $token[0]) {
  79. $class = true;
  80. }
  81. if (T_NAMESPACE === $token[0]) {
  82. $namespace = true;
  83. }
  84. }
  85. return false;
  86. }
  87. }