4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
13 use Civi\ActionSchedule\Event\MailingQueryEvent
;
14 use Civi\Token\AbstractTokenSubscriber
;
15 use Civi\Token\TokenProcessor
;
16 use Civi\Token\TokenRow
;
19 * Class CRM_Contribute_Tokens
21 * Generate "contribution.*" tokens.
23 * At time of writing, we don't have any particularly special tokens -- we just
24 * do some basic formatting based on the corresponding DB field.
26 class CRM_Contribute_Tokens
extends AbstractTokenSubscriber
{
31 protected function getEntityName(): string {
32 return 'contribution';
36 * Get the relevant bao name.
38 public function getBAOName(): string {
39 return CRM_Core_DAO_AllCoreTables
::getFullName(ucfirst($this->getEntityName()));
43 * Metadata about the entity fields.
47 protected $fieldMetadata = [];
50 * Get a list of tokens whose name and title match the DB fields.
53 protected function getPassthruTokens(): array {
55 'contribution_page_id',
69 'contribution_status_id',
71 'payment_instrument_id',
76 * Get tokens supporting the syntax we are migrating to.
78 * In general these are tokens that were not previously supported
79 * so we can add them in the preferred way or that we have
80 * undertaken some, as yet to be written, db update.
82 * See https://lab.civicrm.org/dev/core/-/issues/2650
86 public function getBasicTokens(): array {
88 foreach (['contribution_status_id', 'payment_instrument_id', 'financial_type_id'] as $fieldName) {
89 $return[$fieldName] = $this->getFieldMetadata()[$fieldName]['title'];
95 * Get pseudoTokens - it tokens that reflect the name or label of a pseudoconstant.
97 * @internal - this function will likely be made protected soon.
101 public function getPseudoTokens(): array {
103 foreach (array_keys($this->getBasicTokens()) as $fieldName) {
104 if (!empty($this->fieldMetadata
[$fieldName]['pseudoconstant'])) {
105 $return[$fieldName . ':label'] = $this->fieldMetadata
[$fieldName]['html']['label'];
106 $return[$fieldName . ':name'] = ts('Machine name') . ': ' . $this->fieldMetadata
[$fieldName]['html']['label'];
115 public function __construct() {
116 $tokens = CRM_Utils_Array
::subset(
117 CRM_Utils_Array
::collect('title', $this->getFieldMetadata()),
118 $this->getPassthruTokens()
120 $tokens = array_merge($tokens, $this->getPseudoTokens(), CRM_Utils_Token
::getCustomFieldTokens('Contribution'));
121 parent
::__construct('contribution', $tokens);
125 * Check if the token processor is active.
127 * @param \Civi\Token\TokenProcessor $processor
131 public function checkActive(TokenProcessor
$processor) {
132 return !empty($processor->context
['actionMapping'])
133 && $processor->context
['actionMapping']->getEntity() === 'civicrm_contribution';
137 * Alter action schedule query.
139 * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
141 public function alterActionScheduleQuery(MailingQueryEvent
$e): void
{
142 if ($e->mapping
->getEntity() !== 'civicrm_contribution') {
146 $fields = $this->getFieldMetadata();
147 foreach ($this->getPassthruTokens() as $token) {
148 $e->query
->select("e." . $fields[$token]['name'] . " AS contrib_{$token}");
150 foreach (array_keys($this->getPseudoTokens()) as $token) {
151 $split = explode(':', $token);
152 $e->query
->select("e." . $fields[$split[0]]['name'] . " AS contrib_{$split[0]}");
159 public function evaluateToken(TokenRow
$row, $entity, $field, $prefetch = NULL) {
160 $actionSearchResult = $row->context
['actionSearchResult'];
161 $fieldValue = $actionSearchResult->{"contrib_$field"} ??
NULL;
163 if (in_array($field, ['total_amount', 'fee_amount', 'net_amount'])) {
164 return $row->format('text/plain')->tokens($entity, $field,
165 \CRM_Utils_Money
::format($fieldValue, $actionSearchResult->contrib_currency
));
167 elseif ($cfID = \CRM_Core_BAO_CustomField
::getKeyID($field)) {
168 $row->customToken($entity, $cfID, $actionSearchResult->entity_id
);
170 elseif (array_key_exists($field, $this->getPseudoTokens())) {
171 $split = explode(':', $field);
172 $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $actionSearchResult->{"contrib_$split[0]"} ??
NULL));
174 elseif (in_array($field, array_keys($this->getBasicTokens()))) {
175 $row->tokens($entity, $field, $fieldValue);
177 elseif (!array_key_exists($field, CRM_Contribute_BAO_Contribution
::fields())) {
178 if ($this->isDateField($field)) {
179 $row->format('text/plain')->tokens($entity, $field, \CRM_Utils_Date
::customFormat($fieldValue));
182 $row->format('text/plain')->tokens($entity, $field, $fieldValue);
186 $row->dbToken($entity, $field, 'CRM_Contribute_BAO_Contribution', $field, $fieldValue);
191 * Is the given field a date field.
193 * @param string $fieldName
197 public function isDateField($fieldName): bool {
198 return $this->getFieldMetadata()[$fieldName]['type'] === (\CRM_Utils_Type
::T_DATE + \CRM_Utils_Type
::T_TIME
);
202 * Get the value for the relevant pseudo field.
204 * @param string $realField e.g contribution_status_id
205 * @param string $pseudoKey e.g name
206 * @param int|string $fieldValue e.g 1
209 * Eg. 'Completed' in the example above.
211 * @internal function will likely be protected soon.
213 public function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
214 if ($pseudoKey === 'name') {
215 $fieldValue = (string) CRM_Core_PseudoConstant
::getName($this->getBAOName(), $realField, $fieldValue);
217 if ($pseudoKey === 'label') {
218 $fieldValue = (string) CRM_Core_PseudoConstant
::getLabel($this->getBAOName(), $realField, $fieldValue);
220 return (string) $fieldValue;
224 * Get the metadata for the available fields.
228 protected function getFieldMetadata(): array {
229 if (empty($this->fieldMetadata
)) {
230 $baoName = $this->getBAOName();
231 $fields = (array) $baoName::fields();
232 // re-index by real field name. I originally wanted to use apiv4
233 // getfields - but it returns different stuff for 'type' and
234 // does not return 'pseudoconstant' as a key so for now...
235 foreach ($fields as $details) {
236 $this->fieldMetadata
[$details['name']] = $details;
239 return $this->fieldMetadata
;