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