Adding methods to baseEngine

Removing file inclusion from JsHelper
Adding writeCache to JsHelper
Adding tests.
This commit is contained in:
mark_story 2009-03-12 23:48:19 -04:00
parent 91e47a6379
commit a1a54a152b
2 changed files with 151 additions and 202 deletions

View file

@ -85,7 +85,7 @@ class JsHelper extends AppHelper {
* *
* @var array * @var array
**/ **/
var $helpers = array(); var $helpers = array('Html');
/** /**
* HTML tags used by this helper. * HTML tags used by this helper.
* *
@ -105,13 +105,6 @@ class JsHelper extends AppHelper {
* @access private * @access private
**/ **/
var $__engineName; var $__engineName;
/**
* Scripts that have already been included once, prevents duplicate script insertion
*
* @var array
* @access private
**/
var $__includedScripts = array();
/** /**
* __objects * __objects
* *
@ -144,7 +137,7 @@ class JsHelper extends AppHelper {
} }
$this->__engineName = $className . 'Engine'; $this->__engineName = $className . 'Engine';
$engineClass = $engineName . 'Engine'; $engineClass = $engineName . 'Engine';
$this->helpers = array($engineClass); $this->helpers[] = $engineClass;
parent::__construct(); parent::__construct();
} }
/** /**
@ -165,80 +158,40 @@ class JsHelper extends AppHelper {
trigger_error(sprintf(__('JsHelper:: Missing Method %s is undefined', true), $method), E_USER_WARNING); trigger_error(sprintf(__('JsHelper:: Missing Method %s is undefined', true), $method), E_USER_WARNING);
} }
/** /**
* Returns one or many <script> tags depending on the number of scripts given. * Writes all Javascript generated so far to a code block or
* caches them to a file and returns a linked script.
* *
* If the filename is prefixed with "/", the path will be relative to the base path of your * Options
* application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
* *
* Can include one or many Javascript files. If there are .min.js or .pack.js files * - 'inline' - Set to true to have scripts output as a script block inline
* and your debug level == 0 these files will be used instead of the non min/pack files. * if 'cache' is also true, a script link tag will be generated. (default true)
* - 'cache' - Set to true to have scripts cached to a file and linked in (default true)
* - 'clear' - Set to false to prevent script cache from being cleared (default true)
* - 'onDomReady' - wrap cached scripts in domready event (default true)
* - 'safe' - if an inline block is generated should it be wrapped in <![CDATA[ ... ]]> (default true)
* *
* @param mixed $url String or array of javascript files to include * @param array $options options for the code block
* @param boolean $inline Whether script should be output inline or into scripts_for_layout. * @return string completed javascript tag.
* @param boolean $once Whether or not the script should be checked for uniqueness. If true scripts will only be
* included once, use false to allow the same script to be included more than once per request.
* @return mixed
**/ **/
function uses($url, $inline = true, $once = true) { function writeScripts($options = array()) {
if (is_array($url)) { $defaults = array('onDomReady' => true, 'inline' => true, 'cache' => true, 'clear' => true, 'safe' => true);
$out = ''; $options = array_merge($defaults, $options);
foreach ($url as $i) { $script = implode("\n", $this->{$this->__engineName}->getCache($options['clear']));
$out .= "\n\t" . $this->uses($i, $inline);
} if ($options['onDomReady']) {
if ($inline) { $script = $this->{$this->__engineName}->domReady($script);
return $out . "\n";
}
return;
} }
if (!$options['cache'] && $options['inline']) {
if ($once && isset($this->__includedScripts[$url])) { return $this->Html->scriptBlock($script, $options);
return null;
} }
$this->__includedScripts[$url] = true; if ($options['cache'] && $options['inline']) {
//cache to file and return script tag.
if (strpos($url, '://') === false) {
if ($url[0] !== '/') {
$url = JS_URL . $url;
}
$url = $this->webroot($url);
if (strpos($url, '?') === false) {
if (Configure::read('debug') == 0) {
$suffixes = array('.min.js', '.pack.js');
foreach ($suffixes as $suffix) {
if (file_exists(WWW_ROOT . $url . $suffix)) {
$url .= $suffix;
break;
}
}
}
if (strpos($url, '.js') === false) {
$url .= '.js';
}
}
$timestampEnabled = (
(Configure::read('Asset.timestamp') === true && Configure::read() > 0) ||
Configure::read('Asset.timestamp') === 'force'
);
if (strpos($url, '?') === false && $timestampEnabled) {
$url .= '?' . @filemtime(WWW_ROOT . str_replace('/', DS, $url));
}
if (Configure::read('Asset.filter.js')) {
$url = str_replace(JS_URL, 'cjs/', $url);
}
}
$out = $this->output(sprintf($this->tags['javascriptlink'], $url));
if ($inline) {
return $out;
} else {
$view =& ClassRegistry::getObject('view');
$view->addScript($out);
} }
$view =& ClassRegistry::getObject('view');
$view->addScript($script);
return null;
} }
/** /**
* Loads a remote URL * Loads a remote URL
* *
@ -246,7 +199,7 @@ class JsHelper extends AppHelper {
* @param array $options * @param array $options
* @return string * @return string
**/ **/
function load_($url = null, $options = array()) { /* function load_($url = null, $options = array()) {
if (isset($options['update'])) { if (isset($options['update'])) {
if (!is_array($options['update'])) { if (!is_array($options['update'])) {
$func = "new Ajax.Updater('{$options['update']}',"; $func = "new Ajax.Updater('{$options['update']}',";
@ -285,10 +238,11 @@ class JsHelper extends AppHelper {
} }
/* function get__($name) { /*
function get__($name) {
return $this->__object($name, 'id'); return $this->__object($name, 'id');
} }
*/
function select($pattern) { function select($pattern) {
return $this->__object($pattern, 'pattern'); return $this->__object($pattern, 'pattern');
} }
@ -304,7 +258,7 @@ class JsHelper extends AppHelper {
} }
return $this->__objects[$name]; return $this->__objects[$name];
} }
*/
} }
/** /**
@ -322,6 +276,19 @@ class JsBaseEngineHelper extends AppHelper {
* @access public * @access public
**/ **/
var $useNative = false; var $useNative = false;
/**
* The js snippet for the current selection.
*
* @var string
* @access protected
**/
var $_selection;
/**
* Scripts that are queued for output
*
* @var array
**/
var $__cachedScripts = array();
/** /**
* Constructor. * Constructor.
* *
@ -495,6 +462,66 @@ class JsBaseEngineHelper extends AppHelper {
$escape = array("\r\n" => '\n', "\r" => '\n', "\n" => '\n', '"' => '\"', "'" => "\\'"); $escape = array("\r\n" => '\n', "\r" => '\n', "\n" => '\n', '"' => '\"', "'" => "\\'");
return str_replace(array_keys($escape), array_values($escape), $string); return str_replace(array_keys($escape), array_values($escape), $string);
} }
/**
* Write a script to the cached scripts.
*
* @return void
**/
function writeCache($script) {
$this->__cachedScripts[] = $script;
}
/**
* Get all the cached scripts
*
* @param boolean $clear Whether or not to clear the script cache.s
* @return array Array of scripts added to the request.
**/
function getCache($clear = true) {
$scripts = $this->__cachedScripts;
if ($clear) {
$this->__cachedScripts = array();
}
return $scripts;
}
/**
* Create javascript selector for a CSS rule
*
* @param string $selector The selector that is targeted
* @param boolean $multiple Whether or not the selector could target more than one element.
* @return object instance of $this. Allows chained methods.
**/
function select($selector, $multiple = false) {
return $this;
}
/**
* Add an event to the script cache. Operates on the currently selected elements.
*
* @param string $type Type of event to bind to the current dom id
* @param string $callback The Javascript function you wish to trigger or the function literal
* @return string completed event handler
**/
function addEvent($type, $callback) {
}
/**
* Create a domReady event. This is a special event in many libraries
*
* @param string $functionBody The code to run on domReady
* @return string completed domReady method
**/
function domReady($functionBody) {
}
/**
* Create an iteration over the current selection result.
*
* @param string $method The method you want to apply to the selection
* @param string $callback The function body you wish to apply during the iteration.
* @return string completed iteration
**/
function each($method, $callback) {
}
/** /**
* Parse an options assoc array into an Javascript object literal. * Parse an options assoc array into an Javascript object literal.
* Similar to object() but treats any non-integer value as a string, * Similar to object() but treats any non-integer value as a string,
@ -512,7 +539,7 @@ class JsBaseEngineHelper extends AppHelper {
} }
$out[] = $key . ':' . $val; $out[] = $key . ':' . $val;
} }
return join(', ', $out);; return join(', ', $out);
} }
} }

View file

@ -24,11 +24,11 @@
* @lastmodified $Date$ * @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/ */
App::import('Helper', 'Js'); App::import('Helper', array('Js', 'Html'));
App::import('Core', array('View', 'ClassRegistry')); App::import('Core', array('View', 'ClassRegistry'));
Mock::generate('Helper', 'TestJsEngineHelper', array('methodOne')); Mock::generate('JsBaseEngineHelper', 'TestJsEngineHelper', array('methodOne'));
Mock::generate('View', 'JsHelperView'); Mock::generate('View', 'JsHelperMockView');
/** /**
* JsHelper TestCase. * JsHelper TestCase.
@ -37,6 +37,18 @@ Mock::generate('View', 'JsHelperView');
* @subpackage cake.tests.cases.libs.view.helpers * @subpackage cake.tests.cases.libs.view.helpers
*/ */
class JsHelperTestCase extends CakeTestCase { class JsHelperTestCase extends CakeTestCase {
/**
* Regexp for CDATA start block
*
* @var string
*/
var $cDataStart = 'preg:/^\/\/<!\[CDATA\[[\n\r]*/';
/**
* Regexp for CDATA end block
*
* @var string
*/
var $cDataEnd = 'preg:/[^\]]*\]\]\>[\s\r\n]*/';
/** /**
* setUp method * setUp method
* *
@ -44,8 +56,12 @@ class JsHelperTestCase extends CakeTestCase {
* @return void * @return void
*/ */
function startTest() { function startTest() {
$this->Js = new JsHelper('JsBase'); $this->Js =& new JsHelper('JsBase');
$this->Js->JsBaseEngine = new JsBaseEngineHelper(); $this->Js->Html =& new HtmlHelper();
$this->Js->JsBaseEngine =& new JsBaseEngineHelper();
$view =& new JsHelperMockView();
ClassRegistry::addObject('view', $view);
} }
/** /**
* tearDown method * tearDown method
@ -64,16 +80,16 @@ class JsHelperTestCase extends CakeTestCase {
**/ **/
function testConstruction() { function testConstruction() {
$js = new JsHelper(); $js = new JsHelper();
$this->assertEqual($js->helpers, array('jqueryEngine')); $this->assertEqual($js->helpers, array('Html', 'jqueryEngine'));
$js = new JsHelper(array('mootools')); $js = new JsHelper(array('mootools'));
$this->assertEqual($js->helpers, array('mootoolsEngine')); $this->assertEqual($js->helpers, array('Html', 'mootoolsEngine'));
$js = new JsHelper('prototype'); $js = new JsHelper('prototype');
$this->assertEqual($js->helpers, array('prototypeEngine')); $this->assertEqual($js->helpers, array('Html', 'prototypeEngine'));
$js = new JsHelper('MyPlugin.Dojo'); $js = new JsHelper('MyPlugin.Dojo');
$this->assertEqual($js->helpers, array('MyPlugin.DojoEngine')); $this->assertEqual($js->helpers, array('Html', 'MyPlugin.DojoEngine'));
} }
/** /**
* test that methods dispatch internally and to the engine class * test that methods dispatch internally and to the engine class
@ -92,127 +108,33 @@ class JsHelperTestCase extends CakeTestCase {
$js->someMethodThatSurelyDoesntExist(); $js->someMethodThatSurelyDoesntExist();
} }
/** /**
* test script tag generation * test that writeScripts generates scripts inline.
* *
* @return void * @return void
**/ **/
function testUses() { function testWriteScriptsNoFile() {
$result = $this->Js->uses('foo'); $this->Js->JsBaseEngine = new TestJsEngineHelper();
$this->Js->JsBaseEngine->setReturnValue('getCache', array('one = 1;', 'two = 2;'));
$result = $this->Js->writeScripts(array('onDomReady' => false, 'cache' => false));
$expected = array( $expected = array(
'script' => array('type' => 'text/javascript', 'src' => 'js/foo.js') 'script' => array('type' => 'text/javascript'),
); $this->cDataStart,
$this->assertTags($result, $expected); "one = 1;\ntwo = 2;",
$this->cDataEnd,
$result = $this->Js->uses(array('foobar', 'bar'));
$expected = array(
array('script' => array('type' => 'text/javascript', 'src' => 'js/foobar.js')),
'/script',
array('script' => array('type' => 'text/javascript', 'src' => 'js/bar.js')),
'/script', '/script',
); );
$this->assertTags($result, $expected); $this->assertTags($result, $expected, true);
$result = $this->Js->uses('jquery-1.3'); $this->Js->JsBaseEngine->expectAtLeastOnce('domReady');
$expected = array( $result = $this->Js->writeScripts(array('onDomReady' => true, 'cache' => false));
'script' => array('type' => 'text/javascript', 'src' => 'js/jquery-1.3.js')
);
$this->assertTags($result, $expected);
$result = $this->Js->uses('/plugin/js/jquery-1.3.2'); $view =& new JsHelperMockView();
$expected = array( $view->expectAt(0, 'addScript', array(new PatternExpectation('/one\s=\s1;\ntwo\=\2;/')));
'script' => array('type' => 'text/javascript', 'src' => '/plugin/js/jquery-1.3.2.js') $result = $this->Js->writeScripts(array('onDomReady' => false, 'inline' => false, 'cache' => false));
);
$this->assertTags($result, $expected);
$result = $this->Js->uses('scriptaculous.js?load=effects');
$expected = array(
'script' => array('type' => 'text/javascript', 'src' => 'js/scriptaculous.js?load=effects')
);
$this->assertTags($result, $expected);
$view = new JsHelperView();
ClassRegistry::addObject('view', $view);
$view->expectOnce('addScript');
$result = $this->Js->uses('test', false);
$this->assertNull($result);
}
/**
* test Min/pack version autofinding
*
* @return void
**/
function testMinPackAutoUse() {
if ($this->skipIf(!is_writable(JS), 'webroot/js is not Writable, min/pack js testing is skipped')) {
return;
}
Configure::write('debug', 0);
touch(WWW_ROOT . 'js' . DS. '__cake_js_min_test.min.js');
touch(WWW_ROOT . 'js' . DS. '__cake_js_pack_test.pack.js');
$result = $this->Js->uses('__cake_js_min_test');
$this->assertPattern('/__cake_js_min_test\.min\.js/', $result);
$result = $this->Js->uses('__cake_js_pack_test');
$this->assertPattern('/__cake_js_pack_test\.pack\.js/', $result);
Configure::write('debug', 2);
$result = $this->Js->uses('__cake_js_pack_test');
$this->assertNoPattern('/pack\.js/', $result);
unlink(WWW_ROOT . 'js' . DS. '__cake_js_min_test.min.js');
unlink(WWW_ROOT . 'js' . DS. '__cake_js_pack_test.pack.js');
}
/**
* test timestamp enforcement
*
* @return void
**/
function testAssetTimestamping() {
if ($this->skipIf(!is_writable(JS), 'webroot/js is not Writable, timestamp testing has been skipped')) {
return;
}
Configure::write('Asset.timestamp', true);
touch(WWW_ROOT . 'js' . DS. '__cake_js_test.js');
$timestamp = substr(strtotime('now'), 0, 8);
$result = $this->Js->uses('__cake_js_test', true, false);
$this->assertPattern('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s');
Configure::write('debug', 0);
$result = $this->Js->uses('__cake_js_test', true, false);
$this->assertPattern('/__cake_js_test.js"/', $result);
Configure::write('Asset.timestamp', 'force');
$result = $this->Js->uses('__cake_js_test', true, false);
$this->assertPattern('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s');
unlink(WWW_ROOT . 'js' . DS. '__cake_js_test.js');
Configure::write('debug', 2);
}
/**
* test that scripts added with uses() are only ever included once.
*
* @return void
**/
function testUniqueScriptInsertion() {
$result = $this->Js->uses('foo');
$this->assertNotNull($result);
$result = $this->Js->uses('foo');
$this->assertNull($result, 'Script returned upon duplicate inclusion %s');
$result = $this->Js->uses(array('foo', 'bar', 'baz'));
$this->assertNoPattern('/foo.js/', $result);
$result = $this->Js->uses('foo', true, false);
$this->assertNotNull($result);
} }
} }
/** /**
* JsBaseEngine Class Test case * JsBaseEngine Class Test case
* *
@ -311,7 +233,7 @@ class JsBaseEngineTestCase extends CakeTestCase {
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
} }
/** /**
* test Redirect * test Redirect
* *
* @return void * @return void
**/ **/