WorkerClass.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Mmoreramerino\GearmanBundle\Module;
  3. use Doctrine\Common\Annotations\AnnotationReader;
  4. use Mmoreramerino\GearmanBundle\Driver\Gearman\Work;
  5. use Mmoreramerino\GearmanBundle\Module\JobCollection;
  6. use Mmoreramerino\GearmanBundle\Module\JobClass as Job;
  7. /**
  8. * Worker class
  9. *
  10. * @author Marc Morera <marc@ulabox.com>
  11. */
  12. class WorkerClass
  13. {
  14. /**
  15. * All jobs inside Worker
  16. *
  17. * @var JobCollection
  18. */
  19. private $jobCollection;
  20. /**
  21. * Callable name for this job
  22. * If is setted on annotations, this value will be used
  23. * otherwise, natural method name will be used.
  24. *
  25. * @var string
  26. */
  27. private $callableName;
  28. /**
  29. * Namespace of Work class
  30. *
  31. * @var string
  32. */
  33. private $namespace;
  34. /**
  35. * Retrieves all jobs available from worker
  36. *
  37. * @param Work $classAnnotation
  38. * @param \ReflectionClass $reflectionClass
  39. * @param AnnotationReader $reader
  40. * @param array $settings
  41. */
  42. public function __construct( Work $classAnnotation, \ReflectionClass $reflectionClass, AnnotationReader $reader, array $settings)
  43. {
  44. $this->namespace = $reflectionClass->getNamespaceName();
  45. $this->callableName = (null !== $classAnnotation->name) ?
  46. $classAnnotation->name :
  47. $this->namespace;
  48. $this->description = (null !== $classAnnotation->description) ?
  49. $classAnnotation->description :
  50. 'No description is defined';
  51. $this->fileName = $reflectionClass->getFileName();
  52. $this->className = $reflectionClass->getName();
  53. $this->jobCollection = new JobCollection;
  54. foreach ($reflectionClass->getMethods() as $method) {
  55. $reflMethod = new \ReflectionMethod($method->class, $method->name);
  56. $methodAnnotations = $reader->getMethodAnnotations($reflMethod);
  57. foreach ($methodAnnotations as $annot) {
  58. if ($annot instanceof \Mmoreramerino\GearmanBundle\Driver\Gearman\Job) {
  59. $this->jobCollection->add(new Job($annot, $reflMethod, $classAnnotation, $this->callableName, $settings));
  60. }
  61. }
  62. }
  63. }
  64. /**
  65. * Retrieve all Worker data in cache format
  66. *
  67. * @return array
  68. */
  69. public function __toCache()
  70. {
  71. $dump = array(
  72. 'namespace' => $this->namespace,
  73. 'className' => $this->className,
  74. 'fileName' => $this->fileName,
  75. 'callableName' => $this->callableName,
  76. 'description' => $this->description,
  77. 'jobs' => array(),
  78. );
  79. $dump['jobs'] = $this->jobCollection->__toCache();
  80. return $dump;
  81. }
  82. }