(REF) CryptoToken - Allow optional injection of $registry
authorTim Otten <totten@civicrm.org>
Fri, 8 Jan 2021 08:10:17 +0000 (00:10 -0800)
committerTim Otten <totten@civicrm.org>
Fri, 8 Jan 2021 08:10:53 +0000 (00:10 -0800)
Civi/Crypto/CryptoToken.php

index 9ee7375ac6950c9e0cf7e803ee246d24e5ef74cf..316159a3e495beff23e4851fc0fda1b0b4ac8cc3 100644 (file)
@@ -55,11 +55,19 @@ class CryptoToken {
    */
   protected $delim;
 
+  /**
+   * @var \Civi\Crypto\CryptoRegistry|null
+   */
+  private $registry;
+
   /**
    * CryptoToken constructor.
+   *
+   * @param CryptoRegistry $registry
    */
-  public function __construct() {
+  public function __construct($registry = NULL) {
     $this->delim = chr(2);
+    $this->registry = $registry;
   }
 
   /**
@@ -85,7 +93,7 @@ class CryptoToken {
    */
   public function encrypt($plainText, $keyIdOrTag) {
     /** @var CryptoRegistry $registry */
-    $registry = \Civi::service('crypto.registry');
+    $registry = $this->getRegistry();
 
     $key = $registry->findKey($keyIdOrTag);
     if ($key['suite'] === 'plain') {
@@ -128,7 +136,7 @@ class CryptoToken {
     }
 
     /** @var CryptoRegistry $registry */
-    $registry = \Civi::service('crypto.registry');
+    $registry = $this->getRegistry();
 
     $tokenData = $this->parse($token);
 
@@ -156,7 +164,7 @@ class CryptoToken {
    */
   public function rekey($oldToken, $keyTag) {
     /** @var \Civi\Crypto\CryptoRegistry $registry */
-    $registry = \Civi::service('crypto.registry');
+    $registry = $this->getRegistry();
 
     $sourceKeys = $registry->findKeysByTag($keyTag);
     $targetKey = array_shift($sourceKeys);
@@ -200,4 +208,14 @@ class CryptoToken {
     return $tokenData;
   }
 
+  /**
+   * @return CryptoRegistry
+   */
+  protected function getRegistry(): CryptoRegistry {
+    if ($this->registry === NULL) {
+      $this->registry = \Civi::service('crypto.registry');
+    }
+    return $this->registry;
+  }
+
 }