UniqueJobIdentifierGenerator.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * Gearman Bundle for Symfony2
  4. *
  5. * @author Marc Morera <yuhu@mmoreram.com>
  6. * @since 2013
  7. */
  8. namespace Mmoreram\GearmanBundle\Generator;
  9. use Mmoreram\GearmanBundle\Exceptions\WorkerNameTooLongException;
  10. /**
  11. * Job Unique Key generator
  12. *
  13. * @author Marc Morera <yuhu@mmoreram.com>
  14. * @see https://github.com/mmoreram/GearmanBundle/issues/66
  15. */
  16. class UniqueJobIdentifierGenerator
  17. {
  18. /**
  19. * @var string
  20. *
  21. * Generate unique key
  22. */
  23. protected $generateUniqueKey;
  24. /**
  25. * Construct method
  26. *
  27. * @param string $generateUniqueKey Generate unique key
  28. */
  29. public function __construct($generateUniqueKey)
  30. {
  31. $this->generateUniqueKey = $generateUniqueKey;
  32. }
  33. /**
  34. * Generate unique key if generateUniqueKey is enabled
  35. *
  36. * Even some parameters are not used, are passed to allow user overwrite
  37. * method
  38. *
  39. * Also, if name and unique value exceeds 114 bytes, an exception is thrown
  40. *
  41. * @param string $name A GermanBundle registered function to be executed
  42. * @param string $params Parameters to send to task as string
  43. * @param string $unique unique ID used to identify a particular task
  44. * @param string $method Method to perform
  45. *
  46. * @return string Generated Unique Key
  47. *
  48. * @throws WorkerNameTooLongException If name is too large
  49. */
  50. public function generateUniqueKey($name, $params, $unique, $method)
  51. {
  52. $unique = !$unique && $this->generateUniqueKey
  53. ? md5($name . $params)
  54. : $unique;
  55. if (strlen($name . $unique) > 114) {
  56. throw new WorkerNameTooLongException;
  57. }
  58. return $unique;
  59. }
  60. }