AbstractGearmanService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. /**
  3. * Gearman Bundle for Symfony2
  4. *
  5. * @author Marc Morera <yuhu@mmoreram.com>
  6. * @since 2013
  7. */
  8. namespace Mmoreram\GearmanBundle\Service\Abstracts;
  9. use Mmoreram\GearmanBundle\Service\GearmanCacheWrapper;
  10. use Mmoreram\GearmanBundle\Exceptions\JobDoesNotExistException;
  11. use Mmoreram\GearmanBundle\Exceptions\WorkerDoesNotExistException;
  12. /**
  13. * Gearman execute methods. All Worker methods
  14. *
  15. * @author Marc Morera <yuhu@mmoreram.com>
  16. */
  17. abstract class AbstractGearmanService
  18. {
  19. /**
  20. * All workers
  21. *
  22. * @var type
  23. */
  24. protected $workers;
  25. /**
  26. * The prefix for all job names
  27. *
  28. * @var string $jobPrefix
  29. */
  30. protected $jobPrefix = null;
  31. /**
  32. * Construct method
  33. *
  34. * @param GearmanCacheWrapper $gearmanCacheWrapper GearmanCacheWrapper
  35. * @param array $defaultSettings The default settings for the bundle.
  36. *
  37. */
  38. public function __construct(GearmanCacheWrapper $gearmanCacheWrapper,array $defaultSettings)
  39. {
  40. $this->workers = $gearmanCacheWrapper->getWorkers();
  41. if(isset($defaultSettings['job_prefix']))
  42. $this->jobPrefix = $defaultSettings['job_prefix'];
  43. }
  44. /**
  45. * Return worker containing a job with $jobName as name
  46. * If is not found, throws JobDoesNotExistException Exception
  47. *
  48. * @param string $jobName Name of job
  49. *
  50. * @return Array
  51. */
  52. public function getJob($jobName)
  53. {
  54. $jobName = $this->jobPrefix . $jobName;
  55. foreach ($this->workers as $worker) {
  56. if (is_array($worker['jobs'])) {
  57. foreach ($worker['jobs'] as $job) {
  58. if ($jobName === $job['realCallableName']) {
  59. $worker['job'] = $job;
  60. return $worker;
  61. }
  62. }
  63. }
  64. }
  65. throw new JobDoesNotExistException();
  66. }
  67. /**
  68. * Return worker with $workerName as name and all its jobs
  69. * If is not found, throws WorkerDoesNotExistException Exception
  70. *
  71. * @param string $workerName Name of worker
  72. *
  73. * @return Array
  74. */
  75. public function getWorker($workerName)
  76. {
  77. foreach ($this->workers as $worker) {
  78. if ($workerName === $worker['callableName']) {
  79. return $worker;
  80. }
  81. }
  82. throw new WorkerDoesNotExistException();
  83. }
  84. /**
  85. * Return array of workers
  86. *
  87. * @return array all available workers
  88. */
  89. public function getWorkers()
  90. {
  91. return $this->workers;
  92. }
  93. }