3 use Civi\Token\Event\TokenValueEvent
;
4 use Civi\Token\TokenProcessor
;
6 trait CRM_Core_TokenTrait
{
9 private $customFieldTokens;
12 * CRM_Entity_Tokens constructor.
14 public function __construct() {
15 parent
::__construct($this->getEntityName(), array_merge(
16 $this->getBasicTokens(),
17 $this->getCustomFieldTokens()
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());
33 public function getActiveTokens(TokenValueEvent
$e) {
34 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
35 if (!isset($messageTokens[$this->entity
])) {
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;
46 $altToken = preg_replace('/_\d+_/', '_N_', $msgToken);
47 if (array_key_exists($altToken, $this->tokenNames
)) {
48 $activeTokens[] = $msgToken;
52 return array_unique($activeTokens);
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
60 public function getReturnFields($activeTokens) {
61 // Make sure we always return something
64 $tokensInUse = array_intersect(
66 array_merge(array_keys(self
::getBasicTokens()), array_keys(self
::getCustomFieldTokens()))
68 foreach ($tokensInUse as $token) {
69 if (isset(self
::$fieldMapping[$token])) {
70 $fields = array_merge($fields, self
::$fieldMapping[$token]);
76 return array_unique($fields);
80 * Get the tokens for custom fields
81 * @return array token name => token label
83 protected function getCustomFieldTokens(): array {
84 if (!isset($this->customFieldTokens
)) {
85 $this->customFieldTokens
= \CRM_Utils_Token
::getCustomFieldTokens(ucfirst($this->getEntityName()));
87 return $this->customFieldTokens
;