Fix hookTokens to be clearable outside the class
authorEileen McNaughton <emcnaughton@wikimedia.org>
Thu, 14 Oct 2021 08:21:04 +0000 (21:21 +1300)
committerEileen McNaughton <emcnaughton@wikimedia.org>
Thu, 14 Oct 2021 19:59:01 +0000 (08:59 +1300)
Tests can't unset the proerty in the class easily but just using the static makes it easier

CRM/Contact/Tokens.php
CRM/Utils/Hook/UnitTests.php

index 03c4d37db1088a3eebecc7ceb13c43296ef57af9..7df4720e9368443dcebc452104b9877bf85771c3 100644 (file)
@@ -32,13 +32,6 @@ class CRM_Contact_Tokens extends CRM_Core_EntityTokens {
     return 'Contact';
   }
 
-  /**
-   * Tokens defined by the legacy hook.
-   *
-   * @var array
-   */
-  protected $hookTokens;
-
   /**
    * @inheritDoc
    */
@@ -249,7 +242,7 @@ class CRM_Contact_Tokens extends CRM_Core_EntityTokens {
    */
   public function evaluateLegacyHookTokens(TokenValueEvent $e): void {
     $messageTokens = $e->getTokenProcessor()->getMessageTokens();
-    if (!array_intersect(array_keys($this->getHookTokens()), array_keys($messageTokens))) {
+    if (empty($messageTokens) || !array_intersect(array_keys($this->getHookTokens()), array_keys($messageTokens))) {
       return;
     }
 
@@ -694,17 +687,13 @@ class CRM_Contact_Tokens extends CRM_Core_EntityTokens {
    * @return array
    */
   protected function getHookTokens(): array {
-    if ($this->hookTokens === NULL) {
-      if (isset(Civi::$statics[__CLASS__]['hook_tokens'])) {
-        $this->hookTokens = Civi::$statics[__CLASS__]['hook_tokens'];
-      }
-      else {
-        $this->hookTokens = [];
-        \CRM_Utils_Hook::tokens($this->hookTokens);
-        Civi::$statics[__CLASS__]['hook_tokens'] = $this->hookTokens;
-      }
+    if (isset(Civi::$statics[__CLASS__]['hook_tokens'])) {
+      return Civi::$statics[__CLASS__]['hook_tokens'];
     }
-    return $this->hookTokens;
+    $tokens = [];
+    \CRM_Utils_Hook::tokens($tokens);
+    Civi::$statics[__CLASS__]['hook_tokens'] = $tokens;
+    return $tokens;
   }
 
 }
index 7b07c1b5ce466583a2407ade7ca824f688ca34bc..71babb86f88187b76881bd721e5d88b0a2040347 100644 (file)
@@ -55,6 +55,9 @@ class CRM_Utils_Hook_UnitTests extends CRM_Utils_Hook {
    */
   public function setHook(string $hook, $callable): void {
     $this->adhocHooks[$hook] = $callable;
+    if (strpos($hook, 'token') !== FALSE) {
+      unset(Civi::$statics['CRM_Contact_Tokens']['hook_tokens']);
+    }
   }
 
   /**