UniqueLock.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace Illuminate\Bus;
  3. use Illuminate\Contracts\Cache\Repository as Cache;
  4. class UniqueLock
  5. {
  6. /**
  7. * The cache repository implementation.
  8. *
  9. * @var \Illuminate\Contracts\Cache\Repository
  10. */
  11. protected $cache;
  12. /**
  13. * Create a new unique lock manager instance.
  14. *
  15. * @param \Illuminate\Contracts\Cache\Repository $cache
  16. */
  17. public function __construct(Cache $cache)
  18. {
  19. $this->cache = $cache;
  20. }
  21. /**
  22. * Attempt to acquire a lock for the given job.
  23. *
  24. * @param mixed $job
  25. * @return bool
  26. */
  27. public function acquire($job)
  28. {
  29. $uniqueFor = method_exists($job, 'uniqueFor')
  30. ? $job->uniqueFor()
  31. : ($job->uniqueFor ?? 0);
  32. $cache = method_exists($job, 'uniqueVia')
  33. ? $job->uniqueVia()
  34. : $this->cache;
  35. return (bool) $cache->lock($this->getKey($job), $uniqueFor)->get();
  36. }
  37. /**
  38. * Release the lock for the given job.
  39. *
  40. * @param mixed $job
  41. * @return void
  42. */
  43. public function release($job)
  44. {
  45. $cache = method_exists($job, 'uniqueVia')
  46. ? $job->uniqueVia()
  47. : $this->cache;
  48. $cache->lock($this->getKey($job))->forceRelease();
  49. }
  50. /**
  51. * Generate the lock key for the given job.
  52. *
  53. * @param mixed $job
  54. * @return string
  55. */
  56. public static function getKey($job)
  57. {
  58. $uniqueId = method_exists($job, 'uniqueId')
  59. ? $job->uniqueId()
  60. : ($job->uniqueId ?? '');
  61. return 'laravel_unique_job:'.get_class($job).':'.$uniqueId;
  62. }
  63. }