From 73bcd446c43d6cc753bf28e5c501575613038584 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Tue, 4 Nov 2014 11:09:05 -0500 Subject: [PATCH] Encourage better scoping of js CRM vars with new addVars method --- CRM/Core/Resources.php | 24 ++++++++++++++++++++---- tests/phpunit/CRM/Core/ResourcesTest.php | 11 +++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/CRM/Core/Resources.php b/CRM/Core/Resources.php index dd9fdf805d..d1426b1de2 100644 --- a/CRM/Core/Resources.php +++ b/CRM/Core/Resources.php @@ -210,16 +210,32 @@ class CRM_Core_Resources { } /** - * Add JavaScript variables to the global CRM object. + * Add JavaScript variables to CRM.vars * * Example: * From the server: - * CRM_Core_Resources::singleton()->addSetting(array('myNamespace' => array('foo' => 'bar'))); - * From javascript: - * CRM.myNamespace.foo // "bar" + * CRM_Core_Resources::singleton()->addVars('myNamespace', array('foo' => 'bar')); + * Access var from javascript: + * CRM.vars.myNamespace.foo // "bar" * * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Javascript+Reference * + * @param string $nameSpace - usually the name of your extension + * @param array $vars + * @return CRM_Core_Resources + */ + public function addVars($nameSpace, $vars) { + $existing = CRM_Utils_Array::value($nameSpace, CRM_Utils_Array::value('vars', $this->settings), array()); + $vars = $this->mergeSettings($existing, $vars); + $this->addSetting(array('vars' => array($nameSpace => $vars))); + return $this; + } + + /** + * Add JavaScript variables to the root of the CRM object. + * This function is usually reserved for low-level system use. + * Extensions and components should generally use addVars instead. + * * @param $settings array * @return CRM_Core_Resources */ diff --git a/tests/phpunit/CRM/Core/ResourcesTest.php b/tests/phpunit/CRM/Core/ResourcesTest.php index d95dbc79dc..f8782612f1 100644 --- a/tests/phpunit/CRM/Core/ResourcesTest.php +++ b/tests/phpunit/CRM/Core/ResourcesTest.php @@ -127,6 +127,17 @@ class CRM_Core_ResourcesTest extends CiviUnitTestCase { $this->assertEquals($expected, $actual); } + function testAddVars() { + $this->res + ->addVars('food', array('fruit' => array('mine' => 'apple', 'ours' => 'banana'))) + ->addVars('food', array('fruit' => array('mine' => 'new apple', 'yours' => 'orange'))) + ; + $this->assertTreeEquals( + array('vars' => array('food' => array('fruit' => array('yours' => 'orange', 'mine' => 'new apple', 'ours' => 'banana')))), + $this->res->getSettings() + ); + } + function testAddSetting() { $this->res ->addSetting(array('fruit' => array('mine' => 'apple'))) -- 2.25.1