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()
22 * Check if the token processor is active.
24 * @param \Civi\Token\TokenProcessor $processor
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());
37 public function getActiveTokens(TokenValueEvent
$e) {
38 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
39 if (!isset($messageTokens[$this->entity
])) {
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;
50 $altToken = preg_replace('/_\d+_/', '_N_', $msgToken);
51 if (array_key_exists($altToken, $this->tokenNames
)) {
52 $activeTokens[] = $msgToken;
56 return array_unique($activeTokens);
60 * Find the fields that we need to get to construct the tokens requested.
61 * @param array $activeTokens list of active tokens
62 * @return array list of fields needed to generate those tokens
64 public function getReturnFields($activeTokens) {
65 // Make sure we always return something
68 $tokensInUse = array_intersect(
70 array_merge(array_keys(self
::getBasicTokens()), array_keys(self
::getCustomFieldTokens()))
72 foreach ($tokensInUse as $token) {
73 if (isset(self
::$fieldMapping[$token])) {
74 $fields = array_merge($fields, self
::$fieldMapping[$token]);
80 return array_unique($fields);
84 * Get the tokens for custom fields
85 * @return array token name => token label
87 protected function getCustomFieldTokens(): array {
88 if (!isset($this->customFieldTokens
)) {
89 $this->customFieldTokens
= \CRM_Utils_Token
::getCustomFieldTokens(ucfirst($this->getEntityName()));
91 return $this->customFieldTokens
;