[NFC] Code cleanup - use use statements, hints
[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 * @inheritDoc
23 */
24 public function checkActive(TokenProcessor $processor) {
25 return in_array($this->getEntityContextSchema(), $processor->context['schema']) ||
26 (!empty($processor->context['actionMapping'])
27 && $processor->context['actionMapping']->getEntity() === $this->getEntityTableName());
28 }
29
30 /**
31 * @inheritDoc
32 */
33 public function getActiveTokens(TokenValueEvent $e) {
34 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
35 if (!isset($messageTokens[$this->entity])) {
36 return NULL;
37 }
38
39 $activeTokens = [];
40 // if message token contains '_\d+_', then treat as '_N_'
41 foreach ($messageTokens[$this->entity] as $msgToken) {
42 if (array_key_exists($msgToken, $this->tokenNames)) {
43 $activeTokens[] = $msgToken;
44 }
45 else {
46 $altToken = preg_replace('/_\d+_/', '_N_', $msgToken);
47 if (array_key_exists($altToken, $this->tokenNames)) {
48 $activeTokens[] = $msgToken;
49 }
50 }
51 }
52 return array_unique($activeTokens);
53 }
54
55 /**
56 * Find the fields that we need to get to construct the tokens requested.
57 * @param array $activeTokens list of active tokens
58 * @return array list of fields needed to generate those tokens
59 */
60 public function getReturnFields($activeTokens) {
61 // Make sure we always return something
62 $fields = ['id'];
63
64 $tokensInUse = array_intersect(
65 $activeTokens,
66 array_merge(array_keys(self::getBasicTokens()), array_keys(self::getCustomFieldTokens()))
67 );
68 foreach ($tokensInUse as $token) {
69 if (isset(self::$fieldMapping[$token])) {
70 $fields = array_merge($fields, self::$fieldMapping[$token]);
71 }
72 else {
73 $fields[] = $token;
74 }
75 }
76 return array_unique($fields);
77 }
78
79 /**
80 * Get the tokens for custom fields
81 * @return array token name => token label
82 */
83 protected function getCustomFieldTokens(): array {
84 if (!isset($this->customFieldTokens)) {
85 $this->customFieldTokens = \CRM_Utils_Token::getCustomFieldTokens(ucfirst($this->getEntityName()));
86 }
87 return $this->customFieldTokens;
88 }
89
90 }