use Civi\Token\TokenRow;
use Civi\ActionSchedule\Event\MailingQueryEvent;
use Civi\Token\TokenProcessor;
+use Brick\Money\Money;
/**
* Class CRM_Core_EntityTokens
* @return array
*/
protected function getTokenMetadata(): array {
- if (empty($this->tokensMetadata)) {
- $cacheKey = $this->getCacheKey();
- if (Civi::cache('metadata')->has($cacheKey)) {
- $this->tokensMetadata = Civi::cache('metadata')->get($cacheKey);
+ $cacheKey = $this->getCacheKey();
+ if (!Civi::cache('metadata')->has($cacheKey)) {
+ $tokensMetadata = $this->getBespokeTokens();
+ foreach ($this->getFieldMetadata() as $field) {
+ $this->addFieldToTokenMetadata($tokensMetadata, $field, $this->getExposedFields());
}
- else {
- $this->tokensMetadata = $this->getBespokeTokens();
- foreach ($this->getFieldMetadata() as $field) {
- $this->addFieldToTokenMetadata($field, $this->getExposedFields());
- }
- foreach ($this->getHiddenTokens() as $name) {
- $this->tokensMetadata[$name]['audience'] = 'hidden';
- }
- Civi::cache('metadata')->set($cacheKey, $this->tokensMetadata);
+ foreach ($this->getHiddenTokens() as $name) {
+ $tokensMetadata[$name]['audience'] = 'hidden';
}
+ Civi::cache('metadata')->set($cacheKey, $tokensMetadata);
}
- return $this->tokensMetadata;
+ return Civi::cache('metadata')->get($cacheKey);
}
/**
return $row->customToken($entity, \CRM_Core_BAO_CustomField::getKeyID($field), $this->getFieldValue($row, 'id'));
}
if ($this->isMoneyField($field)) {
+ $currency = $this->getCurrency($row);
+ if (empty($fieldValue) && !is_numeric($fieldValue)) {
+ $fieldValue = 0;
+ }
+ if (!$currency) {
+ // too hard basket for now - just do what we always did.
+ return $row->format('text/plain')->tokens($entity, $field,
+ \CRM_Utils_Money::format($fieldValue, $currency));
+ }
return $row->format('text/plain')->tokens($entity, $field,
- \CRM_Utils_Money::format($fieldValue, $this->getCurrency($row)));
+ Money::of($fieldValue, $currency));
+
}
if ($this->isDateField($field)) {
try {
return CRM_Core_DAO_AllCoreTables::getTableForEntityName($this->getApiEntityName());
}
- /**
- * Get the relevant bao name.
- */
- public function getBAOName(): string {
- return CRM_Core_DAO_AllCoreTables::getFullName($this->getApiEntityName());
- }
-
/**
* Get an array of fields to be requested.
*
+ * @todo this function should look up tokenMetadata that
+ * is already loaded.
+ *
* @return string[]
*/
- public function getReturnFields(): array {
+ protected function getReturnFields(): array {
return array_keys($this->getBasicTokens());
}
*
* @return bool
*/
- public function isBooleanField(string $fieldName): bool {
+ protected function isBooleanField(string $fieldName): bool {
return $this->getMetadataForField($fieldName)['data_type'] === 'Boolean';
}
*
* @return bool
*/
- public function isDateField(string $fieldName): bool {
+ protected function isDateField(string $fieldName): bool {
return in_array($this->getMetadataForField($fieldName)['data_type'], ['Timestamp', 'Date'], TRUE);
}
*
* @return bool
*/
- public function isPseudoField(string $fieldName): bool {
+ protected function isPseudoField(string $fieldName): bool {
return strpos($fieldName, ':') !== FALSE;
}
*
* @return bool
*/
- public function isCustomField(string $fieldName) : bool {
+ protected function isCustomField(string $fieldName) : bool {
return (bool) \CRM_Core_BAO_CustomField::getKeyID($fieldName);
}
*
* @return bool
*/
- public function isMoneyField(string $fieldName): bool {
+ protected function isMoneyField(string $fieldName): bool {
return $this->getMetadataForField($fieldName)['data_type'] === 'Money';
}
* @internal function will likely be protected soon.
*/
protected function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
+ $bao = CRM_Core_DAO_AllCoreTables::getFullName($this->getMetadataForField($realField)['entity']);
if ($pseudoKey === 'name') {
- $fieldValue = (string) CRM_Core_PseudoConstant::getName($this->getBAOName(), $realField, $fieldValue);
+ $fieldValue = (string) CRM_Core_PseudoConstant::getName($bao, $realField, $fieldValue);
}
if ($pseudoKey === 'label') {
- $fieldValue = (string) CRM_Core_PseudoConstant::getLabel($this->getBAOName(), $realField, $fieldValue);
+ $fieldValue = (string) CRM_Core_PseudoConstant::getLabel($bao, $realField, $fieldValue);
+ }
+ if ($pseudoKey === 'abbr' && $realField === 'state_province_id') {
+ // hack alert - currently only supported for state.
+ $fieldValue = (string) CRM_Core_PseudoConstant::stateProvinceAbbreviation($fieldValue);
}
return (string) $fieldValue;
}
return $row->context[$entityName][$field];
}
- $actionSearchResult = $row->context['actionSearchResult'];
- $aliasedField = $this->getEntityAlias() . $field;
- if (isset($actionSearchResult->{$aliasedField})) {
- return $actionSearchResult->{$aliasedField};
- }
$entityID = $row->context[$this->getEntityIDField()];
if ($field === 'id') {
return $entityID;
if ($e->mapping->getEntity() !== $this->getExtendableTableName()) {
return;
}
- foreach ($this->getReturnFields() as $token) {
- $e->query->select('e.' . $token . ' AS ' . $this->getEntityAlias() . $token);
- }
+ $e->query->select('e.id AS tokenContext_' . $this->getEntityIDField());
}
/**
}
/**
- * Get tokens supporting the syntax we are migrating to.
- *
- * In general these are tokens that were not previously supported
- * so we can add them in the preferred way or that we have
- * undertaken some, as yet to be written, db update.
- *
- * See https://lab.civicrm.org/dev/core/-/issues/2650
+ * @todo remove this function & use the metadata that is loaded.
*
* @return string[]
* @throws \API_Exception
*/
- public function getBasicTokens(): array {
+ protected function getBasicTokens(): array {
$return = [];
foreach ($this->getExposedFields() as $fieldName) {
// Custom fields are still added v3 style - we want to keep v4 naming 'unpoluted'
return CRM_Core_DAO_AllCoreTables::convertEntityNameToLower($this->getApiEntityName());
}
- public function getEntityIDField(): string {
+ protected function getEntityIDField(): string {
return $this->getEntityName() . 'Id';
}
return $result;
}
- public function getCurrencyFieldName() {
+ protected function getCurrencyFieldName() {
return [];
}
*
* @return string
*/
- public function getCurrency($row): string {
+ protected function getCurrency($row): string {
if (!empty($this->getCurrencyFieldName())) {
return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]);
}
*
* @return array
*/
- public function getDependencies(): array {
+ protected function getDependencies(): array {
return [];
}
* @param int $id
*
* @return string
+ *
+ * @throws \CRM_Core_Exception
*/
protected function getCustomFieldName(int $id): string {
foreach ($this->getTokenMetadata() as $key => $field) {
return $key;
}
}
+ throw new CRM_Core_Exception(
+ "A custom field with the ID {$id} does not exist"
+ );
}
/**
*/
protected function getCustomFieldValue($entityID, string $field) {
$id = str_replace('custom_', '', $field);
- $value = $this->prefetch[$entityID][$this->getCustomFieldName($id)] ?? '';
- if ($value !== NULL) {
- return CRM_Core_BAO_CustomField::displayValue($value, $id);
+ try {
+ $value = $this->prefetch[$entityID][$this->getCustomFieldName($id)] ?? '';
+ if ($value !== NULL) {
+ return CRM_Core_BAO_CustomField::displayValue($value, $id);
+ }
+ }
+ catch (CRM_Core_Exception $exception) {
+ return NULL;
}
}
if (isset($this->getTokenMetadata()[$fieldName])) {
return $this->getTokenMetadata()[$fieldName];
}
- return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]];
+ if (isset($this->getTokenMappingsForRelatedEntities()[$fieldName])) {
+ return $this->getTokenMetadata()[$this->getTokenMappingsForRelatedEntities()[$fieldName]];
+ }
+ return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]] ?? [];
+ }
+
+ /**
+ * Get token mappings for related entities - specifically the contact entity.
+ *
+ * This function exists to help manage the way contact tokens is structured
+ * of an query-object style result set that needs to be mapped to apiv4.
+ *
+ * The end goal is likely to be to advertised tokens that better map to api
+ * v4 and deprecate the existing ones but that is a long-term migration.
+ *
+ * @return array
+ */
+ protected function getTokenMappingsForRelatedEntities(): array {
+ return [];
}
/**
/**
* Add the token to the metadata based on the field spec.
*
+ * @param array $tokensMetadata
* @param array $field
* @param array $exposedFields
* @param string $prefix
*/
- protected function addFieldToTokenMetadata(array $field, array $exposedFields, $prefix = ''): void {
+ protected function addFieldToTokenMetadata(array &$tokensMetadata, array $field, array $exposedFields, string $prefix = ''): void {
+ if ($field['type'] !== 'Custom' && !in_array($field['name'], $exposedFields, TRUE)) {
+ return;
+ }
$field['audience'] = 'user';
if ($field['name'] === 'contact_id') {
// Since {contact.id} is almost always present don't confuse users
$parts = explode(': ', $field['label']);
$field['title'] = "{$parts[1]} :: {$parts[0]}";
$tokenName = 'custom_' . $field['custom_field_id'];
- $this->tokensMetadata[$tokenName] = $field;
+ $tokensMetadata[$tokenName] = $field;
return;
}
$tokenName = $prefix ? ($prefix . '.' . $field['name']) : $field['name'];
// At the time of writing currency didn't have a label option - this may have changed.
&& !in_array($field['name'], $this->getCurrencyFieldName(), TRUE)
) {
- $this->tokensMetadata[$tokenName . ':label'] = $this->tokensMetadata[$field['name'] . ':name'] = $field;
+ $tokensMetadata[$tokenName . ':label'] = $tokensMetadata[$tokenName . ':name'] = $field;
$fieldLabel = $field['input_attrs']['label'] ?? $field['label'];
- $this->tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
- $this->tokensMetadata[$tokenName . ':name']['name'] = $field['name'] . ':name';
- $this->tokensMetadata[$tokenName . ':name']['audience'] = 'sysadmin';
- $this->tokensMetadata[$tokenName . ':label']['title'] = $fieldLabel;
- $this->tokensMetadata[$tokenName . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel;
+ $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
+ $tokensMetadata[$tokenName . ':name']['name'] = $field['name'] . ':name';
+ $tokensMetadata[$tokenName . ':name']['audience'] = 'sysadmin';
+ $tokensMetadata[$tokenName . ':label']['title'] = $fieldLabel;
+ $tokensMetadata[$tokenName . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel;
$field['audience'] = 'sysadmin';
}
if ($field['data_type'] === 'Boolean') {
- $this->tokensMetadata[$tokenName . ':label'] = $field;
- $this->tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
+ $tokensMetadata[$tokenName . ':label'] = $field;
+ $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
$field['audience'] = 'sysadmin';
}
- $this->tokensMetadata[$tokenName] = $field;
+ $tokensMetadata[$tokenName] = $field;
}
}