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 +--------------------------------------------------------------------+
13 * Class CRM_Core_Resources_CollectionTrait
15 * This is a building-block for creating classes which maintain a list of resources.
17 * The class is generally organized in two sections: First, we have core
18 * bit that manages a list of '$snippets'. Second, we have a set of helper
19 * functions which add some syntactic sugar for the snippets.
21 trait CRM_Core_Resources_CollectionAdderTrait
{
24 * Add an item to the collection.
26 * @param array $snippet
28 * The full/computed snippet (with defaults applied).
29 * @see CRM_Core_Resources_CollectionInterface::add()
31 abstract public function add($snippet);
34 * Locate the 'settings' snippet.
36 * @param array $options
39 abstract protected function &findCreateSettingSnippet($options = []): array;
42 * Export permission data to the client to enable smarter GUIs.
44 * Note: Application security stems from the server's enforcement
45 * of the security logic (e.g. in the API permissions). There's no way
46 * the client can use this info to make the app more secure; however,
47 * it can produce a better-tuned (non-broken) UI.
49 * @param string|iterable $permNames
50 * List of permission names to check/export.
53 public function addPermissions($permNames) {
54 // TODO: Maybe this should be its own resource type to allow smarter management?
55 $permNames = is_scalar($permNames) ?
[$permNames] : $permNames;
58 foreach ($permNames as $permName) {
59 $perms[$permName] = CRM_Core_Permission
::check($permName);
61 return $this->addSetting([
62 'permissions' => $perms,
67 * Add a JavaScript file to the current page using <SCRIPT SRC>.
70 * JavaScript source code.
71 * @param array $options
72 * Open-ended list of options (per add())
73 * Ex: ['weight' => 123]
76 public function addScript(string $code, ...$options) {
77 $this->add(self
::mergeStandardOptions($options, [
84 * Add a JavaScript file to the current page using <SCRIPT SRC>.
86 * Options may be use key-value format (preferred) or positional format (legacy).
88 * - addScriptFile('myext', 'my.js', ['weight' => 123, 'region' => 'page-footer'])
89 * - addScriptFile('myext', 'my.js', 123, 'page-footer')
92 * extension name; use 'civicrm' for core.
94 * file path -- relative to the extension base dir.
95 * @param array $options
96 * Open-ended list of options (per add()).
97 * Ex: ['weight' => 123]
98 * Accepts some additional options:
99 * - bool|string $translate: Whether to load translated strings for this file. Use one of:
100 * - FALSE: Do not load translated strings.
101 * - TRUE: Load translated strings. Use the $ext's default domain.
102 * - string: Load translated strings. Use a specific domain.
106 * @throws \CRM_Core_Exception
108 public function addScriptFile(string $ext, string $file, ...$options) {
109 $this->add(self
::mergeStandardOptions($options, [
110 'scriptFile' => [$ext, $file],
116 * Add a JavaScript file to the current page using <SCRIPT SRC>.
118 * Options may be use key-value format (preferred) or positional format (legacy).
120 * - addScriptUrl('http://example.com/foo.js', ['weight' => 123, 'region' => 'page-footer'])
121 * - addScriptUrl('http://example.com/foo.js', 123, 'page-footer')
124 * @param array $options
125 * Open-ended list of options (per add())
128 public function addScriptUrl(string $url, ...$options) {
129 $this->add(self
::mergeStandardOptions($options, [
136 * Add translated string to the js CRM object.
137 * It can then be retrived from the client-side ts() function
138 * Variable substitutions can happen from client-side
140 * Note: this function rarely needs to be called directly and is mostly for internal use.
141 * See CRM_Core_Resources::addScriptFile which automatically adds translated strings from js files
145 * CRM_Core_Resources::singleton()->addString('Hello');
146 * // The string is now available to javascript code i.e.
149 * Example with client-side substitutions:
151 * CRM_Core_Resources::singleton()->addString('Your %1 has been %2');
152 * // ts() in javascript works the same as in php, for example:
153 * ts('Your %1 has been %2', {1: objectName, 2: actionTaken});
155 * NOTE: This function does not work with server-side substitutions
156 * (as this might result in collisions and unwanted variable injections)
157 * Instead, use code like:
158 * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('myString' => ts('Your %1 has been %2', array(subs)))));
159 * And from javascript access it at CRM.myNamespace.myString
161 * @param string|array $text
162 * @param string|null $domain
165 public function addString($text, $domain = 'civicrm') {
166 // TODO: Maybe this should be its own resource type to allow smarter management?
168 foreach ((array) $text as $str) {
169 $translated = ts($str, [
170 'domain' => ($domain == 'civicrm') ?
NULL : [$domain, NULL],
174 // We only need to push this string to client if the translation
175 // is actually different from the original
176 if ($translated != $str) {
177 $bucket = $domain == 'civicrm' ?
'strings' : 'strings::' . $domain;
179 $bucket => [$str => $translated],
187 * Add a CSS content to the current page using <STYLE>.
189 * @param string $code
191 * @param array $options
192 * Open-ended list of options (per add())
193 * Ex: ['weight' => 123]
196 public function addStyle(string $code, ...$options) {
197 $this->add(self
::mergeStandardOptions($options, [
204 * Add a CSS file to the current page using <LINK HREF>.
207 * extension name; use 'civicrm' for core.
208 * @param string $file
209 * file path -- relative to the extension base dir.
210 * @param array $options
211 * Open-ended list of options (per add())
212 * Ex: ['weight' => 123]
215 public function addStyleFile(string $ext, string $file, ...$options) {
216 $this->add(self
::mergeStandardOptions($options, [
217 'styleFile' => [$ext, $file],
223 * Add a CSS file to the current page using <LINK HREF>.
226 * @param array $options
227 * Open-ended list of options (per add())
228 * Ex: ['weight' => 123]
231 public function addStyleUrl(string $url, ...$options) {
232 $this->add(self
::mergeStandardOptions($options, [
239 * Add JavaScript variables to the root of the CRM object.
240 * This function is usually reserved for low-level system use.
241 * Extensions and components should generally use addVars instead.
243 * @param array $settings
245 * @param array $options
246 * Extra processing instructions on where/how to place the data.
249 public function addSetting(array $settings, ...$options) {
250 $s = &$this->findCreateSettingSnippet($options);
251 $s['settings'] = self
::mergeSettings($s['settings'], $settings);
256 * Add JavaScript variables to the global CRM object via a callback function.
258 * @param callable $callable
261 public function addSettingsFactory($callable) {
262 $s = &$this->findCreateSettingSnippet();
263 $s['settingsFactories'][] = $callable;
268 * Add JavaScript variables to CRM.vars
272 * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar'));
273 * Access var from javascript:
274 * CRM.vars.myNamespace.foo // "bar"
276 * @see https://docs.civicrm.org/dev/en/latest/standards/javascript/
278 * @param string $nameSpace
279 * Usually the name of your extension.
281 * @param array $options
282 * There are no supported options.
285 public function addVars(string $nameSpace, array $vars, ...$options) {
286 $s = &$this->findCreateSettingSnippet($options);
287 $s['settings']['vars'][$nameSpace] = self
::mergeSettings(
288 $s['settings']['vars'][$nameSpace] ??
[],
295 * Given the "$options" for "addScriptUrl()" (etal), normalize the contents
296 * and potentially add more.
298 * @param array $splats
299 * A list of options, as represented by the splat mechanism ("...$options").
300 * This may appear in one of two ways:
301 * - New (String Index): as in `addFoo($foo, array $options)`
302 * - Old (Numeric Index): as in `addFoo($foo, int $weight = X, string $region = Y, bool $translate = X)`
303 * @param array $defaults
304 * List of values to merge into $options.
307 public static function mergeStandardOptions(array $splats, array $defaults = []) {
308 $count = count($splats);
311 // Common+simple case: No splat options. We can short-circuit.
315 // Might be new format (key-value pairs) or old format
316 $parsed = is_array($splats[0]) ?
$splats[0] : ['weight' => $splats[0]];
320 $parsed = ['weight' => $splats[0], 'region' => $splats[1]];
324 $parsed = ['weight' => $splats[0], 'region' => $splats[1], 'translate' => $splats[2]];
328 throw new \
RuntimeException("Cannot resolve resource options. For clearest behavior, pass options in key-value format.");
331 return array_merge($defaults, $parsed);
335 * Given the "$options" for "addSetting()" (etal), normalize the contents
336 * and potentially add more.
338 * @param array $splats
339 * A list of options, as represented by the splat mechanism ("...$options").
340 * This may appear in one of two ways:
341 * - New (String Index): as in `addFoo($foo, array $options)`
342 * - Old (Numeric Index): as in `addFoo($foo, int $weight = X, string $region = Y, bool $translate = X)`
343 * @param array $defaults
344 * List of values to merge into $options.
347 public static function mergeSettingOptions(array $splats, array $defaults = []) {
348 $count = count($splats);
351 // Common+simple case: No splat options. We can short-circuit.
355 // Might be new format (key-value pairs) or old format
356 $parsed = is_array($splats[0]) ?
$splats[0] : ['region' => $splats[0]];
360 throw new \
RuntimeException("Cannot resolve resource options. For clearest behavior, pass options in key-value format.");
363 return array_merge($defaults, $parsed);
367 * @param array $settings
368 * @param array $additions
370 * combination of $settings and $additions
372 public static function mergeSettings(array $settings, array $additions): array {
373 foreach ($additions as $k => $v) {
374 if (isset($settings[$k]) && is_array($settings[$k]) && is_array($v)) {