Merge pull request #20629 from civicrm/5.39
[civicrm-core.git] / Civi / API / Request.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 namespace Civi\API;
12
13 use Civi\Api4\Utils\CoreUtil;
14
15 /**
16 * Class Request
17 * @package Civi\API
18 */
19 class Request {
20 private static $nextId = 1;
21
22 /**
23 * Create a formatted/normalized request object.
24 *
25 * @param string $entity
26 * API entity name.
27 * @param string $action
28 * API action name.
29 * @param array $params
30 * API parameters.
31 *
32 * @throws \Civi\API\Exception\NotImplementedException
33 * @return \Civi\Api4\Generic\AbstractAction|array
34 */
35 public static function create(string $entity, string $action, array $params) {
36 switch ($params['version'] ?? NULL) {
37 case 3:
38 return [
39 'id' => self::getNextId(),
40 'version' => 3,
41 'params' => $params,
42 'fields' => NULL,
43 'entity' => self::normalizeEntityName($entity),
44 'action' => self::normalizeActionName($action),
45 ];
46
47 case 4:
48 // For custom pseudo-entities
49 if (strpos($entity, 'Custom_') === 0) {
50 $apiRequest = \Civi\Api4\CustomValue::$action(substr($entity, 7));
51 }
52 else {
53 $callable = [CoreUtil::getApiClass($entity), $action];
54 if (!is_callable($callable)) {
55 throw new \Civi\API\Exception\NotImplementedException("API ($entity, $action) does not exist (join the API team and implement it!)");
56 }
57 $apiRequest = call_user_func($callable);
58 }
59 foreach ($params as $name => $param) {
60 $setter = 'set' . ucfirst($name);
61 $apiRequest->$setter($param);
62 }
63 return $apiRequest;
64
65 default:
66 throw new \Civi\API\Exception\NotImplementedException("Unknown api version");
67 }
68 }
69
70 /**
71 * Normalize entity to be CamelCase.
72 *
73 * APIv1-v3 munges entity/action names, and accepts any mixture of case and underscores.
74 *
75 * @param string $entity
76 * @return string
77 */
78 public static function normalizeEntityName($entity) {
79 return \CRM_Core_DAO_AllCoreTables::convertEntityNameToCamel(\CRM_Utils_String::munge($entity), TRUE);
80 }
81
82 /**
83 * Normalize api action name to be lowercase.
84 *
85 * APIv1-v3 munges entity/action names, and accepts any mixture of case and underscores.
86 *
87 * @param $action
88 * @param $version
89 * @return string
90 */
91 public static function normalizeActionName($action) {
92 return strtolower(\CRM_Utils_String::munge($action));
93 }
94
95 public static function getNextId() {
96 return self::$nextId++;
97 }
98
99 }