WorkerDirectoryLoader.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 WorkerDirectoryLoader 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 Path to find
  18. * @param string $type Type
  19. *
  20. * @return Array
  21. */
  22. public function load($path, $type = null)
  23. {
  24. $dir = $this->locator->locate($path);
  25. $files = array();
  26. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  27. if (!$file->isFile() || '.php' !== substr($file->getFilename(), -4)) {
  28. continue;
  29. }
  30. $class = $this->findClass($file);
  31. if ($class) {
  32. $files[] = array(
  33. 'path' => $file,
  34. 'class' => $class
  35. );
  36. }
  37. }
  38. return $files;
  39. }
  40. /**
  41. * Returns true if this class supports the given resource.
  42. *
  43. * @param mixed $resource A resource
  44. * @param string $type The resource type
  45. *
  46. * @return Boolean True if this class supports the given resource, false otherwise
  47. */
  48. public function supports($resource, $type = null)
  49. {
  50. return is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION) && (!$type || 'annotation' === $type);
  51. }
  52. /**
  53. * Returns the full class name for the first class in the file.
  54. *
  55. * @param string $file A PHP file path
  56. *
  57. * @return string|false Full class name if found, false otherwise
  58. */
  59. protected function findClass($file)
  60. {
  61. $class = false;
  62. $namespace = false;
  63. $tokens = token_get_all(file_get_contents($file));
  64. for ($i = 0, $count = count($tokens); $i < $count; $i++) {
  65. $token = $tokens[$i];
  66. if (!is_array($token)) {
  67. continue;
  68. }
  69. if (true === $class && T_STRING === $token[0]) {
  70. return $namespace.'\\'.$token[1];
  71. }
  72. if (true === $namespace && T_STRING === $token[0]) {
  73. $namespace = '';
  74. do {
  75. $namespace .= $token[1];
  76. $token = $tokens[++$i];
  77. } while ($i < $count && is_array($token) && in_array($token[0], array(T_NS_SEPARATOR, T_STRING)));
  78. }
  79. if (T_CLASS === $token[0]) {
  80. $class = true;
  81. }
  82. if (T_NAMESPACE === $token[0]) {
  83. $namespace = true;
  84. }
  85. }
  86. return false;
  87. }
  88. }