[NFC] Code cleanup - use use statements, hints
[civicrm-core.git] / CRM / Core / TokenTrait.php
CommitLineData
88d88c53
MW
1<?php
2
c2a33d9c 3use Civi\Token\Event\TokenValueEvent;
4use Civi\Token\TokenProcessor;
5
88d88c53
MW
6trait 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 */
c2a33d9c 24 public function checkActive(TokenProcessor $processor) {
51e25a23 25 return in_array($this->getEntityContextSchema(), $processor->context['schema']) ||
88d88c53
MW
26 (!empty($processor->context['actionMapping'])
27 && $processor->context['actionMapping']->getEntity() === $this->getEntityTableName());
28 }
29
30 /**
31 * @inheritDoc
32 */
c2a33d9c 33 public function getActiveTokens(TokenValueEvent $e) {
88d88c53
MW
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.
f10c962e 57 * @param array $activeTokens list of active tokens
88d88c53
MW
58 * @return array list of fields needed to generate those tokens
59 */
f10c962e 60 public function getReturnFields($activeTokens) {
88d88c53
MW
61 // Make sure we always return something
62 $fields = ['id'];
63
f10c962e
MW
64 $tokensInUse = array_intersect(
65 $activeTokens,
88d88c53 66 array_merge(array_keys(self::getBasicTokens()), array_keys(self::getCustomFieldTokens()))
f10c962e
MW
67 );
68 foreach ($tokensInUse as $token) {
88d88c53
MW
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 */
c2a33d9c 83 protected function getCustomFieldTokens(): array {
88d88c53
MW
84 if (!isset($this->customFieldTokens)) {
85 $this->customFieldTokens = \CRM_Utils_Token::getCustomFieldTokens(ucfirst($this->getEntityName()));
86 }
87 return $this->customFieldTokens;
88 }
89
90}