3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * A task is an item that can be enqueued and later executed
15 class CRM_Queue_Task
{
18 * Task was performed successfully.
20 const TASK_SUCCESS
= 1;
23 * Task failed and should not be retried.
48 * If specified, it may include these keys:
49 * - contactId: int|null
50 * - domainId: int|null
55 * @param mixed $callback
56 * Serializable, a callable PHP item; must accept at least one argument
57 * (CRM_Queue_TaskContext).
58 * @param array $arguments
59 * Serializable, extra arguments to pass to the callback (in order).
60 * @param string|null $title
61 * A printable string which describes this task.
63 public function __construct($callback, array $arguments = [], ?
string $title = NULL) {
64 $this->callback
= $callback;
65 $this->arguments
= $arguments;
66 $this->title
= $title;
72 * @param \CRM_Queue_TaskContext $taskCtx
75 * TRUE if task completes successfully.
76 * FALSE or exception if task fails.
78 public function run($taskCtx) {
79 $args = $this->arguments
;
80 array_unshift($args, $taskCtx);
82 if ($this->runAs
!== NULL) {
83 $equals = function($a, $b) {
84 return $a === $b ||
(is_numeric($a) && is_numeric($b) && $a == $b);
86 if (array_key_exists('contactId', $this->runAs
) && !$equals(CRM_Core_Session
::getLoggedInContactID(), $this->runAs
['contactId'])) {
87 throw new Exception(sprintf('Cannot execute queue task. Unexpected contact "%s" for job "%s"', CRM_Core_Session
::getLoggedInContactID(), $this->getSummary()));
89 if (array_key_exists('domainId', $this->runAs
) && !$equals(CRM_Core_BAO_Domain
::getDomain()->id
, $this->runAs
['domainId'])) {
90 throw new Exception(sprintf('Cannot execute queue task. Unexpected domain "%s" for job "%s"', CRM_Core_BAO_Domain
::getDomain()->id
, $this->getSummary()));
94 if (is_callable($this->callback
)) {
95 $result = call_user_func_array($this->callback
, $args);
99 throw new Exception('Failed to call callback: ' . $this->getSummary());
103 private function getSummary(): string {
104 return json_encode(['title' => $this->title
, 'runAs' => $this->runAs
, 'callback' => $this->callback
], JSON_UNESCAPED_SLASHES
);