UniqueJobIdentifierGenerator.php 1.8 KB

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