Merge pull request #21015 from civicrm/5.40
[civicrm-core.git] / CRM / Contribute / Tokens.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
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 +--------------------------------------------------------------------+
11 */
12
13 use Civi\ActionSchedule\Event\MailingQueryEvent;
14 use Civi\Token\AbstractTokenSubscriber;
15 use Civi\Token\TokenProcessor;
16 use Civi\Token\TokenRow;
17
18 /**
19 * Class CRM_Contribute_Tokens
20 *
21 * Generate "contribution.*" tokens.
22 *
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.
25 */
26 class CRM_Contribute_Tokens extends AbstractTokenSubscriber {
27
28 /**
29 * @return string
30 */
31 private function getEntityName(): string {
32 return 'contribution';
33 }
34
35 /**
36 * Get the relevant bao name.
37 */
38 public function getBAOName(): string {
39 return CRM_Core_DAO_AllCoreTables::getFullName(ucfirst($this->getEntityName()));
40 }
41
42 /**
43 * Metadata about the entity fields.
44 *
45 * @var array
46 */
47 protected $entityFieldMetadata = [];
48
49 /**
50 * Get a list of tokens whose name and title match the DB fields.
51 * @return array
52 */
53 protected function getPassthruTokens(): array {
54 return [
55 'contribution_page_id',
56 'receive_date',
57 'total_amount',
58 'fee_amount',
59 'net_amount',
60 'trxn_id',
61 'invoice_id',
62 'currency',
63 'contribution_cancel_date',
64 'receipt_date',
65 'thankyou_date',
66 'tax_amount',
67 'contribution_status_id',
68 ];
69 }
70
71 /**
72 * Get alias tokens.
73 *
74 * @return array
75 */
76 protected function getAliasTokens(): array {
77 return [
78 'id' => 'contribution_id',
79 'payment_instrument' => 'payment_instrument_id',
80 'source' => 'contribution_source',
81 'type' => 'financial_type_id',
82 'cancel_date' => 'contribution_cancel_date',
83 ];
84 }
85
86 /**
87 * Get tokens supporting the syntax we are migrating to.
88 *
89 * In general these are tokens that were not previously supported
90 * so we can add them in the preferred way or that we have
91 * undertaken some, as yet to be written, db update.
92 *
93 * See https://lab.civicrm.org/dev/core/-/issues/2650
94 *
95 * @return string[]
96 */
97 protected function getBasicTokens(): array {
98 return ['contribution_status_id' => ts('Contribution Status ID')];
99 }
100
101 /**
102 * Get pseudoTokens - it tokens that reflect the name or label of a pseudoconstant.
103 *
104 * @internal - this function will likely be made protected soon.
105 *
106 * @return array
107 */
108 public function getPseudoTokens(): array {
109 $return = [];
110 foreach (array_keys($this->getBasicTokens()) as $fieldName) {
111 if (!empty($this->entityFieldMetadata[$fieldName]['pseudoconstant'])) {
112 $return[$fieldName . ':label'] = $this->entityFieldMetadata[$fieldName]['html']['label'];
113 $return[$fieldName . ':name'] = ts('Machine name') . ': ' . $this->entityFieldMetadata[$fieldName]['html']['label'];
114 }
115 }
116 return $return;
117 }
118
119 /**
120 * Class constructor.
121 */
122 public function __construct() {
123 $this->entityFieldMetadata = CRM_Contribute_DAO_Contribution::fields();
124 $tokens = CRM_Utils_Array::subset(
125 CRM_Utils_Array::collect('title', $this->entityFieldMetadata),
126 $this->getPassthruTokens()
127 );
128 $tokens['id'] = ts('Contribution ID');
129 $tokens['payment_instrument'] = ts('Payment Instrument');
130 $tokens['source'] = ts('Contribution Source');
131 $tokens['type'] = ts('Financial Type');
132 $tokens = array_merge($tokens, $this->getPseudoTokens(), CRM_Utils_Token::getCustomFieldTokens('Contribution'));
133 parent::__construct('contribution', $tokens);
134 }
135
136 /**
137 * Check if the token processor is active.
138 *
139 * @param \Civi\Token\TokenProcessor $processor
140 *
141 * @return bool
142 */
143 public function checkActive(TokenProcessor $processor) {
144 return !empty($processor->context['actionMapping'])
145 && $processor->context['actionMapping']->getEntity() === 'civicrm_contribution';
146 }
147
148 /**
149 * Alter action schedule query.
150 *
151 * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
152 */
153 public function alterActionScheduleQuery(MailingQueryEvent $e): void {
154 if ($e->mapping->getEntity() !== 'civicrm_contribution') {
155 return;
156 }
157
158 $fields = CRM_Contribute_DAO_Contribution::fields();
159 foreach ($this->getPassthruTokens() as $token) {
160 $e->query->select("e." . $fields[$token]['name'] . " AS contrib_{$token}");
161 }
162 foreach (array_keys($this->getPseudoTokens()) as $token) {
163 $split = explode(':', $token);
164 $e->query->select("e." . $fields[$split[0]]['name'] . " AS contrib_{$split[0]}");
165 }
166 foreach ($this->getAliasTokens() as $alias => $orig) {
167 $e->query->select('e.' . $fields[$orig]['name'] . " AS contrib_{$alias}");
168 }
169 }
170
171 /**
172 * @inheritDoc
173 */
174 public function evaluateToken(TokenRow $row, $entity, $field, $prefetch = NULL) {
175 $actionSearchResult = $row->context['actionSearchResult'];
176 $fieldValue = $actionSearchResult->{"contrib_$field"} ?? NULL;
177
178 $aliasTokens = $this->getAliasTokens();
179 if (in_array($field, ['total_amount', 'fee_amount', 'net_amount'])) {
180 return $row->format('text/plain')->tokens($entity, $field,
181 \CRM_Utils_Money::format($fieldValue, $actionSearchResult->contrib_currency));
182 }
183 if (isset($aliasTokens[$field])) {
184 $row->dbToken($entity, $field, 'CRM_Contribute_BAO_Contribution', $aliasTokens[$field], $fieldValue);
185 }
186 elseif ($cfID = \CRM_Core_BAO_CustomField::getKeyID($field)) {
187 $row->customToken($entity, $cfID, $actionSearchResult->entity_id);
188 }
189 elseif (array_key_exists($field, $this->getPseudoTokens())) {
190 $split = explode(':', $field);
191 $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $actionSearchResult->{"contrib_$split[0]"} ?? NULL));
192 }
193 elseif (in_array($field, array_keys($this->getBasicTokens()))) {
194 $row->tokens($entity, $field, $fieldValue);
195 }
196 else {
197 $row->dbToken($entity, $field, 'CRM_Contribute_BAO_Contribution', $field, $fieldValue);
198 }
199 }
200
201 /**
202 * Get the value for the relevant pseudo field.
203 *
204 * @param string $realField e.g contribution_status_id
205 * @param string $pseudoKey e.g name
206 * @param int|string $fieldValue e.g 1
207 *
208 * @return string
209 * Eg. 'Completed' in the example above.
210 *
211 * @internal function will likely be protected soon.
212 */
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);
216 }
217 if ($pseudoKey === 'label') {
218 $fieldValue = (string) CRM_Core_PseudoConstant::getLabel($this->getBAOName(), $realField, $fieldValue);
219 }
220 return (string) $fieldValue;
221 }
222
223 }