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 +--------------------------------------------------------------------+
12 namespace Civi\API\Provider
;
15 use Symfony\Component\EventDispatcher\EventSubscriberInterface
;
18 * An adhoc provider is useful for creating mock API implementations.
20 class AdhocProvider
implements EventSubscriberInterface
, ProviderInterface
{
25 public static function getSubscribedEvents() {
26 // Using a high priority allows adhoc implementations
27 // to override standard implementations -- which is
28 // handy for testing/mocking.
31 ['onApiResolve', Events
::W_EARLY
],
33 Events
::AUTHORIZE
=> [
34 ['onApiAuthorize', Events
::W_EARLY
],
40 * @var array (string $name => array('perm' => string, 'callback' => callable))
42 protected $actions = [];
57 * @param string $entity
60 public function __construct($version, $entity) {
61 $this->entity
= $entity;
62 $this->version
= $version;
71 * Permissions required for invoking the action.
72 * @param mixed $callback
73 * The function which executes the API.
74 * @return AdhocProvider
76 public function addAction($name, $perm, $callback) {
77 $this->actions
[strtolower($name)] = [
79 'callback' => $callback,
85 * @param \Civi\API\Event\ResolveEvent $event
86 * API resolution event.
88 public function onApiResolve(\Civi\API\Event\ResolveEvent
$event) {
89 $apiRequest = $event->getApiRequest();
90 if ($this->matchesRequest($apiRequest)) {
91 $event->setApiRequest($apiRequest);
92 $event->setApiProvider($this);
93 $event->stopPropagation();
98 * @param \Civi\API\Event\AuthorizeEvent $event
99 * API authorization event.
101 public function onApiAuthorize(\Civi\API\Event\AuthorizeEvent
$event) {
102 $apiRequest = $event->getApiRequest();
103 if ($this->matchesRequest($apiRequest) && \CRM_Core_Permission
::check($this->actions
[strtolower($apiRequest['action'])]['perm'])) {
105 $event->stopPropagation();
111 * @param array $apiRequest
112 * @return array|mixed
114 public function invoke($apiRequest) {
115 return call_user_func($this->actions
[strtolower($apiRequest['action'])]['callback'], $apiRequest);
120 * @param int $version
123 public function getEntityNames($version) {
124 return [$this->entity
];
129 * @param int $version
130 * @param string $entity
133 public function getActionNames($version, $entity) {
134 if ($version == $this->version
&& $entity == $this->entity
) {
135 return array_keys($this->actions
);
143 * @param array $apiRequest
144 * The full description of the API request.
148 public function matchesRequest($apiRequest) {
149 return $apiRequest['entity'] == $this->entity
&& $apiRequest['version'] == $this->version
&& isset($this->actions
[strtolower($apiRequest['action'])]);