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 $helpers = array();
var $helpers = array('Html');
/**
* HTML tags used by this helper.
*
@ -105,13 +105,6 @@ class JsHelper extends AppHelper {
* @access private
**/
var $__engineName;
/**
* Scripts that have already been included once, prevents duplicate script insertion
*
* @var array
* @access private
**/
var $__includedScripts = array();
/**
* __objects
*
@ -144,7 +137,7 @@ class JsHelper extends AppHelper {
}
$this->__engineName = $className . 'Engine';
$engineClass = $engineName . 'Engine';
$this->helpers = array($engineClass);
$this->helpers[] = $engineClass;
parent::__construct();
}
/**
@ -165,80 +158,40 @@ class JsHelper extends AppHelper {
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
* application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
* Options
*
* Can include one or many Javascript files. If there are .min.js or .pack.js files
* and your debug level == 0 these files will be used instead of the non min/pack files.
* - 'inline' - Set to true to have scripts output as a script block inline
* 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 boolean $inline Whether script should be output inline or into scripts_for_layout.
* @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
* @param array $options options for the code block
* @return string completed javascript tag.
**/
function uses($url, $inline = true, $once = true) {
if (is_array($url)) {
$out = '';
foreach ($url as $i) {
$out .= "\n\t" . $this->uses($i, $inline);
}
if ($inline) {
return $out . "\n";
}
return;
function writeScripts($options = array()) {
$defaults = array('onDomReady' => true, 'inline' => true, 'cache' => true, 'clear' => true, 'safe' => true);
$options = array_merge($defaults, $options);
$script = implode("\n", $this->{$this->__engineName}->getCache($options['clear']));
if ($options['onDomReady']) {
$script = $this->{$this->__engineName}->domReady($script);
}
if ($once && isset($this->__includedScripts[$url])) {
return null;
if (!$options['cache'] && $options['inline']) {
return $this->Html->scriptBlock($script, $options);
}
$this->__includedScripts[$url] = true;
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);
if ($options['cache'] && $options['inline']) {
//cache to file and return script tag.
}
$view =& ClassRegistry::getObject('view');
$view->addScript($script);
return null;
}
/**
* Loads a remote URL
*
@ -246,7 +199,7 @@ class JsHelper extends AppHelper {
* @param array $options
* @return string
**/
function load_($url = null, $options = array()) {
/* function load_($url = null, $options = array()) {
if (isset($options['update'])) {
if (!is_array($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');
}
*/
function select($pattern) {
return $this->__object($pattern, 'pattern');
}
@ -304,7 +258,7 @@ class JsHelper extends AppHelper {
}
return $this->__objects[$name];
}
*/
}
/**
@ -322,6 +276,19 @@ class JsBaseEngineHelper extends AppHelper {
* @access public
**/
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.
*
@ -495,6 +462,66 @@ class JsBaseEngineHelper extends AppHelper {
$escape = array("\r\n" => '\n', "\r" => '\n', "\n" => '\n', '"' => '\"', "'" => "\\'");
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.
* Similar to object() but treats any non-integer value as a string,
@ -512,7 +539,7 @@ class JsBaseEngineHelper extends AppHelper {
}
$out[] = $key . ':' . $val;
}
return join(', ', $out);;
return join(', ', $out);
}
}

View file

@ -24,11 +24,11 @@
* @lastmodified $Date$
* @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'));
Mock::generate('Helper', 'TestJsEngineHelper', array('methodOne'));
Mock::generate('View', 'JsHelperView');
Mock::generate('JsBaseEngineHelper', 'TestJsEngineHelper', array('methodOne'));
Mock::generate('View', 'JsHelperMockView');
/**
* JsHelper TestCase.
@ -37,6 +37,18 @@ Mock::generate('View', 'JsHelperView');
* @subpackage cake.tests.cases.libs.view.helpers
*/
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
*
@ -44,8 +56,12 @@ class JsHelperTestCase extends CakeTestCase {
* @return void
*/
function startTest() {
$this->Js = new JsHelper('JsBase');
$this->Js->JsBaseEngine = new JsBaseEngineHelper();
$this->Js =& new JsHelper('JsBase');
$this->Js->Html =& new HtmlHelper();
$this->Js->JsBaseEngine =& new JsBaseEngineHelper();
$view =& new JsHelperMockView();
ClassRegistry::addObject('view', $view);
}
/**
* tearDown method
@ -64,16 +80,16 @@ class JsHelperTestCase extends CakeTestCase {
**/
function testConstruction() {
$js = new JsHelper();
$this->assertEqual($js->helpers, array('jqueryEngine'));
$this->assertEqual($js->helpers, array('Html', 'jqueryEngine'));
$js = new JsHelper(array('mootools'));
$this->assertEqual($js->helpers, array('mootoolsEngine'));
$this->assertEqual($js->helpers, array('Html', 'mootoolsEngine'));
$js = new JsHelper('prototype');
$this->assertEqual($js->helpers, array('prototypeEngine'));
$this->assertEqual($js->helpers, array('Html', 'prototypeEngine'));
$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
@ -92,127 +108,33 @@ class JsHelperTestCase extends CakeTestCase {
$js->someMethodThatSurelyDoesntExist();
}
/**
* test script tag generation
* test that writeScripts generates scripts inline.
*
* @return void
**/
function testUses() {
$result = $this->Js->uses('foo');
function testWriteScriptsNoFile() {
$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(
'script' => array('type' => 'text/javascript', 'src' => 'js/foo.js')
);
$this->assertTags($result, $expected);
$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' => array('type' => 'text/javascript'),
$this->cDataStart,
"one = 1;\ntwo = 2;",
$this->cDataEnd,
'/script',
);
$this->assertTags($result, $expected);
$this->assertTags($result, $expected, true);
$result = $this->Js->uses('jquery-1.3');
$expected = array(
'script' => array('type' => 'text/javascript', 'src' => 'js/jquery-1.3.js')
);
$this->assertTags($result, $expected);
$this->Js->JsBaseEngine->expectAtLeastOnce('domReady');
$result = $this->Js->writeScripts(array('onDomReady' => true, 'cache' => false));
$result = $this->Js->uses('/plugin/js/jquery-1.3.2');
$expected = array(
'script' => array('type' => 'text/javascript', 'src' => '/plugin/js/jquery-1.3.2.js')
);
$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);
$view =& new JsHelperMockView();
$view->expectAt(0, 'addScript', array(new PatternExpectation('/one\s=\s1;\ntwo\=\2;/')));
$result = $this->Js->writeScripts(array('onDomReady' => false, 'inline' => false, 'cache' => false));
}
}
/**
* JsBaseEngine Class Test case
*
@ -311,7 +233,7 @@ class JsBaseEngineTestCase extends CakeTestCase {
$this->assertEqual($result, $expected);
}
/**
* test Redirect
* test Redirect
*
* @return void
**/