[REF][PHP8.1] Add in type hints to fix deprecations and add in #[\ReturnTypeWillChang...
[civicrm-core.git] / Civi / Token / TokenRow.php
1 <?php
2 namespace Civi\Token;
3
4 use Brick\Money\Money;
5
6 /**
7 * Class TokenRow
8 *
9 * @package Civi\Token
10 *
11 * A TokenRow is a helper/stub providing simplified access to the TokenProcessor.
12 * There are two common cases for using the TokenRow stub:
13 *
14 * (1) When setting up a job, you may specify general/baseline info.
15 * This is called the "context" data. Here, we create two rows:
16 *
17 * ```
18 * $proc->addRow()->context('contact_id', 123);
19 * $proc->addRow()->context('contact_id', 456);
20 * ```
21 *
22 * (2) When defining a token (eg `{profile.viewUrl}`), you might read the
23 * context-data (`contact_id`) and set the token-data (`profile => viewUrl`):
24 *
25 * ```
26 * foreach ($proc->getRows() as $row) {
27 * $row->tokens('profile', [
28 * 'viewUrl' => 'http://example.com/profile?cid=' . urlencode($row->context['contact_id'];
29 * ]);
30 * }
31 * ```
32 *
33 * The context and tokens can be accessed using either methods or attributes.
34 *
35 * ```
36 * # Setting context data
37 * $row->context('contact_id', 123);
38 * $row->context(['contact_id' => 123]);
39 *
40 * # Setting token data
41 * $row->tokens('profile', ['viewUrl' => 'http://example.com/profile?cid=123']);
42 * $row->tokens('profile', 'viewUrl, 'http://example.com/profile?cid=123');
43 *
44 * # Reading context data
45 * echo $row->context['contact_id'];
46 *
47 * # Reading token data
48 * echo $row->tokens['profile']['viewUrl'];
49 * ```
50 *
51 * Note: The methods encourage a "fluent" style. They were written for PHP 5.3
52 * (eg before short-array syntax was supported) and are fairly flexible about
53 * input notations (e.g. `context(string $key, mixed $value)` vs `context(array $keyValuePairs)`).
54 *
55 * Note: An instance of `TokenRow` is a stub which only contains references to the
56 * main data in `TokenProcessor`. There may be several `TokenRow` stubs
57 * referencing the same `TokenProcessor`. You can think of `TokenRow` objects as
58 * lightweight and disposable.
59 */
60 class TokenRow {
61
62 /**
63 * The token-processor is where most data is actually stored.
64 *
65 * Note: Not intended for public usage. However, this is marked public to allow
66 * interaction classes in this package (`TokenProcessor`<=>`TokenRow`<=>`TokenRowContext`).
67 *
68 * @var TokenProcessor
69 */
70 public $tokenProcessor;
71
72 /**
73 * Row ID - the record within TokenProcessor that we're accessing.
74 *
75 * @var int
76 */
77 public $tokenRow;
78
79 /**
80 * The MIME type associated with new token-values.
81 *
82 * This is generally manipulated as part of a fluent chain, eg
83 *
84 * $row->format('text/plain')->token(['display_name', 'Alice Bobdaughter']);
85 *
86 * @var string
87 */
88 public $format;
89
90 /**
91 * @var array|\ArrayAccess
92 * List of token values.
93 * This is a facade for the TokenProcessor::$rowValues.
94 * Ex: ['contact' => ['display_name' => 'Alice']]
95 */
96 public $tokens;
97
98 /**
99 * @var array|\ArrayAccess
100 * List of context values.
101 * This is a facade for the TokenProcessor::$rowContexts.
102 * Ex: ['controller' => 'CRM_Foo_Bar']
103 */
104 public $context;
105
106 public function __construct(TokenProcessor $tokenProcessor, $key) {
107 $this->tokenProcessor = $tokenProcessor;
108 $this->tokenRow = $key;
109 // Set a default.
110 $this->format('text/plain');
111 $this->context = new TokenRowContext($tokenProcessor, $key);
112 }
113
114 /**
115 * @param string $format
116 * @return TokenRow
117 */
118 public function format($format) {
119 $this->format = $format;
120 $this->tokens = &$this->tokenProcessor->rowValues[$this->tokenRow][$format];
121 return $this;
122 }
123
124 /**
125 * Update the value of a context element.
126 *
127 * @param string|array $a
128 * @param mixed $b
129 * @return TokenRow
130 */
131 public function context($a = NULL, $b = NULL) {
132 if (is_array($a)) {
133 \CRM_Utils_Array::extend($this->tokenProcessor->rowContexts[$this->tokenRow], $a);
134 }
135 elseif (is_array($b)) {
136 \CRM_Utils_Array::extend($this->tokenProcessor->rowContexts[$this->tokenRow][$a], $b);
137 }
138 else {
139 $this->tokenProcessor->rowContexts[$this->tokenRow][$a] = $b;
140 }
141 return $this;
142 }
143
144 /**
145 * Update the value of a token.
146 *
147 * If you are reading this it probably means you can't follow this function.
148 * Don't worry - I've stared at it & all I see is a bunch of letters. However,
149 * the answer to your problem is almost certainly that you are passing in null
150 * rather than an empty string for 'c'.
151 *
152 * @param string|array $a
153 * @param string|array $b
154 * @param mixed $c
155 * @return TokenRow
156 */
157 public function tokens($a = NULL, $b = NULL, $c = NULL) {
158 if (is_array($a)) {
159 \CRM_Utils_Array::extend($this->tokens, $a);
160 }
161 elseif (is_array($b)) {
162 \CRM_Utils_Array::extend($this->tokens[$a], $b);
163 }
164 elseif (is_array($c)) {
165 \CRM_Utils_Array::extend($this->tokens[$a][$b], $c);
166 }
167 elseif ($c === NULL) {
168 $this->tokens[$a] = $b;
169 }
170 else {
171 $this->tokens[$a][$b] = $c;
172 }
173 return $this;
174 }
175
176 /**
177 * Update the value of a custom field token.
178 *
179 * @param string $entity
180 * @param int $customFieldID
181 * @param int $entityID
182 * @return TokenRow
183 */
184 public function customToken($entity, $customFieldID, $entityID) {
185 $customFieldName = 'custom_' . $customFieldID;
186 $record = civicrm_api3($entity, 'getSingle', [
187 'return' => $customFieldName,
188 'id' => $entityID,
189 ]);
190 $fieldValue = \CRM_Utils_Array::value($customFieldName, $record, '');
191
192 // format the raw custom field value into proper display value
193 if (isset($fieldValue)) {
194 $fieldValue = (string) \CRM_Core_BAO_CustomField::displayValue($fieldValue, $customFieldID);
195 }
196
197 return $this->format('text/html')->tokens($entity, $customFieldName, $fieldValue);
198 }
199
200 /**
201 * Update the value of a token. Apply formatting based on DB schema.
202 *
203 * @param string $tokenEntity
204 * @param string $tokenField
205 * @param string $baoName
206 * @param string $baoField
207 * @param mixed $fieldValue
208 * @return TokenRow
209 * @throws \CRM_Core_Exception
210 */
211 public function dbToken($tokenEntity, $tokenField, $baoName, $baoField, $fieldValue) {
212 \CRM_Core_Error::deprecatedFunctionWarning('no alternative');
213 if ($fieldValue === NULL || $fieldValue === '') {
214 return $this->tokens($tokenEntity, $tokenField, '');
215 }
216
217 $fields = $baoName::fields();
218 if (!empty($fields[$baoField]['pseudoconstant'])) {
219 $options = $baoName::buildOptions($baoField, 'get');
220 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $options[$fieldValue]);
221 }
222
223 switch ($fields[$baoField]['type']) {
224 case \CRM_Utils_Type::T_DATE + \CRM_Utils_Type::T_TIME:
225 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Date::customFormat($fieldValue));
226
227 case \CRM_Utils_Type::T_MONEY:
228 // Is this something you should ever use? Seems like you need more context
229 // to know which currency to use.
230 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, \CRM_Utils_Money::format($fieldValue));
231
232 case \CRM_Utils_Type::T_STRING:
233 case \CRM_Utils_Type::T_BOOLEAN:
234 case \CRM_Utils_Type::T_INT:
235 case \CRM_Utils_Type::T_TEXT:
236 return $this->format('text/plain')->tokens($tokenEntity, $tokenField, $fieldValue);
237
238 }
239
240 throw new \CRM_Core_Exception("Cannot format token for field '$baoField' in '$baoName'");
241 }
242
243 /**
244 * Auto-convert between different formats
245 *
246 * @param string $format
247 *
248 * @return TokenRow
249 */
250 public function fill($format = NULL) {
251 if ($format === NULL) {
252 $format = $this->format;
253 }
254
255 if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/html'])) {
256 $this->tokenProcessor->rowValues[$this->tokenRow]['text/html'] = [];
257 }
258 if (!isset($this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'])) {
259 $this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'] = [];
260 }
261
262 $htmlTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/html'];
263 $textTokens = &$this->tokenProcessor->rowValues[$this->tokenRow]['text/plain'];
264
265 switch ($format) {
266 case 'text/html':
267 // Plain => HTML.
268 foreach ($textTokens as $entity => $values) {
269 $entityFields = civicrm_api3($entity, "getFields", ['api_action' => 'get']);
270 foreach ($values as $field => $value) {
271 if (!isset($htmlTokens[$entity][$field])) {
272 // CRM-18420 - Activity Details Field are enclosed within <p>,
273 // hence if $body_text is empty, htmlentities will lead to
274 // conversion of these tags resulting in raw HTML.
275 if ($entity == 'activity' && $field == 'details') {
276 $htmlTokens[$entity][$field] = $value;
277 }
278 elseif (\CRM_Utils_Array::value('data_type', \CRM_Utils_Array::value($field, $entityFields['values'])) == 'Memo') {
279 // Memo fields aka custom fields of type Note are html.
280 $htmlTokens[$entity][$field] = \CRM_Utils_String::purifyHTML($value);
281 }
282 else {
283 $htmlTokens[$entity][$field] = is_object($value) ? $value : htmlentities($value, ENT_QUOTES);
284 }
285 }
286 }
287 }
288 break;
289
290 case 'text/plain':
291 // HTML => Plain.
292 foreach ($htmlTokens as $entity => $values) {
293 foreach ($values as $field => $value) {
294 if (!$value instanceof \DateTime && !$value instanceof Money) {
295 $value = html_entity_decode(strip_tags($value));
296 }
297 if (!isset($textTokens[$entity][$field])) {
298 $textTokens[$entity][$field] = $value;
299 }
300 }
301 }
302 break;
303
304 default:
305 throw new \RuntimeException('Invalid format');
306 }
307
308 return $this;
309 }
310
311 /**
312 * Render a message.
313 *
314 * @param string $name
315 * The name previously registered with TokenProcessor::addMessage.
316 * @return string
317 * Fully rendered message, with tokens merged.
318 */
319 public function render($name) {
320 return $this->tokenProcessor->render($name, $this);
321 }
322
323 }
324
325 /**
326 * Class TokenRowContext
327 * @package Civi\Token
328 *
329 * Combine the row-context and general-context into a single array-like facade.
330 */
331 class TokenRowContext implements \ArrayAccess, \IteratorAggregate, \Countable {
332
333 /**
334 * @var TokenProcessor
335 */
336 protected $tokenProcessor;
337
338 protected $tokenRow;
339
340 /**
341 * Class constructor.
342 *
343 * @param array $tokenProcessor
344 * @param array $tokenRow
345 */
346 public function __construct($tokenProcessor, $tokenRow) {
347 $this->tokenProcessor = $tokenProcessor;
348 $this->tokenRow = $tokenRow;
349 }
350
351 /**
352 * Does offset exist.
353 *
354 * @param mixed $offset
355 *
356 * @return bool
357 */
358 public function offsetExists($offset): bool {
359 return isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset])
360 || isset($this->tokenProcessor->context[$offset]);
361 }
362
363 /**
364 * Get offset.
365 *
366 * @param string $offset
367 *
368 * @return string
369 */
370 #[\ReturnTypeWillChange]
371 public function &offsetGet($offset) {
372 if (isset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset])) {
373 return $this->tokenProcessor->rowContexts[$this->tokenRow][$offset];
374 }
375 if (isset($this->tokenProcessor->context[$offset])) {
376 return $this->tokenProcessor->context[$offset];
377 }
378 $val = NULL;
379 return $val;
380 }
381
382 /**
383 * Set offset.
384 *
385 * @param string $offset
386 * @param mixed $value
387 */
388 public function offsetSet($offset, $value): void {
389 $this->tokenProcessor->rowContexts[$this->tokenRow][$offset] = $value;
390 }
391
392 /**
393 * Unset offset.
394 *
395 * @param mixed $offset
396 */
397 public function offsetUnset($offset): void {
398 unset($this->tokenProcessor->rowContexts[$this->tokenRow][$offset]);
399 }
400
401 /**
402 * Get iterator.
403 *
404 * @return \ArrayIterator
405 */
406 #[\ReturnTypeWillChange]
407 public function getIterator() {
408 return new \ArrayIterator($this->createMergedArray());
409 }
410
411 /**
412 * Count.
413 *
414 * @return int
415 */
416 public function count(): int {
417 return count($this->createMergedArray());
418 }
419
420 /**
421 * Create merged array.
422 *
423 * @return array
424 */
425 protected function createMergedArray() {
426 return array_merge(
427 $this->tokenProcessor->rowContexts[$this->tokenRow],
428 $this->tokenProcessor->context
429 );
430 }
431
432 }