Merge pull request #23817 from civicrm/5.51
[civicrm-core.git] / Civi / API / Subscriber / WrapperAdapter.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 namespace Civi\API\Subscriber;
13
14 use Civi\API\Events;
15 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
16
17 /**
18 * This is a wrapper for the legacy "API Wrapper" interface which allows
19 * wrappers to run through the new kernel. It translates from dispatcher events
20 * ('civi.api.prepare', 'civi.api.respond') to wrapper calls ('fromApiInput', 'toApiOutput').
21 */
22 class WrapperAdapter implements EventSubscriberInterface {
23
24 /**
25 * @return array
26 */
27 public static function getSubscribedEvents() {
28 return [
29 'civi.api.prepare' => ['onApiPrepare', Events::W_MIDDLE],
30 'civi.api.respond' => ['onApiRespond', Events::W_EARLY * 2],
31 ];
32 }
33
34 /**
35 * @var \API_Wrapper[]
36 */
37 protected $defaults;
38
39 /**
40 * @param array $defaults
41 * array(\API_Wrapper).
42 */
43 public function __construct($defaults = []) {
44 $this->defaults = $defaults;
45 }
46
47 /**
48 * @param \Civi\API\Event\PrepareEvent $event
49 * API preparation event.
50 */
51 public function onApiPrepare(\Civi\API\Event\PrepareEvent $event) {
52 $apiRequest = $event->getApiRequest();
53
54 // For input filtering, process $apiWrappers in forward order
55 foreach ($this->getWrappers($apiRequest) as $apiWrapper) {
56 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
57 }
58
59 $event->setApiRequest($apiRequest);
60 }
61
62 /**
63 * @param \Civi\API\Event\RespondEvent $event
64 * API response event.
65 */
66 public function onApiRespond(\Civi\API\Event\RespondEvent $event) {
67 $apiRequest = $event->getApiRequest();
68 $result = $event->getResponse();
69
70 // For output filtering, process $apiWrappers in reverse order
71 foreach (array_reverse($this->getWrappers($apiRequest)) as $apiWrapper) {
72 $result = $apiWrapper->toApiOutput($apiRequest, $result);
73 }
74
75 $event->setResponse($result);
76 }
77
78 /**
79 * @param array $apiRequest
80 * The full API request.
81 * @return array<\API_Wrapper>
82 */
83 public function getWrappers($apiRequest) {
84 if (!isset($apiRequest['wrappers']) || is_null($apiRequest['wrappers'])) {
85 $apiRequest['wrappers'] = $apiRequest['version'] < 4 ? $this->defaults : [];
86 \CRM_Utils_Hook::apiWrappers($apiRequest['wrappers'], $apiRequest);
87 }
88 return $apiRequest['wrappers'];
89 }
90
91 }