Merge pull request #23283 from eileenmcnaughton/import_saved_map
[civicrm-core.git] / Civi / Api4 / Action / Queue / ClaimItems.php
CommitLineData
8369e17b
TO
1<?php
2
3/*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13namespace Civi\Api4\Action\Queue;
14
15use Civi\Api4\Generic\Traits\SelectParamTrait;
16
17/**
18 * Claim an item from the queue. Returns zero or one items.
19 *
20 * @method ?string setQueue
21 * @method $this setQueue(?string $queue)
22 */
23class ClaimItems extends \Civi\Api4\Generic\AbstractAction {
24
25 use SelectParamTrait;
26
27 /**
28 * Name of the target queue.
29 *
30 * @var string|null
31 */
32 protected $queue;
33
34 public function _run(\Civi\Api4\Generic\Result $result) {
35 $this->select = empty($this->select) ? ['id', 'data', 'queue'] : $this->select;
36 $queue = $this->queue();
37 if (!$queue->isActive()) {
38 return;
39 }
40
41 $isBatch = $queue instanceof \CRM_Queue_Queue_BatchQueueInterface;
42 $limit = $queue->getSpec('batch_limit') ?: 1;
43 if ($limit > 1 && !$isBatch) {
44 throw new \API_Exception(sprintf('Queue "%s" (%s) does not support batching.', $queue->getName(), get_class($queue)));
45 // Note 1: Simply looping over `claimItem()` is unlikley to help the consumer b/c
46 // drivers like Sql+Memory are linear+blocking.
47 // Note 2: The default is batch_limit=1. So someone has specifically chosen an invalid configuration...
48 }
49 $items = $isBatch ? $queue->claimItems($limit) : [$queue->claimItem()];
50
51 foreach ($items as $item) {
52 if ($item) {
53 $result[] = $this->convertItemToStub($item);
54 }
55 }
56 }
57
58 /**
59 * @param \CRM_Queue_DAO_QueueItem|\stdClass $item
60 * @return array
61 */
62 protected function convertItemToStub(object $item): array {
63 $array = [];
64 foreach ($this->select as $field) {
65 switch ($field) {
66 case 'id':
67 $array['id'] = $item->id;
68 break;
69
70 case 'data':
71 $array['data'] = (array) $item->data;
72 break;
73
74 case 'queue':
75 $array['queue'] = $this->queue;
76 break;
77
78 }
79 }
80 return $array;
81 }
82
83 protected function queue(): \CRM_Queue_Queue {
84 if (empty($this->queue)) {
85 throw new \API_Exception('Missing required parameter: $queue');
86 }
87 return \Civi::queue($this->queue);
88 }
89
90}