api4 - Import CRM/, Civi/, templates/, ang/, css/, js/, xml/menu
[civicrm-core.git] / Civi / Api4 / Generic / AbstractSaveAction.php
CommitLineData
19b53e5b
C
1<?php
2
3namespace Civi\Api4\Generic;
4
5/**
6 * Base class for all "Save" api actions.
7 *
8 * @method $this setRecords(array $records) Array of records.
9 * @method $this addRecord($record) Add a record to update.
10 * @method array getRecords()
11 * @method $this setDefaults(array $defaults) Array of defaults.
12 * @method $this addDefault($name, $value) Add a default value.
13 * @method array getDefaults()
14 * @method $this setReload(bool $reload) Specify whether complete objects will be returned after saving.
15 * @method bool getReload()
16 *
17 * @package Civi\Api4\Generic
18 */
19abstract class AbstractSaveAction extends AbstractAction {
20
21 /**
22 * Array of records.
23 *
24 * Should be in the same format as returned by Get.
25 *
26 * @var array
27 * @required
28 */
29 protected $records = [];
30
31 /**
32 * Array of default values.
33 *
34 * These defaults will be applied to all records unless they specify otherwise.
35 *
36 * @var array
37 */
38 protected $defaults = [];
39
40 /**
41 * Reload records after saving.
42 *
43 * By default this api typically returns partial records containing only the fields
44 * that were updated. Set reload to TRUE to do an additional lookup after saving
45 * to return complete records.
46 *
47 * @var bool
48 */
49 protected $reload = FALSE;
50
51 /**
52 * @var string
53 */
54 private $idField;
55
56 /**
57 * BatchAction constructor.
58 * @param string $entityName
59 * @param string $actionName
60 * @param string $idField
61 */
62 public function __construct($entityName, $actionName, $idField = 'id') {
63 // $idField should be a string but some apis (e.g. CustomValue) give us an array
64 $this->idField = array_values((array) $idField)[0];
65 parent::__construct($entityName, $actionName);
66 }
67
68 /**
69 * @throws \API_Exception
70 */
71 protected function validateValues() {
72 $unmatched = [];
73 foreach ($this->records as $record) {
74 if (empty($record[$this->idField])) {
75 $unmatched = array_unique(array_merge($unmatched, $this->checkRequiredFields($record)));
76 }
77 }
78 if ($unmatched) {
79 throw new \API_Exception("Mandatory values missing from Api4 {$this->getEntityName()}::{$this->getActionName()}: " . implode(", ", $unmatched), "mandatory_missing", ["fields" => $unmatched]);
80 }
81 }
82
83 /**
84 * @return string
85 */
86 protected function getIdField() {
87 return $this->idField;
88 }
89
90}