Merge pull request #17329 from civicrm/5.26
[civicrm-core.git] / Civi / Api4 / Action / Setting / AbstractSettingAction.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\Action\Setting;
14
15 use Civi\Api4\Domain;
16 use Civi\Api4\Generic\Result;
17
18 /**
19 * Base class for setting actions.
20 *
21 * @method int getDomainId
22 * @method $this setDomainId(int $domainId)
23 */
24 abstract class AbstractSettingAction extends \Civi\Api4\Generic\AbstractAction {
25
26 /**
27 * Domain id of setting. Leave NULL for default domain.
28 *
29 * @var int|string|array
30 */
31 protected $domainId;
32
33 /**
34 * Contact - if this is a contact-related setting.
35 *
36 * @var int
37 */
38 protected $contactId;
39
40 public function _run(Result $result) {
41 $this->findDomains();
42 $meta = [];
43 foreach ($this->domainId as $domain) {
44 $meta[$domain] = $this->validateSettings($domain);
45 }
46 foreach ($this->domainId as $domain) {
47 $settingsBag = $this->contactId ? \Civi::contactSettings($this->contactId, $domain) : \Civi::settings($domain);
48 $this->processSettings($result, $settingsBag, $meta[$domain], $domain);
49 }
50 }
51
52 /**
53 * Checks that really ought to be taken care of by `Civi::settings`.
54 *
55 * @param int $domain
56 * @return array
57 * @throws \API_Exception
58 */
59 protected function validateSettings($domain) {
60 $meta = \Civi\Core\SettingsMetadata::getMetadata([], $domain);
61 $names = isset($this->values) ? array_keys($this->values) : $this->select;
62 $invalid = array_diff($names, array_keys($meta));
63 if ($invalid) {
64 throw new \API_Exception("Unknown settings for domain $domain: " . implode(', ', $invalid));
65 }
66 if (isset($this->values)) {
67 foreach ($this->values as $name => &$value) {
68 \CRM_Core_BAO_Setting::validateSetting($value, $meta[$name]);
69 }
70 }
71 return $meta;
72 }
73
74 protected function findDomains() {
75 if ($this->domainId == 'all') {
76 $this->domainId = Domain::get()->setCheckPermissions(FALSE)->addSelect('id')->execute()->column('id');
77 }
78 elseif ($this->domainId) {
79 $this->domainId = (array) $this->domainId;
80 $domains = Domain::get()->setCheckPermissions(FALSE)->addSelect('id')->execute()->column('id');
81 $invalid = array_diff($this->domainId, $domains);
82 if ($invalid) {
83 throw new \API_Exception('Invalid domain id: ' . implode(', ', $invalid));
84 }
85 }
86 else {
87 $this->domainId = [\CRM_Core_Config::domainID()];
88 }
89 }
90
91 }