MmoreramerinoGearmanBundle.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Mmoreramerino\GearmanBundle;
  3. use Symfony\Component\Config\FileLocator;
  4. use Doctrine\Common\Annotations\AnnotationReader;
  5. use Doctrine\Common\Annotations\AnnotationRegistry;
  6. use Mmoreramerino\GearmanBundle\Module\WorkerCollection;
  7. use Mmoreramerino\GearmanBundle\Module\GearmanBaseBundle;
  8. use Mmoreramerino\GearmanBundle\Module\WorkerDirectoryLoader;
  9. use Mmoreramerino\GearmanBundle\Module\WorkerClass as Worker;
  10. use Mmoreramerino\GearmanBundle\Service\GearmanCache as Cache;
  11. use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
  12. use Mmoreramerino\GearmanBundle\Exceptions\GearmanNotInstalledException;
  13. /**
  14. * Gearman Bundle
  15. *
  16. * @author Marc Morera <marc@ulabox.com>
  17. */
  18. class MmoreramerinoGearmanBundle extends GearmanBaseBundle
  19. {
  20. /**
  21. * Boots the Bundle.
  22. * This method load all data and saves all annotations into cache.
  23. * Also, it load all settings from Yaml file format
  24. *
  25. * @api
  26. */
  27. public function boot()
  28. {
  29. if (!in_array('gearman', get_loaded_extensions())) {
  30. throw new GearmanNotInstalledException;
  31. }
  32. $gearmanCache = $this->container->get('gearman.cache');
  33. $existsCache = $gearmanCache->existsCacheFile();
  34. $environmentsCacheClear = array(
  35. 'back_dev', 'back_test', 'dev', 'test',
  36. );
  37. if (in_array($this->container->get('kernel')->getEnvironment(), $environmentsCacheClear) || !$existsCache) {
  38. if ($existsCache) {
  39. $gearmanCache->emptyCache();
  40. }
  41. $reader = new AnnotationReader();
  42. AnnotationRegistry::registerFile(__DIR__ . "/Driver/Gearman/GearmanAnnotations.php");
  43. $reader->setDefaultAnnotationNamespace('Mmoreramerino\GearmanBundle\Driver\\');
  44. $workerCollection = new WorkerCollection;
  45. $bundles = $this->container->get('kernel')->getBundles();
  46. foreach ($bundles as $bundle) {
  47. if (!\in_array($bundle->getNamespace(), $this->getParseableBundles())) {
  48. continue;
  49. }
  50. $filesLoader = new WorkerDirectoryLoader(new FileLocator('.'));
  51. $files = $filesLoader->load($bundle->getPath());
  52. foreach ($files as $file) {
  53. $reflClass = new \ReflectionClass($file['class']);
  54. $classAnnotations = $reader->getClassAnnotations($reflClass);
  55. foreach ($classAnnotations as $annot) {
  56. if ($annot instanceof \Mmoreramerino\GearmanBundle\Driver\Gearman\Work) {
  57. $workerCollection->add(new Worker($annot, $reflClass, $reader, $this->getSettings()));
  58. }
  59. }
  60. }
  61. }
  62. $gearmanCache ->set($workerCollection->__toCache())
  63. ->save();
  64. }
  65. }
  66. }