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\Subscriber
;
15 use Symfony\Component\EventDispatcher\EventSubscriberInterface
;
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').
22 class WrapperAdapter
implements EventSubscriberInterface
{
27 public static function getSubscribedEvents() {
29 Events
::PREPARE
=> ['onApiPrepare', Events
::W_MIDDLE
],
30 Events
::RESPOND
=> ['onApiRespond', Events
::W_EARLY
* 2],
40 * @param array $defaults
41 * array(\API_Wrapper).
43 public function __construct($defaults = []) {
44 $this->defaults
= $defaults;
48 * @param \Civi\API\Event\PrepareEvent $event
49 * API preparation event.
51 public function onApiPrepare(\Civi\API\Event\PrepareEvent
$event) {
52 $apiRequest = $event->getApiRequest();
54 // For input filtering, process $apiWrappers in forward order
55 foreach ($this->getWrappers($apiRequest) as $apiWrapper) {
56 $apiRequest = $apiWrapper->fromApiInput($apiRequest);
59 $event->setApiRequest($apiRequest);
63 * @param \Civi\API\Event\RespondEvent $event
66 public function onApiRespond(\Civi\API\Event\RespondEvent
$event) {
67 $apiRequest = $event->getApiRequest();
68 $result = $event->getResponse();
70 // For output filtering, process $apiWrappers in reverse order
71 foreach (array_reverse($this->getWrappers($apiRequest)) as $apiWrapper) {
72 $result = $apiWrapper->toApiOutput($apiRequest, $result);
75 $event->setResponse($result);
79 * @param array $apiRequest
80 * The full API request.
81 * @return array<\API_Wrapper>
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);
88 return $apiRequest['wrappers'];