Memory.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace Drupal\Core\Queue;
  3. /**
  4. * Static queue implementation.
  5. *
  6. * This allows "undelayed" variants of processes relying on the Queue
  7. * interface. The queue data resides in memory. It should only be used for
  8. * items that will be queued and dequeued within a given page request.
  9. *
  10. * @ingroup queue
  11. */
  12. class Memory implements QueueInterface {
  13. /**
  14. * The queue data.
  15. *
  16. * @var array
  17. */
  18. protected $queue;
  19. /**
  20. * Counter for item ids.
  21. *
  22. * @var int
  23. */
  24. protected $idSequence;
  25. /**
  26. * Constructs a Memory object.
  27. *
  28. * @param string $name
  29. * An arbitrary string. The name of the queue to work with.
  30. */
  31. public function __construct($name) {
  32. $this->queue = [];
  33. $this->idSequence = 0;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function createItem($data) {
  39. $item = new \stdClass();
  40. $item->item_id = $this->idSequence++;
  41. $item->data = $data;
  42. $item->created = time();
  43. $item->expire = 0;
  44. $this->queue[$item->item_id] = $item;
  45. return $item->item_id;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function numberOfItems() {
  51. return count($this->queue);
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function claimItem($lease_time = 30) {
  57. foreach ($this->queue as $key => $item) {
  58. if ($item->expire == 0) {
  59. $item->expire = time() + $lease_time;
  60. $this->queue[$key] = $item;
  61. return $item;
  62. }
  63. }
  64. return FALSE;
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function deleteItem($item) {
  70. unset($this->queue[$item->item_id]);
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function releaseItem($item) {
  76. if (isset($this->queue[$item->item_id]) && $this->queue[$item->item_id]->expire != 0) {
  77. $this->queue[$item->item_id]->expire = 0;
  78. return TRUE;
  79. }
  80. return FALSE;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function createQueue() {
  86. // Nothing needed here.
  87. }
  88. /**
  89. * {@inheritdoc}
  90. */
  91. public function deleteQueue() {
  92. $this->queue = [];
  93. $this->idSequence = 0;
  94. }
  95. }