From 1c4a04c963ecdff97daa6cf7cefe0e7da350bcb3 Mon Sep 17 00:00:00 2001 From: Aidan Saunders Date: Thu, 26 Apr 2018 16:00:45 +0100 Subject: [PATCH] Add listTokens() function to return formatted list of tokens for forms --- Civi/Token/TokenProcessor.php | 23 +++++++++++++++++++ .../phpunit/Civi/Token/TokenProcessorTest.php | 8 +++++++ 2 files changed, 31 insertions(+) diff --git a/Civi/Token/TokenProcessor.php b/Civi/Token/TokenProcessor.php index bfad77926c..4cafeb251e 100644 --- a/Civi/Token/TokenProcessor.php +++ b/Civi/Token/TokenProcessor.php @@ -68,6 +68,13 @@ class TokenProcessor { */ protected $tokens = NULL; + /** + * A list of available tokens formatted for display + * @var array + * Array('{' . $dottedName . '}' => 'labelString') + */ + protected $listTokens = NULL; + protected $next = 0; /** @@ -220,6 +227,22 @@ class TokenProcessor { return $this->tokens; } + /** + * Get the list of available tokens, formatted for display + * + * @return array + * Ex: $tokens[ '{token.name}' ] = "Token label" + */ + public function listTokens() { + if ($this->listTokens === NULL) { + $this->listTokens = array(); + foreach ($this->getTokens() as $token => $values) { + $this->listTokens['{' . $token . '}'] = $values['label']; + } + } + return $this->listTokens; + } + /** * Compute and store token values. */ diff --git a/tests/phpunit/Civi/Token/TokenProcessorTest.php b/tests/phpunit/Civi/Token/TokenProcessorTest.php index aadb596f4d..38d02d44c1 100644 --- a/tests/phpunit/Civi/Token/TokenProcessorTest.php +++ b/tests/phpunit/Civi/Token/TokenProcessorTest.php @@ -113,6 +113,14 @@ class TokenProcessorTest extends \CiviUnitTestCase { $this->assertEquals($expected, $p->getMessageTokens()); } + public function testListTokens() { + $p = new TokenProcessor($this->dispatcher, array( + 'controller' => __CLASS__, + )); + $p->addToken(array('entity' => 'MyEntity', 'field' => 'myField', 'label' => 'My Label')); + $this->assertEquals(array('{MyEntity.myField}' => 'My Label'), $p->listTokens()); + } + /** * Perform a full mail-merge, substituting multiple tokens for multiple * contacts in multiple messages. -- 2.25.1