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 class determines what fields are allowed for a request
19 * and validates that the fields are provided correctly.
21 class APIv3SchemaAdapter
implements EventSubscriberInterface
{
26 public static function getSubscribedEvents() {
28 'civi.api.prepare' => [
29 ['onApiPrepare', Events
::W_MIDDLE
],
30 ['onApiPrepare_validate', Events
::W_LATE
],
36 * @param \Civi\API\Event\PrepareEvent $event
37 * API preparation event.
39 * @throws \API_Exception
41 public function onApiPrepare(\Civi\API\Event\PrepareEvent
$event) {
42 $apiRequest = $event->getApiRequest();
43 if ($apiRequest['version'] > 3) {
47 $apiRequest['fields'] = _civicrm_api3_api_getfields($apiRequest);
49 _civicrm_api3_swap_out_aliases($apiRequest, $apiRequest['fields']);
50 if (strtolower($apiRequest['action']) != 'getfields') {
51 if (empty($apiRequest['params']['id'])) {
52 $apiRequest['params'] = array_merge($this->getDefaults($apiRequest['fields']), $apiRequest['params']);
54 // Note: If 'id' is set then verify_mandatory will only check 'version'.
55 civicrm_api3_verify_mandatory($apiRequest['params'], NULL, $this->getRequired($apiRequest['fields']));
58 $event->setApiRequest($apiRequest);
62 * @param \Civi\API\Event\Event $event
63 * API preparation event.
67 public function onApiPrepare_validate(\Civi\API\Event\Event
$event) {
68 $apiRequest = $event->getApiRequest();
69 if ($apiRequest['version'] > 3) {
72 // Not sure why this is omitted for generic actions. It would make sense
73 // to omit 'getfields', but that's only one generic action.
75 if (isset($apiRequest['function']) && !$apiRequest['is_generic'] && isset($apiRequest['fields'])) {
76 _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $apiRequest['fields']);
77 $event->setApiRequest($apiRequest);
82 * Return array of defaults for the given API (function is a wrapper on getfields).
86 public function getDefaults($fields) {
89 foreach ($fields as $field => $values) {
90 if (isset($values['api.default'])) {
91 $defaults[$field] = $values['api.default'];
98 * Return array of required fields for the given API (function is a wrapper on getfields).
102 public function getRequired($fields) {
103 $required = ['version'];
105 foreach ($fields as $field => $values) {
106 if (!empty($values['api.required'])) {
107 $required[] = $field;