Update release-notes/5.52.1.md
[civicrm-core.git] / CRM / Core / TokenTrait.php
1 <?php
2
3 use Civi\Token\Event\TokenValueEvent;
4 use Civi\Token\TokenProcessor;
5
6 trait CRM_Core_TokenTrait {
7
8 private $basicTokens;
9 private $customFieldTokens;
10
11 /**
12 * CRM_Entity_Tokens constructor.
13 */
14 public function __construct() {
15 parent::__construct($this->getEntityName(), array_merge(
16 $this->getBasicTokens(),
17 $this->getCustomFieldTokens()
18 ));
19 }
20
21 /**
22 * Check if the token processor is active.
23 *
24 * @param \Civi\Token\TokenProcessor $processor
25 *
26 * @return bool
27 */
28 public function checkActive(TokenProcessor $processor) {
29 return in_array($this->getEntityContextSchema(), $processor->context['schema']) ||
30 (!empty($processor->context['actionMapping'])
31 && $processor->context['actionMapping']->getEntity() === $this->getEntityTableName());
32 }
33
34 /**
35 * @inheritDoc
36 */
37 public function getActiveTokens(TokenValueEvent $e) {
38 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
39 if (!isset($messageTokens[$this->entity])) {
40 return NULL;
41 }
42
43 $activeTokens = [];
44 // if message token contains '_\d+_', then treat as '_N_'
45 foreach ($messageTokens[$this->entity] as $msgToken) {
46 if (array_key_exists($msgToken, $this->tokenNames)) {
47 $activeTokens[] = $msgToken;
48 }
49 }
50 return array_unique($activeTokens);
51 }
52
53 /**
54 * Find the fields that we need to get to construct the tokens requested.
55 *
56 * @return array list of fields needed to generate those tokens
57 */
58 public function getReturnFields(): array {
59 // Make sure we always return something
60 $fields = ['id'];
61
62 $tokensInUse =
63 array_merge(array_keys(self::getBasicTokens()), array_keys(self::getCustomFieldTokens()));
64 foreach ($tokensInUse as $token) {
65 if (isset(self::$fieldMapping[$token])) {
66 $fields = array_merge($fields, self::$fieldMapping[$token]);
67 }
68 else {
69 $fields[] = $token;
70 }
71 }
72 return array_unique($fields);
73 }
74
75 /**
76 * Get the tokens for custom fields
77 * @return array token name => token label
78 */
79 protected function getCustomFieldTokens(): array {
80 if (!isset($this->customFieldTokens)) {
81 $this->customFieldTokens = [];
82 foreach (CRM_Core_BAO_CustomField::getFields(ucfirst($this->getEntityName())) as $id => $info) {
83 $this->customFieldTokens['custom_' . $id] = $info['label'] . ' :: ' . $info['groupTitle'];
84 }
85 }
86 return $this->customFieldTokens;
87 }
88
89 }