Add now token
authorEileen McNaughton <emcnaughton@wikimedia.org>
Sat, 18 Sep 2021 23:24:18 +0000 (11:24 +1200)
committerEileen McNaughton <emcnaughton@wikimedia.org>
Wed, 22 Sep 2021 00:32:35 +0000 (12:32 +1200)
CRM/Core/DomainTokens.php
Civi/Token/TokenProcessor.php
Civi/Token/TokenRow.php
tests/phpunit/CRM/Utils/TokenConsistencyTest.php

index 8aaafaff4ca5dc6b9fbbac597f57e19647ec08bb..a79368e301befe38e2a92ba6228508320d01270f 100644 (file)
@@ -47,6 +47,7 @@ class CRM_Core_DomainTokens extends AbstractTokenSubscriber {
       'email' => ts('Domain (organization) email'),
       'id' => ts('Domain ID'),
       'description' => ts('Domain Description'),
+      'now' => ts('Current time/date'),
     ];
   }
 
@@ -55,6 +56,10 @@ class CRM_Core_DomainTokens extends AbstractTokenSubscriber {
    * @throws \CRM_Core_Exception
    */
   public function evaluateToken(TokenRow $row, $entity, $field, $prefetch = NULL): void {
+    if ($field === 'now') {
+      $row->format('text/html')->tokens($entity, $field, new DateTime());
+      return;
+    }
     $row->format('text/html')->tokens($entity, $field, self::getDomainTokenValues()[$field]);
     $row->format('text/plain')->tokens($entity, $field, self::getDomainTokenValues(NULL, FALSE)[$field]);
   }
index 3bad2d891878c5bf08c94870906c4d27f8f7d2ba..2023a0dc172fe41190a54003167cfd57f74df416 100644 (file)
@@ -365,6 +365,11 @@ class TokenProcessor {
       [$full, $entity, $field] = $m;
       if (isset($tokens[$entity][$field])) {
         $v = $tokens[$entity][$field];
+        if ($v instanceof \DateTime) {
+          if (!isset($m[3])) {
+            $m[3] = 'crmDate';
+          }
+        }
         if (isset($m[3])) {
           $v = $this->filterTokenValue($v, $m[3], $row);
         }
@@ -384,7 +389,7 @@ class TokenProcessor {
     // Regex counter-examples: '{foobar}', '{foo bar}', '{$foo.bar}', '{$foo.bar|whiz}', '{foo.bar|whiz{bang}}'
     // Key observations: Civi tokens MUST have a `.` and MUST NOT have a `$`. Civi filters MUST NOT have `{}`s or `$`s.
     $tokRegex = '([\w]+)\.([\w:\.]+)';
-    $filterRegex = '(\w+)';
+    $filterRegex = '(\w+:?\w+)';
     $event->string = preg_replace_callback(";\{$tokRegex(?:\|$filterRegex)?\};", $getToken, $message['string']);
     $this->dispatcher->dispatch('civi.token.render', $event);
     return $event->string;
@@ -413,6 +418,13 @@ class TokenProcessor {
       case 'lower':
         return mb_strtolower($value);
 
+      case 'crmDate':
+        if ($value instanceof \DateTime) {
+          // @todo cludgey.
+          require_once 'CRM/Core/Smarty/plugins/modifier.crmDate.php';
+          return \smarty_modifier_crmDate($value->format('Y-m-d H:i:s'));
+        }
+
       default:
         throw new \CRM_Core_Exception("Invalid token filter: $filter");
     }
index fb1fda5c218276f353b03e45501fd29ac6d691ea..46aa8a889de8a1ee7fcc928287ecb3800849d1e5 100644 (file)
@@ -283,15 +283,18 @@ class TokenRow {
         // HTML => Plain.
         foreach ($htmlTokens as $entity => $values) {
           foreach ($values as $field => $value) {
+            if (!$value instanceof \DateTime) {
+              $value = html_entity_decode(strip_tags($value));
+            }
             if (!isset($textTokens[$entity][$field])) {
-              $textTokens[$entity][$field] = html_entity_decode(strip_tags($value));
+              $textTokens[$entity][$field] = $value;
             }
           }
         }
         break;
 
       default:
-        throw new \RuntimeException("Invalid format");
+        throw new \RuntimeException('Invalid format');
     }
 
     return $this;
index 0a0ab45571112070dcb4499b322d9d4dc7ef8009..34d5fea5febaa6f4cd9b917d0523ee8c096fd4bb 100644 (file)
@@ -509,9 +509,33 @@ December 21st, 2007
     ]);
     $tokens['{domain.id}'] = 'Domain ID';
     $tokens['{domain.description}'] = 'Domain Description';
+    $tokens['domain.now'] = 'Current time/date';
     $this->assertEquals($tokens, $tokenProcessor->listTokens());
   }
 
+  /**
+   * @throws \API_Exception
+   * @throws \CRM_Core_Exception
+   */
+  public function testDomainNow(): void {
+    putenv('TIME_FUNC=frozen');
+    CRM_Utils_Time::setTime('2021-21-18 11:58:00');
+    $resolved = CRM_Core_BAO_MessageTemplate::renderTemplate([
+      'messageTemplate' => [
+        'msg_text' => '{domain.now|crmDate:short}',
+      ],
+    ])['text'];
+    $this->assertEquals('September 18th, 2021 11:58 PM', $resolved);
+    $resolved = CRM_Core_BAO_MessageTemplate::renderTemplate([
+      'messageTemplate' => [
+        'msg_text' => '{domain.now}',
+      ],
+    ])['text'];
+    $this->assertEquals('September 18th, 2021 11:58 PM', $resolved);
+
+    $b1 = 1;
+  }
+
   /**
    * Get declared participant tokens.
    *
@@ -525,6 +549,7 @@ December 21st, 2007
       '{domain.email}' => 'Domain (organization) email',
       '{domain.id}' => ts('Domain ID'),
       '{domain.description}' => ts('Domain Description'),
+      '{domain.now}' => 'Current time/date',
     ];
   }