Merge pull request #22966 from eileenmcnaughton/retrieve
[civicrm-core.git] / Civi / Api4 / Generic / AbstractCreateAction.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13 namespace Civi\Api4\Generic;
14
15 use Civi\Api4\Event\ValidateValuesEvent;
16 use Civi\API\Exception\UnauthorizedException;
17 use Civi\Api4\Utils\CoreUtil;
18
19 /**
20 * Base class for all `Create` api actions.
21 *
22 * @method $this setValues(array $values) Set all field values from an array of key => value pairs.
23 * @method array getValues() Get field values.
24 *
25 * @package Civi\Api4\Generic
26 */
27 abstract class AbstractCreateAction extends AbstractAction {
28
29 /**
30 * Field values to set for the new $ENTITY.
31 *
32 * @var array
33 */
34 protected $values = [];
35
36 /**
37 * @param string $fieldName
38 * @return mixed|null
39 */
40 public function getValue(string $fieldName) {
41 return $this->values[$fieldName] ?? NULL;
42 }
43
44 /**
45 * Add a field value.
46 * @param string $fieldName
47 * @param mixed $value
48 * @return $this
49 */
50 public function addValue(string $fieldName, $value) {
51 $this->values[$fieldName] = $value;
52 return $this;
53 }
54
55 /**
56 * @throws \API_Exception
57 * @throws \Civi\API\Exception\UnauthorizedException
58 */
59 protected function validateValues() {
60 // FIXME: There should be a protocol to report a full list of errors... Perhaps a subclass of API_Exception?
61 $unmatched = $this->checkRequiredFields($this->getValues());
62 if ($unmatched) {
63 throw new \API_Exception("Mandatory values missing from Api4 {$this->getEntityName()}::{$this->getActionName()}: " . implode(", ", $unmatched), "mandatory_missing", ["fields" => $unmatched]);
64 }
65
66 if ($this->checkPermissions && !CoreUtil::checkAccessRecord($this, $this->getValues(), \CRM_Core_Session::getLoggedInContactID() ?: 0)) {
67 throw new UnauthorizedException("ACL check failed");
68 }
69
70 $e = new ValidateValuesEvent($this, [$this->getValues()], new \CRM_Utils_LazyArray(function () {
71 return [['old' => NULL, 'new' => $this->getValues()]];
72 }));
73 \Civi::dispatcher()->dispatch('civi.api4.validate', $e);
74 if (!empty($e->errors)) {
75 throw $e->toException();
76 }
77 }
78
79 }