AbstractGearmanService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 array
  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. public function __construct(GearmanCacheWrapper $gearmanCacheWrapper, array $defaultSettings)
  38. {
  39. $this->workers = $gearmanCacheWrapper->getWorkers();
  40. if (isset($defaultSettings['job_prefix'])) {
  41. $this->jobPrefix = $defaultSettings['job_prefix'];
  42. }
  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. * @throws JobDoesNotExistException
  53. */
  54. public function getJob($jobName)
  55. {
  56. $jobName = $this->jobPrefix . $jobName;
  57. foreach ($this->workers as $worker) {
  58. if (is_array($worker['jobs'])) {
  59. foreach ($worker['jobs'] as $job) {
  60. if ($jobName === $job['realCallableName']) {
  61. $worker['job'] = $job;
  62. return $worker;
  63. }
  64. }
  65. }
  66. }
  67. throw new JobDoesNotExistException();
  68. }
  69. /**
  70. * Return worker with $workerName as name and all its jobs
  71. * If is not found, throws WorkerDoesNotExistException Exception
  72. *
  73. * @param string $workerName Name of worker
  74. *
  75. * @return Array
  76. *
  77. * @throws WorkerDoesNotExistException
  78. */
  79. public function getWorker($workerName)
  80. {
  81. foreach ($this->workers as $worker) {
  82. if ($workerName === $worker['callableName']) {
  83. return $worker;
  84. }
  85. }
  86. throw new WorkerDoesNotExistException();
  87. }
  88. /**
  89. * Return array of workers
  90. *
  91. * @return array all available workers
  92. */
  93. public function getWorkers()
  94. {
  95. return $this->workers;
  96. }
  97. }