Merge commit 'code/1.3' into 1.3-jshelper

Conflicts:
	cake/tests/cases/libs/view/helpers/html.test.php
	cake/tests/lib/header.php
This commit is contained in:
mark_story 2009-07-25 01:35:36 -04:00
commit 4ebf5a4e32
99 changed files with 30481 additions and 11188 deletions

View file

@ -86,7 +86,7 @@ if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR); trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
} }
$corePath = Configure::corePaths('cake'); $corePath = App::core('cake');
if (isset($corePath[0])) { if (isset($corePath[0])) {
define('TEST_CAKE_CORE_INCLUDE_PATH', rtrim($corePath[0], DS) . DS); define('TEST_CAKE_CORE_INCLUDE_PATH', rtrim($corePath[0], DS) . DS);
} else { } else {

View file

@ -362,8 +362,8 @@ if (!function_exists('array_combine')) {
*/ */
function env($key) { function env($key) {
if ($key == 'HTTPS') { if ($key == 'HTTPS') {
if (isset($_SERVER) && !empty($_SERVER)) { if (isset($_SERVER['HTTPS'])) {
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'); return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
} }
return (strpos(env('SCRIPT_URI'), 'https://') === 0); return (strpos(env('SCRIPT_URI'), 'https://') === 0);
} }
@ -624,9 +624,9 @@ if (!function_exists('file_put_contents')) {
} }
if ($return === false) { if ($return === false) {
echo I18n::translate($singular, $plural, null, 5, $count); echo I18n::translate($singular, $plural, null, 6, $count);
} else { } else {
return I18n::translate($singular, $plural, null, 5, $count); return I18n::translate($singular, $plural, null, 6, $count);
} }
} }
/** /**
@ -672,9 +672,9 @@ if (!function_exists('file_put_contents')) {
} }
if ($return === false) { if ($return === false) {
echo I18n::translate($singular, $plural, $domain, 5, $count); echo I18n::translate($singular, $plural, $domain, 6, $count);
} else { } else {
return I18n::translate($singular, $plural, $domain, 5, $count); return I18n::translate($singular, $plural, $domain, 6, $count);
} }
} }
/** /**
@ -723,13 +723,13 @@ if (!function_exists('file_put_contents')) {
* Valid categories are: LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL. * Valid categories are: LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.
* *
* Note that the category must be specified with a numeric value, instead of the constant name. The values are: * Note that the category must be specified with a numeric value, instead of the constant name. The values are:
* LC_CTYPE 0 * LC_ALL 0
* LC_NUMERIC 1 * LC_COLLATE 1
* LC_TIME 2 * LC_CTYPE 2
* LC_COLLATE 3 * LC_MONETARY 3
* LC_MONETARY 4 * LC_NUMERIC 4
* LC_MESSAGES 5 * LC_TIME 5
* LC_ALL 6 * LC_MESSAGES 6
* *
* @param string $domain Domain * @param string $domain Domain
* @param string $singular Singular string to translate * @param string $singular Singular string to translate

View file

@ -259,8 +259,8 @@ class ShellDispatcher {
Configure::getInstance(file_exists(CONFIGS . 'bootstrap.php')); Configure::getInstance(file_exists(CONFIGS . 'bootstrap.php'));
if (!file_exists(APP_PATH . 'config' . DS . 'core.php')) { if (!file_exists(APP_PATH . 'config' . DS . 'core.php')) {
include_once CORE_PATH . 'cake' . DS . 'console' . DS . 'templates' . DS . 'skel' . DS . 'config' . DS . 'core.php'; include_once CORE_PATH . 'cake' . DS . 'console' . DS . 'libs' . DS . 'templates' . DS . 'skel' . DS . 'config' . DS . 'core.php';
Configure::buildPaths(array()); App::build();
} }
Configure::write('debug', 1); Configure::write('debug', 1);

View file

@ -66,7 +66,7 @@ class ApiShell extends Shell {
return $this->help(); return $this->help();
} }
$type = low($this->args[0]); $type = strtolower($this->args[0]);
if (isset($this->paths[$type])) { if (isset($this->paths[$type])) {
$path = $this->paths[$type]; $path = $this->paths[$type];
@ -202,7 +202,7 @@ class ApiShell extends Shell {
if (strpos($method, '__') === false && $method[0] != '_') { if (strpos($method, '__') === false && $method[0] != '_') {
$parsed[$method] = array( $parsed[$method] = array(
'comment' => r(array('/*', '*/', '*'), '', trim($result[1][$key])), 'comment' => str_replace(array('/*', '*/', '*'), '', trim($result[1][$key])),
'method' => $method, 'method' => $method,
'parameters' => trim($result[3][$key]) 'parameters' => trim($result[3][$key])
); );

View file

@ -1,5 +1,4 @@
<?php <?php
/* SVN FILE: $Id$ */
/** /**
* Command-line code generation utility to automate programmer chores. * Command-line code generation utility to automate programmer chores.
* *
@ -21,9 +20,6 @@
* @package cake * @package cake
* @subpackage cake.cake.console.libs * @subpackage cake.cake.console.libs
* @since CakePHP(tm) v 1.2.0.5012 * @since CakePHP(tm) v 1.2.0.5012
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
/** /**
@ -40,7 +36,7 @@ class BakeShell extends Shell {
* @var array * @var array
* @access public * @access public
*/ */
var $tasks = array('Project', 'DbConfig', 'Model', 'Controller', 'View', 'Plugin', 'Test'); var $tasks = array('Project', 'DbConfig', 'Model', 'Controller', 'View', 'Plugin', 'Fixture', 'Test');
/** /**
* Override loadTasks() to handle paths * Override loadTasks() to handle paths
* *
@ -50,8 +46,16 @@ class BakeShell extends Shell {
parent::loadTasks(); parent::loadTasks();
$task = Inflector::classify($this->command); $task = Inflector::classify($this->command);
if (isset($this->{$task}) && !in_array($task, array('Project', 'DbConfig'))) { if (isset($this->{$task}) && !in_array($task, array('Project', 'DbConfig'))) {
$path = Inflector::underscore(Inflector::pluralize($this->command)); if (empty($this->{$task}->path)) {
$this->{$task}->path = $this->params['working'] . DS . $path . DS; $path = Inflector::underscore(Inflector::pluralize($this->command));
$this->{$task}->path = $this->params['working'] . DS . $path . DS;
}
if (isset($this->params['connection'])) {
$this->{$task}->connection = $this->params['connection'];
}
if (isset($this->params['plugin'])) {
$this->{$task}->plugin = $this->params['plugin'];
}
if (!is_dir($this->{$task}->path)) { if (!is_dir($this->{$task}->path)) {
$this->err(sprintf(__("%s directory could not be found.\nBe sure you have created %s", true), $task, $this->{$task}->path)); $this->err(sprintf(__("%s directory could not be found.\nBe sure you have created %s", true), $task, $this->{$task}->path));
$this->_stop(); $this->_stop();
@ -82,6 +86,7 @@ class BakeShell extends Shell {
$this->out('[V]iew'); $this->out('[V]iew');
$this->out('[C]ontroller'); $this->out('[C]ontroller');
$this->out('[P]roject'); $this->out('[P]roject');
$this->out('[F]ixture');
$this->out('[Q]uit'); $this->out('[Q]uit');
$classToBake = strtoupper($this->in(__('What would you like to Bake?', true), array('D', 'M', 'V', 'C', 'P', 'Q'))); $classToBake = strtoupper($this->in(__('What would you like to Bake?', true), array('D', 'M', 'V', 'C', 'P', 'Q')));
@ -101,6 +106,9 @@ class BakeShell extends Shell {
case 'P': case 'P':
$this->Project->execute(); $this->Project->execute();
break; break;
case 'F':
$this->Fixture->execute();
break;
case 'Q': case 'Q':
exit(0); exit(0);
break; break;
@ -116,22 +124,26 @@ class BakeShell extends Shell {
* @access public * @access public
*/ */
function all() { function all() {
$ds = 'default';
$this->hr(); $this->hr();
$this->out('Bake All'); $this->out('Bake All');
$this->hr(); $this->hr();
if (isset($this->params['connection'])) { if (!isset($this->params['connection']) && empty($this->connection)) {
$ds = $this->params['connection']; $this->connection = $this->DbConfig->getConfig();
} }
if (empty($this->args)) { if (empty($this->args)) {
$name = $this->Model->getName($ds); $this->Model->interactive = true;
$name = $this->Model->getName($this->connection);
}
foreach (array('Model', 'Controller', 'View') as $task) {
$this->{$task}->connection = $this->connection;
$this->{$task}->interactive = false;
} }
if (!empty($this->args[0])) { if (!empty($this->args[0])) {
$name = $this->args[0]; $name = $this->args[0];
$this->Model->listAll($ds, false);
} }
$modelExists = false; $modelExists = false;
@ -141,7 +153,7 @@ class BakeShell extends Shell {
$modelExists = true; $modelExists = true;
} else { } else {
App::import('Model'); App::import('Model');
$object = new Model(array('name' => $name, 'ds' => $ds)); $object = new Model(array('name' => $name, 'ds' => $this->connection));
} }
$modelBaked = $this->Model->bake($object, false); $modelBaked = $this->Model->bake($object, false);
@ -149,6 +161,7 @@ class BakeShell extends Shell {
if ($modelBaked && $modelExists === false) { if ($modelBaked && $modelExists === false) {
$this->out(sprintf(__('%s Model was baked.', true), $model)); $this->out(sprintf(__('%s Model was baked.', true), $model));
if ($this->_checkUnitTest()) { if ($this->_checkUnitTest()) {
$this->Model->bakeFixture($model);
$this->Model->bakeTest($model); $this->Model->bakeTest($model);
} }
$modelExists = true; $modelExists = true;
@ -165,16 +178,13 @@ class BakeShell extends Shell {
if (App::import('Controller', $controller)) { if (App::import('Controller', $controller)) {
$this->View->args = array($controller); $this->View->args = array($controller);
$this->View->execute(); $this->View->execute();
$this->out(sprintf(__('%s Views were baked.', true), $name));
} }
$this->out(__('Bake All complete')); $this->out(__('Bake All complete', true));
array_shift($this->args); array_shift($this->args);
} else { } else {
$this->err(__('Bake All could not continue without a valid model', true)); $this->err(__('Bake All could not continue without a valid model', true));
} }
if (empty($this->args)) {
$this->all();
}
$this->_stop(); $this->_stop();
} }

View file

@ -269,8 +269,7 @@ class ConsoleShell extends Shell {
if ($this->_isValidModel($modelToSave)) { if ($this->_isValidModel($modelToSave)) {
// Extract the array of data we are trying to build // Extract the array of data we are trying to build
list($foo, $data) = explode("->save", $command); list($foo, $data) = explode("->save", $command);
$badChars = array("(", ")"); $data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
$data = str_replace($badChars, "", $data);
$saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));"; $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
@eval($saveCommand); @eval($saveCommand);
$this->out('Saved record for ' . $modelToSave); $this->out('Saved record for ' . $modelToSave);
@ -358,4 +357,4 @@ class ConsoleShell extends Shell {
return true; return true;
} }
} }
?> ?>

View file

@ -199,7 +199,7 @@ class SchemaShell extends Shell {
} }
} }
$db =& ConnectionManager::getDataSource($this->Schema->connection); $db =& ConnectionManager::getDataSource($this->Schema->connection);
$contents = "#". $Schema->name ." sql generated on: " . date('Y-m-d H:m:s') . " : ". time()."\n\n"; $contents = "#". $Schema->name ." sql generated on: " . date('Y-m-d H:i:s') . " : ". time()."\n\n";
$contents .= $db->dropSchema($Schema) . "\n\n". $db->createSchema($Schema); $contents .= $db->dropSchema($Schema) . "\n\n". $db->createSchema($Schema);
if ($write) { if ($write) {
if (strpos($write, '.sql') === false) { if (strpos($write, '.sql') === false) {

View file

@ -149,10 +149,10 @@ class Shell extends Object {
ClassRegistry::map($this->name, $this->alias); ClassRegistry::map($this->name, $this->alias);
if (!PHP5 && isset($this->args[0])) { if (!PHP5 && isset($this->args[0])) {
if (strpos($this->name, low(Inflector::camelize($this->args[0]))) !== false) { if (strpos($this->name, strtolower(Inflector::camelize($this->args[0]))) !== false) {
$dispatch->shiftArgs(); $dispatch->shiftArgs();
} }
if (low($this->command) == low(Inflector::variable($this->args[0])) && method_exists($this, $this->command)) { if (strtolower($this->command) == strtolower(Inflector::variable($this->args[0])) && method_exists($this, $this->command)) {
$dispatch->shiftArgs(); $dispatch->shiftArgs();
} }
} }
@ -329,7 +329,7 @@ class Shell extends Object {
} }
} }
if (is_array($options)) { if (is_array($options)) {
while ($in == '' || ($in && (!in_array(low($in), $options) && !in_array(up($in), $options)) && !in_array($in, $options))) { while ($in == '' || ($in && (!in_array(strtolower($in), $options) && !in_array(strtoupper($in), $options)) && !in_array($in, $options))) {
$in = $this->Dispatch->getInput($prompt, $options, $default); $in = $this->Dispatch->getInput($prompt, $options, $default);
} }
} }
@ -427,10 +427,10 @@ class Shell extends Object {
$this->out("\n" . sprintf(__("Creating file %s", true), $path)); $this->out("\n" . sprintf(__("Creating file %s", true), $path));
if (is_file($path) && $this->interactive === true) { if (is_file($path) && $this->interactive === true) {
$key = $this->in(__("File exists, overwrite?", true). " {$path}", array('y', 'n', 'q'), 'n'); $key = $this->in(__("File exists, overwrite?", true). " {$path}", array('y', 'n', 'q'), 'n');
if (low($key) == 'q') { if (strtolower($key) == 'q') {
$this->out(__("Quitting.", true) ."\n"); $this->out(__("Quitting.", true) ."\n");
exit; exit;
} elseif (low($key) != 'y') { } elseif (strtolower($key) != 'y') {
$this->out(__("Skip", true) ." {$path}\n"); $this->out(__("Skip", true) ." {$path}\n");
return false; return false;
} }
@ -472,7 +472,7 @@ class Shell extends Object {
return true; return true;
} }
$unitTest = $this->in('SimpleTest is not installed. Do you want to bake unit test files anyway?', array('y','n'), 'y'); $unitTest = $this->in('SimpleTest is not installed. Do you want to bake unit test files anyway?', array('y','n'), 'y');
$result = low($unitTest) == 'y' || low($unitTest) == 'yes'; $result = strtolower($unitTest) == 'y' || strtolower($unitTest) == 'yes';
if ($result) { if ($result) {
$this->out("\nYou can download SimpleTest from http://simpletest.org", true); $this->out("\nYou can download SimpleTest from http://simpletest.org", true);
@ -488,37 +488,8 @@ class Shell extends Object {
*/ */
function shortPath($file) { function shortPath($file) {
$shortPath = str_replace(ROOT, null, $file); $shortPath = str_replace(ROOT, null, $file);
$shortPath = str_replace('..'.DS, '', $shortPath); $shortPath = str_replace('..' . DS, '', $shortPath);
return r(DS.DS, DS, $shortPath); return str_replace(DS . DS, DS, $shortPath);
}
/**
* Checks for Configure::read('Routing.admin') and forces user to input it if not enabled
*
* @return string Admin route to use
* @access public
*/
function getAdmin() {
$admin = '';
$cakeAdmin = null;
$adminRoute = Configure::read('Routing.admin');
if (!empty($adminRoute)) {
$cakeAdmin = $adminRoute . '_';
} else {
$this->out('You need to enable Configure::write(\'Routing.admin\',\'admin\') in /app/config/core.php to use admin routing.');
$this->out('What would you like the admin route to be?');
$this->out('Example: www.example.com/admin/controller');
while ($admin == '') {
$admin = $this->in("What would you like the admin route to be?", null, 'admin');
}
if ($this->Project->cakeAdmin($admin) !== true) {
$this->out('Unable to write to /app/config/core.php.');
$this->out('You need to enable Configure::write(\'Routing.admin\',\'admin\') in /app/config/core.php to use admin routing.');
$this->_stop();
} else {
$cakeAdmin = $admin . '_';
}
}
return $cakeAdmin;
} }
/** /**
* Creates the proper controller path for the specified controller class name * Creates the proper controller path for the specified controller class name
@ -528,7 +499,7 @@ class Shell extends Object {
* @access protected * @access protected
*/ */
function _controllerPath($name) { function _controllerPath($name) {
return low(Inflector::underscore($name)); return strtolower(Inflector::underscore($name));
} }
/** /**
* Creates the proper controller plural name for the specified controller class name * Creates the proper controller plural name for the specified controller class name
@ -611,5 +582,21 @@ class Shell extends Object {
function _pluralHumanName($name) { function _pluralHumanName($name) {
return Inflector::humanize(Inflector::underscore(Inflector::pluralize($name))); return Inflector::humanize(Inflector::underscore(Inflector::pluralize($name)));
} }
/**
* Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
*
* @param string $pluginName Name of the plugin you want ie. DebugKit
* @return string $path path to the correct plugin.
**/
function _pluginPath($pluginName) {
$pluginPaths = App::path('plugins');
$pluginDirName = Inflector::underscore($pluginName);
foreach ($pluginPaths as $path) {
if (is_dir($path . $pluginDirName)) {
return $path . $pluginDirName . DS ;
}
}
return $pluginPaths[0] . $pluginDirName . DS;
}
} }
?> ?>

View file

@ -1,5 +1,4 @@
<?php <?php
/* SVN FILE: $Id$ */
/** /**
* The ControllerTask handles creating and updating controller files. * The ControllerTask handles creating and updating controller files.
* *
@ -8,20 +7,17 @@
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. * Copyright 2005-2009, Cake Software Foundation, Inc.
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake * @package cake
* @subpackage cake.cake.console.libs.tasks * @subpackage cake.cake.console.libs.tasks
* @since CakePHP(tm) v 1.2 * @since CakePHP(tm) v 1.2
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
/** /**
@ -44,7 +40,7 @@ class ControllerTask extends Shell {
* @var array * @var array
* @access public * @access public
*/ */
var $tasks = array('Project'); var $tasks = array('Model', 'Test', 'Template', 'DbConfig', 'Project');
/** /**
* path to CONTROLLERS directory * path to CONTROLLERS directory
* *
@ -70,16 +66,22 @@ class ControllerTask extends Shell {
} }
if (isset($this->args[0])) { if (isset($this->args[0])) {
if (!isset($this->connection)) {
$this->connection = 'default';
}
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
$controller = Inflector::camelize($this->args[0]); $controller = Inflector::camelize($this->args[0]);
$actions = null; $actions = null;
if (isset($this->args[1]) && $this->args[1] == 'scaffold') { if (isset($this->args[1]) && $this->args[1] == 'scaffold') {
$this->out('Baking scaffold for ' . $controller); $this->out(__('Baking scaffold for ', true) . $controller);
$actions = $this->bakeActions($controller); $actions = $this->bakeActions($controller);
} else { } else {
$actions = 'scaffold'; $actions = 'scaffold';
} }
if ((isset($this->args[1]) && $this->args[1] == 'admin') || (isset($this->args[2]) && $this->args[2] == 'admin')) { if ((isset($this->args[1]) && $this->args[1] == 'admin') || (isset($this->args[2]) && $this->args[2] == 'admin')) {
if ($admin = $this->getAdmin()) { if ($admin = $this->Project->getAdmin()) {
$this->out('Adding ' . Configure::read('Routing.admin') .' methods'); $this->out('Adding ' . Configure::read('Routing.admin') .' methods');
if ($actions == 'scaffold') { if ($actions == 'scaffold') {
$actions = $this->bakeActions($controller, $admin); $actions = $this->bakeActions($controller, $admin);
@ -95,144 +97,164 @@ class ControllerTask extends Shell {
} }
} }
} }
/**
* Bake All the controllers at once. Will only bake controllers for models that exist.
*
* @access public
* @return void
**/
function all() {
$this->interactive = false;
$this->listAll($this->connection, false);
ClassRegistry::config('Model', array('ds' => $this->connection));
$unitTestExists = $this->_checkUnitTest();
foreach ($this->__tables as $table) {
$model = $this->_modelName($table);
$controller = $this->_controllerName($model);
if (App::import('Model', $model)) {
$actions = $this->bakeActions($controller);
if ($this->bake($controller, $actions) && $unitTestExists) {
$this->bakeTest($controller);
}
}
}
}
/** /**
* Interactive * Interactive
* *
* @access private * @access private
*/ */
function __interactive($controllerName = false) { function __interactive() {
if (!$controllerName) { $this->interactive = true;
$this->interactive = true;
$this->hr();
$this->out(sprintf("Bake Controller\nPath: %s", $this->path));
$this->hr();
$actions = '';
$uses = array();
$helpers = array();
$components = array();
$wannaUseSession = 'y';
$wannaDoAdmin = 'n';
$wannaUseScaffold = 'n';
$wannaDoScaffolding = 'y';
$controllerName = $this->getName();
}
$this->hr(); $this->hr();
$this->out("Baking {$controllerName}Controller"); $this->out(sprintf(__("Bake Controller\nPath: %s", true), $this->path));
$this->hr(); $this->hr();
$controllerFile = low(Inflector::underscore($controllerName)); if (empty($this->connection)) {
$this->connection = $this->DbConfig->getConfig();
}
$controllerName = $this->getName();
$this->hr();
$this->out(sprintf(__('Baking %sController', true), $controllerName));
$this->hr();
$helpers = $components = array();
$actions = '';
$wannaUseSession = 'y';
$wannaBakeAdminCrud = 'n';
$useDynamicScaffold = 'n';
$wannaBakeCrud = 'y';
$controllerFile = strtolower(Inflector::underscore($controllerName));
$question[] = __("Would you like to build your controller interactively?", true); $question[] = __("Would you like to build your controller interactively?", true);
if (file_exists($this->path . $controllerFile .'_controller.php')) { if (file_exists($this->path . $controllerFile .'_controller.php')) {
$question[] = sprintf(__("Warning: Choosing no will overwrite the %sController.", true), $controllerName); $question[] = sprintf(__("Warning: Choosing no will overwrite the %sController.", true), $controllerName);
} }
$doItInteractive = $this->in(join("\n", $question), array('y','n'), 'y'); $doItInteractive = $this->in(join("\n", $question), array('y', 'n'), 'y');
if (low($doItInteractive) == 'y' || low($doItInteractive) == 'yes') { if (strtolower($doItInteractive) == 'y') {
$this->interactive = true; $this->interactive = true;
$useDynamicScaffold = $this->in(
__("Would you like to use dynamic scaffolding?", true), array('y','n'), 'n'
);
$wannaUseScaffold = $this->in(__("Would you like to use scaffolding?", true), array('y','n'), 'n'); if (strtolower($useDynamicScaffold) == 'y') {
$wannaBakeCrud = 'n';
if (low($wannaUseScaffold) == 'n' || low($wannaUseScaffold) == 'no') { $actions = 'scaffold';
$wannaDoScaffolding = $this->in(__("Would you like to include some basic class methods (index(), add(), view(), edit())?", true), array('y','n'), 'n');
if (low($wannaDoScaffolding) == 'y' || low($wannaDoScaffolding) == 'yes') {
$wannaDoAdmin = $this->in(__("Would you like to create the methods for admin routing?", true), array('y','n'), 'n');
}
$wannaDoHelpers = $this->in(__("Would you like this controller to use other helpers besides HtmlHelper and FormHelper?", true), array('y','n'), 'n');
if (low($wannaDoHelpers) == 'y' || low($wannaDoHelpers) == 'yes') {
$helpersList = $this->in(__("Please provide a comma separated list of the other helper names you'd like to use.\nExample: 'Ajax, Javascript, Time'", true));
$helpersListTrimmed = str_replace(' ', '', $helpersList);
$helpers = explode(',', $helpersListTrimmed);
}
$wannaDoComponents = $this->in(__("Would you like this controller to use any components?", true), array('y','n'), 'n');
if (low($wannaDoComponents) == 'y' || low($wannaDoComponents) == 'yes') {
$componentsList = $this->in(__("Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'", true));
$componentsListTrimmed = str_replace(' ', '', $componentsList);
$components = explode(',', $componentsListTrimmed);
}
$wannaUseSession = $this->in(__("Would you like to use Sessions?", true), array('y','n'), 'y');
} else { } else {
$wannaDoScaffolding = 'n'; list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
$helpers = $this->doHelpers();
$components = $this->doComponents();
$wannaUseSession = $this->in(
__("Would you like to use Session flash messages?", true), array('y','n'), 'y'
);
} }
} else { } else {
$wannaDoScaffolding = $this->in(__("Would you like to include some basic class methods (index(), add(), view(), edit())?", true), array('y','n'), 'y'); list($wannaBakeCrud, $wannaBakeCrud) = $this->_askAboutMethods();
if (low($wannaDoScaffolding) == 'y' || low($wannaDoScaffolding) == 'yes') {
$wannaDoAdmin = $this->in(__("Would you like to create the methods for admin routing?", true), array('y','n'), 'y');
}
}
$admin = false;
if ((low($wannaDoAdmin) == 'y' || low($wannaDoAdmin) == 'yes')) {
$admin = $this->getAdmin();
} }
if (low($wannaDoScaffolding) == 'y' || low($wannaDoScaffolding) == 'yes') { if (strtolower($wannaBakeCrud) == 'y') {
$actions = $this->bakeActions($controllerName, null, in_array(low($wannaUseSession), array('y', 'yes'))); $actions = $this->bakeActions($controllerName, null, strtolower($wannaUseSession) == 'y');
if ($admin) { }
$actions .= $this->bakeActions($controllerName, $admin, in_array(low($wannaUseSession), array('y', 'yes'))); if (strtolower($wannaBakeAdminCrud) == 'y') {
} $admin = $this->Project->getAdmin();
$actions .= $this->bakeActions($controllerName, $admin, strtolower($wannaUseSession) == 'y');
} }
if ($this->interactive === true) { if ($this->interactive === true) {
$this->out(''); $this->confirmController($controllerName, $useDynamicScaffold, $helpers, $components);
$this->hr();
$this->out('The following controller will be created:');
$this->hr();
$this->out("Controller Name: $controllerName");
if (low($wannaUseScaffold) == 'y' || low($wannaUseScaffold) == 'yes') {
$this->out(" var \$scaffold;");
$actions = 'scaffold';
}
if (count($helpers)) {
$this->out("Helpers: ", false);
foreach ($helpers as $help) {
if ($help != $helpers[count($helpers) - 1]) {
$this->out(ucfirst($help) . ", ", false);
} else {
$this->out(ucfirst($help));
}
}
}
if (count($components)) {
$this->out("Components: ", false);
foreach ($components as $comp) {
if ($comp != $components[count($components) - 1]) {
$this->out(ucfirst($comp) . ", ", false);
} else {
$this->out(ucfirst($comp));
}
}
}
$this->hr();
$looksGood = $this->in(__('Look okay?', true), array('y','n'), 'y'); $looksGood = $this->in(__('Look okay?', true), array('y','n'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') { if (strtolower($looksGood) == 'y') {
$baked = $this->bake($controllerName, $actions, $helpers, $components, $uses); $baked = $this->bake($controllerName, $actions, $helpers, $components);
if ($baked && $this->_checkUnitTest()) { if ($baked && $this->_checkUnitTest()) {
$this->bakeTest($controllerName); $this->bakeTest($controllerName);
} }
} else {
$this->__interactive($controllerName);
} }
} else { } else {
$baked = $this->bake($controllerName, $actions, $helpers, $components, $uses); $baked = $this->bake($controllerName, $actions, $helpers, $components);
if ($baked && $this->_checkUnitTest()) { if ($baked && $this->_checkUnitTest()) {
$this->bakeTest($controllerName); $this->bakeTest($controllerName);
} }
} }
} }
/**
* Confirm a to be baked controller with the user
*
* @return void
**/
function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
$this->out('');
$this->hr();
$this->out(__('The following controller will be created:', true));
$this->hr();
$this->out(sprintf(__("Controller Name:\n\t%s", true), $controllerName));
if (strtolower($useDynamicScaffold) == 'y') {
$this->out("var \$scaffold;");
}
$properties = array(
'helpers' => __("Helpers:", true),
'components' => __('Components:', true),
);
foreach ($properties as $var => $title) {
if (count($$var)) {
$output = '';
$length = count($$var);
foreach ($$var as $i => $propElement) {
if ($i != $length -1) {
$output .= ucfirst($propElement) . ', ';
} else {
$output .= ucfirst($propElement);
}
}
$this->out($title . "\n\t" . $output);
}
}
$this->hr();
}
/**
* Interact with the user and ask about which methods (admin or regular they want to bake)
*
* @return array Array containing (bakeRegular, bakeAdmin) answers
**/
function _askAboutMethods() {
$wannaBakeCrud = $this->in(
__("Would you like to create some basic class methods \n(index(), add(), view(), edit())?", true),
array('y','n'), 'n'
);
$wannaBakeAdminCrud = $this->in(
__("Would you like to create the basic class methods for admin routing?", true),
array('y','n'), 'n'
);
return array($wannaBakeCrud, $wannaBakeAdminCrud);
}
/** /**
* Bake scaffold actions * Bake scaffold actions
* *
@ -247,151 +269,23 @@ class ControllerTask extends Shell {
if ($this->plugin) { if ($this->plugin) {
$modelImport = $this->plugin . '.' . $modelImport; $modelImport = $this->plugin . '.' . $modelImport;
} }
if (!App::import('Model', $modelImport)) { if (!App::import('Model', $currentModelName)) {
$this->err(__('You must have a model for this class to build scaffold methods. Please try again.', true)); $this->err(__('You must have a model for this class to build basic methods. Please try again.', true));
exit; $this->_stop();
} }
$actions = null;
$modelObj =& new $currentModelName(); $modelObj =& ClassRegistry::init($currentModelName);
$controllerPath = $this->_controllerPath($controllerName); $controllerPath = $this->_controllerPath($controllerName);
$pluralName = $this->_pluralName($currentModelName); $pluralName = $this->_pluralName($currentModelName);
$singularName = Inflector::variable($currentModelName); $singularName = Inflector::variable($currentModelName);
$singularHumanName = Inflector::humanize($currentModelName); $singularHumanName = Inflector::humanize($currentModelName);
$pluralHumanName = Inflector::humanize($controllerName); $pluralHumanName = Inflector::humanize($controllerName);
$actions .= "\n";
$actions .= "\tfunction {$admin}index() {\n";
$actions .= "\t\t\$this->{$currentModelName}->recursive = 0;\n";
$actions .= "\t\t\$this->set('{$pluralName}', \$this->paginate());\n";
$actions .= "\t}\n";
$actions .= "\n";
$actions .= "\tfunction {$admin}view(\$id = null) {\n";
$actions .= "\t\tif (!\$id) {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\$this->Session->setFlash(__('Invalid {$singularHumanName}.', true));\n";
$actions .= "\t\t\t\$this->redirect(array('action'=>'index'));\n";
} else {
$actions .= "\t\t\t\$this->flash(__('Invalid {$singularHumanName}', true), array('action'=>'index'));\n";
}
$actions .= "\t\t}\n";
$actions .= "\t\t\$this->set('".$singularName."', \$this->{$currentModelName}->read(null, \$id));\n";
$actions .= "\t}\n";
$actions .= "\n";
/* ADD ACTION */ $this->Template->set(compact('admin', 'controllerPath', 'pluralName', 'singularName', 'singularHumanName',
$compact = array(); 'pluralHumanName', 'modelObj', 'wannaUseSession', 'currentModelName'));
$actions .= "\tfunction {$admin}add() {\n"; $actions = $this->Template->generate('actions', 'controller_actions');
$actions .= "\t\tif (!empty(\$this->data)) {\n";
$actions .= "\t\t\t\$this->{$currentModelName}->create();\n";
$actions .= "\t\t\tif (\$this->{$currentModelName}->save(\$this->data)) {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\t\$this->Session->setFlash(__('The ".$singularHumanName." has been saved', true));\n";
$actions .= "\t\t\t\t\$this->redirect(array('action'=>'index'));\n";
} else {
$actions .= "\t\t\t\t\$this->flash(__('{$currentModelName} saved.', true), array('action'=>'index'));\n";
}
$actions .= "\t\t\t} else {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\t\$this->Session->setFlash(__('The {$singularHumanName} could not be saved. Please, try again.', true));\n";
}
$actions .= "\t\t\t}\n";
$actions .= "\t\t}\n";
foreach ($modelObj->hasAndBelongsToMany as $associationName => $relation) {
if (!empty($associationName)) {
$habtmModelName = $this->_modelName($associationName);
$habtmSingularName = $this->_singularName($associationName);
$habtmPluralName = $this->_pluralName($associationName);
$actions .= "\t\t\${$habtmPluralName} = \$this->{$currentModelName}->{$habtmModelName}->find('list');\n";
$compact[] = "'{$habtmPluralName}'";
}
}
foreach ($modelObj->belongsTo as $associationName => $relation) {
if (!empty($associationName)) {
$belongsToModelName = $this->_modelName($associationName);
$belongsToPluralName = $this->_pluralName($associationName);
$actions .= "\t\t\${$belongsToPluralName} = \$this->{$currentModelName}->{$belongsToModelName}->find('list');\n";
$compact[] = "'{$belongsToPluralName}'";
}
}
if (!empty($compact)) {
$actions .= "\t\t\$this->set(compact(".join(', ', $compact)."));\n";
}
$actions .= "\t}\n";
$actions .= "\n";
/* EDIT ACTION */
$compact = array();
$actions .= "\tfunction {$admin}edit(\$id = null) {\n";
$actions .= "\t\tif (!\$id && empty(\$this->data)) {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\$this->Session->setFlash(__('Invalid {$singularHumanName}', true));\n";
$actions .= "\t\t\t\$this->redirect(array('action'=>'index'));\n";
} else {
$actions .= "\t\t\t\$this->flash(__('Invalid {$singularHumanName}', true), array('action'=>'index'));\n";
}
$actions .= "\t\t}\n";
$actions .= "\t\tif (!empty(\$this->data)) {\n";
$actions .= "\t\t\tif (\$this->{$currentModelName}->save(\$this->data)) {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\t\$this->Session->setFlash(__('The ".$singularHumanName." has been saved', true));\n";
$actions .= "\t\t\t\t\$this->redirect(array('action'=>'index'));\n";
} else {
$actions .= "\t\t\t\t\$this->flash(__('The ".$singularHumanName." has been saved.', true), array('action'=>'index'));\n";
}
$actions .= "\t\t\t} else {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\t\$this->Session->setFlash(__('The {$singularHumanName} could not be saved. Please, try again.', true));\n";
}
$actions .= "\t\t\t}\n";
$actions .= "\t\t}\n";
$actions .= "\t\tif (empty(\$this->data)) {\n";
$actions .= "\t\t\t\$this->data = \$this->{$currentModelName}->read(null, \$id);\n";
$actions .= "\t\t}\n";
foreach ($modelObj->hasAndBelongsToMany as $associationName => $relation) {
if (!empty($associationName)) {
$habtmModelName = $this->_modelName($associationName);
$habtmSingularName = $this->_singularName($associationName);
$habtmPluralName = $this->_pluralName($associationName);
$actions .= "\t\t\${$habtmPluralName} = \$this->{$currentModelName}->{$habtmModelName}->find('list');\n";
$compact[] = "'{$habtmPluralName}'";
}
}
foreach ($modelObj->belongsTo as $associationName => $relation) {
if (!empty($associationName)) {
$belongsToModelName = $this->_modelName($associationName);
$belongsToPluralName = $this->_pluralName($associationName);
$actions .= "\t\t\${$belongsToPluralName} = \$this->{$currentModelName}->{$belongsToModelName}->find('list');\n";
$compact[] = "'{$belongsToPluralName}'";
}
}
if (!empty($compact)) {
$actions .= "\t\t\$this->set(compact(".join(',', $compact)."));\n";
}
$actions .= "\t}\n";
$actions .= "\n";
$actions .= "\tfunction {$admin}delete(\$id = null) {\n";
$actions .= "\t\tif (!\$id) {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\$this->Session->setFlash(__('Invalid id for {$singularHumanName}', true));\n";
$actions .= "\t\t\t\$this->redirect(array('action'=>'index'));\n";
} else {
$actions .= "\t\t\t\$this->flash(__('Invalid {$singularHumanName}', true), array('action'=>'index'));\n";
}
$actions .= "\t\t}\n";
$actions .= "\t\tif (\$this->{$currentModelName}->delete(\$id)) {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\$this->Session->setFlash(__('{$singularHumanName} deleted', true));\n";
$actions .= "\t\t\t\$this->redirect(array('action'=>'index'));\n";
} else {
$actions .= "\t\t\t\$this->flash(__('{$singularHumanName} deleted', true), array('action'=>'index'));\n";
}
$actions .= "\t\t}\n";
$actions .= "\t}\n";
$actions .= "\n";
return $actions; return $actions;
} }
/** /**
* Assembles and writes a Controller file * Assembles and writes a Controller file
* *
@ -403,53 +297,22 @@ class ControllerTask extends Shell {
* @return string Baked controller * @return string Baked controller
* @access private * @access private
*/ */
function bake($controllerName, $actions = '', $helpers = null, $components = null, $uses = null) { function bake($controllerName, $actions = '', $helpers = null, $components = null) {
$out = "<?php\n"; $isScaffold = ($actions === 'scaffold') ? true : false;
$out .= "class $controllerName" . "Controller extends {$this->plugin}AppController {\n\n";
$out .= "\tvar \$name = '$controllerName';\n";
if (low($actions) == 'scaffold') { $this->Template->set('plugin', Inflector::camelize($this->plugin));
$out .= "\tvar \$scaffold;\n"; $this->Template->set(compact('controllerName', 'actions', 'helpers', 'components', 'isScaffold'));
} else { $contents = $this->Template->generate('classes', 'controller');
if (count($uses)) {
$out .= "\tvar \$uses = array('" . $this->_modelName($controllerName) . "', ";
foreach ($uses as $use) { $path = $this->path;
if ($use != $uses[count($uses) - 1]) { if (isset($this->plugin)) {
$out .= "'" . $this->_modelName($use) . "', "; $path = $this->_pluginPath($this->plugin) . 'controllers' . DS;
} else {
$out .= "'" . $this->_modelName($use) . "'";
}
}
$out .= ");\n";
}
$out .= "\tvar \$helpers = array('Html', 'Form'";
if (count($helpers)) {
foreach ($helpers as $help) {
$out .= ", '" . Inflector::camelize($help) . "'";
}
}
$out .= ");\n";
if (count($components)) {
$out .= "\tvar \$components = array(";
foreach ($components as $comp) {
if ($comp != $components[count($components) - 1]) {
$out .= "'" . Inflector::camelize($comp) . "', ";
} else {
$out .= "'" . Inflector::camelize($comp) . "'";
}
}
$out .= ");\n";
}
$out .= $actions;
} }
$out .= "}\n"; $filename = $path . $this->_controllerPath($controllerName) . '_controller.php';
$out .= "?>"; if ($this->createFile($filename, $contents)) {
$filename = $this->path . $this->_controllerPath($controllerName) . '_controller.php'; return $contents;
return $this->createFile($filename, $out); }
return false;
} }
/** /**
* Assembles and writes a unit test file * Assembles and writes a unit test file
@ -459,84 +322,89 @@ class ControllerTask extends Shell {
* @access private * @access private
*/ */
function bakeTest($className) { function bakeTest($className) {
$import = $className; $this->Test->plugin = $this->plugin;
if ($this->plugin) { $this->Test->connection = $this->connection;
$import = $this->plugin . '.' . $className; return $this->Test->bake('Controller', $className);
}
$out = "App::import('Controller', '$import');\n\n";
$out .= "class Test{$className} extends {$className}Controller {\n";
$out .= "\tvar \$autoRender = false;\n}\n\n";
$out .= "class {$className}ControllerTest extends CakeTestCase {\n";
$out .= "\tvar \${$className} = null;\n\n";
$out .= "\tfunction startTest() {\n\t\t\$this->{$className} = new Test{$className}();";
$out .= "\n\t\t\$this->{$className}->constructClasses();\n\t}\n\n";
$out .= "\tfunction test{$className}ControllerInstance() {\n";
$out .= "\t\t\$this->assertTrue(is_a(\$this->{$className}, '{$className}Controller'));\n\t}\n\n";
$out .= "\tfunction endTest() {\n\t\tunset(\$this->{$className});\n\t}\n}\n";
$path = CONTROLLER_TESTS;
if (isset($this->plugin)) {
$pluginPath = 'plugins' . DS . Inflector::underscore($this->plugin) . DS;
$path = APP . $pluginPath . 'tests' . DS . 'cases' . DS . 'controllers' . DS;
}
$filename = Inflector::underscore($className).'_controller.test.php';
$this->out("\nBaking unit test for $className...");
$header = '$Id';
$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $className ."Controller Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
return $this->createFile($path . $filename, $content);
} }
/** /**
* Outputs and gets the list of possible models or controllers from database * Interact with the user and get a list of additional helpers
*
* @return array Helpers that the user wants to use.
**/
function doHelpers() {
return $this->_doPropertyChoices(
__("Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?", true),
__("Please provide a comma separated list of the other\nhelper names you'd like to use.\nExample: 'Ajax, Javascript, Time'", true)
);
}
/**
* Interact with the user and get a list of additional components
*
* @return array Components the user wants to use.
**/
function doComponents() {
return $this->_doPropertyChoices(
__("Would you like this controller to use any components?", true),
__("Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'", true)
);
}
/**
* Common code for property choice handling.
*
* @param string $prompt A yes/no question to precede the list
* @param sting $example A question for a comma separated list, with examples.
* @return array Array of values for property.
**/
function _doPropertyChoices($prompt, $example) {
$proceed = $this->in($prompt, array('y','n'), 'n');
$property = array();
if (strtolower($proceed) == 'y') {
$propertyList = $this->in($example);
$propertyListTrimmed = str_replace(' ', '', $propertyList);
$property = explode(',', $propertyListTrimmed);
}
return array_filter($property);
}
/**
* Outputs and gets the list of possible controllers from database
* *
* @param string $useDbConfig Database configuration name * @param string $useDbConfig Database configuration name
* @param boolean $interactive Whether you are using listAll interactively and want options output.
* @return array Set of controllers * @return array Set of controllers
* @access public * @access public
*/ */
function listAll($useDbConfig = 'default') { function listAll($useDbConfig = null) {
$db =& ConnectionManager::getDataSource($useDbConfig); if (is_null($useDbConfig)) {
$usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix']; $useDbConfig = $this->connection;
if ($usePrefix) { }
$tables = array(); $this->__tables = $this->Model->getAllTables($useDbConfig);
foreach ($db->listSources() as $table) {
if (!strncmp($table, $usePrefix, strlen($usePrefix))) { if ($this->interactive == true) {
$tables[] = substr($table, strlen($usePrefix)); $this->out(__('Possible Controllers based on your current database:', true));
} $this->_controllerNames = array();
$count = count($this->__tables);
for ($i = 0; $i < $count; $i++) {
$this->_controllerNames[] = $this->_controllerName($this->_modelName($this->__tables[$i]));
$this->out($i + 1 . ". " . $this->_controllerNames[$i]);
} }
} else { return $this->_controllerNames;
$tables = $db->listSources();
} }
return $this->__tables;
if (empty($tables)) {
$this->err(__('Your database does not have any tables.', true));
$this->_stop();
}
$this->__tables = $tables;
$this->out('Possible Controllers based on your current database:');
$this->_controllerNames = array();
$count = count($tables);
for ($i = 0; $i < $count; $i++) {
$this->_controllerNames[] = $this->_controllerName($this->_modelName($tables[$i]));
$this->out($i + 1 . ". " . $this->_controllerNames[$i]);
}
return $this->_controllerNames;
} }
/** /**
* Forces the user to specify the controller he wants to bake, and returns the selected controller name. * Forces the user to specify the controller he wants to bake, and returns the selected controller name.
* *
* @param string $useDbConfig Connection name to get a controller name for.
* @return string Controller name * @return string Controller name
* @access public * @access public
*/ */
function getName() { function getName($useDbConfig = null) {
$useDbConfig = 'default'; $controllers = $this->listAll($useDbConfig);
$controllers = $this->listAll($useDbConfig, 'Controllers');
$enteredController = ''; $enteredController = '';
while ($enteredController == '') { while ($enteredController == '') {
$enteredController = $this->in(__("Enter a number from the list above, type in the name of another controller, or 'q' to exit", true), null, 'q'); $enteredController = $this->in(__("Enter a number from the list above,\ntype in the name of another controller, or 'q' to exit", true), null, 'q');
if ($enteredController === 'q') { if ($enteredController === 'q') {
$this->out(__("Exit", true)); $this->out(__("Exit", true));
@ -544,8 +412,7 @@ class ControllerTask extends Shell {
} }
if ($enteredController == '' || intval($enteredController) > count($controllers)) { if ($enteredController == '' || intval($enteredController) > count($controllers)) {
$this->out(__('Error:', true)); $this->err(__("The Controller name you supplied was empty,\nor the number you selected was not an option. Please try again.", true));
$this->out(__("The Controller name you supplied was empty, or the number \nyou selected was not an option. Please try again.", true));
$enteredController = ''; $enteredController = '';
} }
} }
@ -555,7 +422,6 @@ class ControllerTask extends Shell {
} else { } else {
$controllerName = Inflector::camelize($enteredController); $controllerName = Inflector::camelize($enteredController);
} }
return $controllerName; return $controllerName;
} }
/** /**
@ -568,12 +434,26 @@ class ControllerTask extends Shell {
$this->out("Usage: cake bake controller <arg1> <arg2>..."); $this->out("Usage: cake bake controller <arg1> <arg2>...");
$this->hr(); $this->hr();
$this->out('Commands:'); $this->out('Commands:');
$this->out("\n\tcontroller <name>\n\t\tbakes controller with var \$scaffold"); $this->out('');
$this->out("\n\tcontroller <name> scaffold\n\t\tbakes controller with scaffold actions.\n\t\t(index, view, add, edit, delete)"); $this->out("controller <name>");
$this->out("\n\tcontroller <name> scaffold admin\n\t\tbakes a controller with scaffold actions for both public and Configure::read('Routing.admin')"); $this->out("\tbakes controller with var \$scaffold");
$this->out("\n\tcontroller <name> admin\n\t\tbakes a controller with scaffold actions only for Configure::read('Routing.admin')"); $this->out('');
$this->out("controller <name> scaffold");
$this->out("\tbakes controller with scaffold actions.");
$this->out("\t(index, view, add, edit, delete)");
$this->out('');
$this->out("controller <name> scaffold admin");
$this->out("\tbakes a controller with scaffold actions for both public");
$this->out("\tand Configure::read('Routing.admin')");
$this->out('');
$this->out("controller <name> admin");
$this->out("\tbakes a controller with scaffold actions only for");
$this->out("\tConfigure::read('Routing.admin')");
$this->out('');
$this->out("controller all");
$this->out("\tbakes all controllers with CRUD methods.");
$this->out(""); $this->out("");
$this->_stop(); $this->_stop();
} }
} }
?> ?>

View file

@ -1,5 +1,4 @@
<?php <?php
/* SVN FILE: $Id$ */
/** /**
* The DbConfig Task handles creating and updating the database.php * The DbConfig Task handles creating and updating the database.php
* *
@ -8,25 +7,19 @@
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake * @package cake
* @subpackage cake.cake.console.libs.tasks * @subpackage cake.cake.console.libs.tasks
* @since CakePHP(tm) v 1.2 * @since CakePHP(tm) v 1.2
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
if (!class_exists('File')) {
uses('file');
}
/** /**
* Task class for creating and updating the database configuration file. * Task class for creating and updating the database configuration file.
* *
@ -52,6 +45,13 @@ class DbConfigTask extends Shell {
'login'=> 'root', 'password'=> 'password', 'database'=> 'project_name', 'login'=> 'root', 'password'=> 'password', 'database'=> 'project_name',
'schema'=> null, 'prefix'=> null, 'encoding' => null, 'port' => null 'schema'=> null, 'prefix'=> null, 'encoding' => null, 'port' => null
); );
/**
* String name of the database config class name.
* Used for testing.
*
* @var string
**/
var $databaseClassName = 'DATABASE_CONFIG';
/** /**
* initialization callback * initialization callback
* *
@ -92,35 +92,27 @@ class DbConfigTask extends Shell {
if (preg_match('/[^a-z0-9_]/i', $name)) { if (preg_match('/[^a-z0-9_]/i', $name)) {
$name = ''; $name = '';
$this->out('The name may only contain unaccented latin characters, numbers or underscores'); $this->out('The name may only contain unaccented latin characters, numbers or underscores');
} } else if (preg_match('/^[^a-z_]/i', $name)) {
else if (preg_match('/^[^a-z_]/i', $name)) {
$name = ''; $name = '';
$this->out('The name must start with an unaccented latin character or an underscore'); $this->out('The name must start with an unaccented latin character or an underscore');
} }
} }
$driver = '';
while ($driver == '') { $driver = $this->in('Driver:', array('db2', 'firebird', 'mssql', 'mysql', 'mysqli', 'odbc', 'oracle', 'postgres', 'sqlite', 'sybase'), 'mysql');
$driver = $this->in('Driver:', array('db2', 'firebird', 'mssql', 'mysql', 'mysqli', 'odbc', 'oracle', 'postgres', 'sqlite', 'sybase'), 'mysql');
}
$persistent = '';
while ($persistent == '') {
$persistent = $this->in('Persistent Connection?', array('y', 'n'), 'n');
}
$persistent = $this->in('Persistent Connection?', array('y', 'n'), 'n');
if (low($persistent) == 'n') { if (low($persistent) == 'n') {
$persistent = 'false'; $persistent = 'false';
} else { } else {
$persistent = 'true'; $persistent = 'true';
} }
$host = '';
$host = '';
while ($host == '') { while ($host == '') {
$host = $this->in('Database Host:', null, 'localhost'); $host = $this->in('Database Host:', null, 'localhost');
} }
$port = '';
$port = '';
while ($port == '') { while ($port == '') {
$port = $this->in('Port?', null, 'n'); $port = $this->in('Port?', null, 'n');
} }
@ -128,8 +120,8 @@ class DbConfigTask extends Shell {
if (low($port) == 'n') { if (low($port) == 'n') {
$port = null; $port = null;
} }
$login = '';
$login = '';
while ($login == '') { while ($login == '') {
$login = $this->in('User:', null, 'root'); $login = $this->in('User:', null, 'root');
} }
@ -141,43 +133,39 @@ class DbConfigTask extends Shell {
if ($password == '') { if ($password == '') {
$blank = $this->in('The password you supplied was empty. Use an empty password?', array('y', 'n'), 'n'); $blank = $this->in('The password you supplied was empty. Use an empty password?', array('y', 'n'), 'n');
if ($blank == 'y') if ($blank == 'y') {
{
$blankPassword = true; $blankPassword = true;
} }
} }
} }
$database = '';
$database = '';
while ($database == '') { while ($database == '') {
$database = $this->in('Database Name:', null, 'cake'); $database = $this->in('Database Name:', null, 'cake');
} }
$prefix = '';
$prefix = '';
while ($prefix == '') { while ($prefix == '') {
$prefix = $this->in('Table Prefix?', null, 'n'); $prefix = $this->in('Table Prefix?', null, 'n');
} }
if (low($prefix) == 'n') { if (low($prefix) == 'n') {
$prefix = null; $prefix = null;
} }
$encoding = '';
$encoding = '';
while ($encoding == '') { while ($encoding == '') {
$encoding = $this->in('Table encoding?', null, 'n'); $encoding = $this->in('Table encoding?', null, 'n');
} }
if (low($encoding) == 'n') { if (low($encoding) == 'n') {
$encoding = null; $encoding = null;
} }
$schema = '';
$schema = '';
if ($driver == 'postgres') { if ($driver == 'postgres') {
while ($schema == '') { while ($schema == '') {
$schema = $this->in('Table schema?', null, 'n'); $schema = $this->in('Table schema?', null, 'n');
} }
} }
if (low($schema) == 'n') { if (low($schema) == 'n') {
$schema = null; $schema = null;
} }
@ -240,7 +228,7 @@ class DbConfigTask extends Shell {
$this->hr(); $this->hr();
$looksGood = $this->in('Look okay?', array('y', 'n'), 'y'); $looksGood = $this->in('Look okay?', array('y', 'n'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') { if (strtolower($looksGood) == 'y') {
return $config; return $config;
} }
return false; return false;
@ -262,7 +250,7 @@ class DbConfigTask extends Shell {
$oldConfigs = array(); $oldConfigs = array();
if (file_exists($filename)) { if (file_exists($filename)) {
$db = new DATABASE_CONFIG; $db = new $this->databaseClassName;
$temp = get_class_vars(get_class($db)); $temp = get_class_vars(get_class($db));
foreach ($temp as $configName => $info) { foreach ($temp as $configName => $info) {
@ -346,8 +334,27 @@ class DbConfigTask extends Shell {
$out .= "}\n"; $out .= "}\n";
$out .= "?>"; $out .= "?>";
$filename = $this->path.'database.php'; $filename = $this->path . 'database.php';
return $this->createFile($filename, $out); return $this->createFile($filename, $out);
} }
/**
* Get a user specified Connection name
*
* @return void
**/
function getConfig() {
$useDbConfig = 'default';
$configs = get_class_vars($this->databaseClassName);
if (!is_array($configs)) {
return $this->execute();
}
$connections = array_keys($configs);
if (count($connections) > 1) {
$useDbConfig = $this->in(__('Use Database Config', true) .':', $connections, 'default');
}
return $useDbConfig;
}
} }
?> ?>

View file

@ -1,5 +1,4 @@
<?php <?php
/* SVN FILE: $Id$ */
/** /**
* Short description for file. * Short description for file.
* *
@ -8,20 +7,17 @@
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake * @package cake
* @subpackage cake.cake.console.libs * @subpackage cake.cake.console.libs
* @since CakePHP(tm) v 1.2.0.5012 * @since CakePHP(tm) v 1.2.0.5012
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
/** /**

View file

@ -0,0 +1,409 @@
<?php
/**
* The FixtureTask handles creating and updating fixture files.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* Task class for creating and updating fixtures files.
*
* @package cake
* @subpackage cake.cake.console.libs.tasks
*/
class FixtureTask extends Shell {
/**
* Name of plugin
*
* @var string
* @access public
*/
var $plugin = null;
/**
* Tasks to be loaded by this Task
*
* @var array
* @access public
*/
var $tasks = array('DbConfig', 'Model', 'Template');
/**
* path to fixtures directory
*
* @var string
* @access public
*/
var $path = null;
/**
* The db connection being used for baking
*
* @var string
**/
var $connection = null;
/**
* Schema instance
*
* @var object
**/
var $_Schema = null;
/**
* Override initialize
*
* @access public
*/
function __construct(&$dispatch) {
parent::__construct($dispatch);
$this->path = $this->params['working'] . DS . 'tests' . DS . 'fixtures' . DS;
if (!class_exists('CakeSchema')) {
App::import('Model', 'CakeSchema');
}
}
/**
* Execution method always used for tasks
* Handles dispatching to interactive, named, or all processess.
*
* @access public
*/
function execute() {
if (empty($this->args)) {
$this->__interactive();
}
if (isset($this->args[0])) {
if (!isset($this->connection)) {
$this->connection = 'default';
}
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
$model = Inflector::camelize($this->args[0]);
$this->bake($model);
}
}
/**
* Bake All the Fixtures at once. Will only bake fixtures for models that exist.
*
* @access public
* @return void
**/
function all() {
$this->interactive = false;
$tables = $this->Model->listAll($this->connection, false);
foreach ($tables as $table) {
$model = $this->_modelName($table);
$this->bake($model);
}
}
/**
* Interactive baking function
*
* @access private
*/
function __interactive() {
$this->interactive = true;
$this->hr();
$this->out(sprintf("Bake Fixture\nPath: %s", $this->path));
$this->hr();
$useDbConfig = $this->connection;
if (!isset($this->connection)) {
$this->connection = $this->DbConfig->getConfig();
}
$modelName = $this->Model->getName($this->connection);
$useTable = $this->Model->getTable($modelName, $this->connection);
$importOptions = $this->importOptions($modelName);
$this->bake($modelName, $useTable, $importOptions);
}
/**
* Interacts with the User to setup an array of import options. For a fixture.
*
* @param string $modelName Name of model you are dealing with.
* @return array Array of import options.
**/
function importOptions($modelName) {
$options = array();
$doSchema = $this->in(__('Would you like to import schema for this fixture?', true), array('y', 'n'), 'n');
if ($doSchema == 'y') {
$options['schema'] = $modelName;
}
$doRecords = $this->in(__('Would you like to use record importing for this fixture?', true), array('y', 'n'), 'n');
if ($doRecords == 'y') {
$options['records'] = true;
}
if ($doRecords == 'n') {
$prompt = sprintf(__("Would you like to build this fixture with data from %s's table?", true), $modelName);
$fromTable = $this->in($prompt, array('y', 'n'), 'n');
if (strtolower($fromTable) == 'y') {
$options['fromTable'] = true;
}
}
return $options;
}
/**
* Assembles and writes a Fixture file
*
* @param string $model Name of model to bake.
* @param string $useTable Name of table to use.
* @param array $importOptions Options for var $import
* @return string Baked fixture
* @access private
*/
function bake($model, $useTable = false, $importOptions = array()) {
$table = $schema = $records = $import = $modelImport = $recordImport = null;
if (!$useTable) {
$useTable = Inflector::tableize($model);
} elseif ($useTable != Inflector::tableize($model)) {
$table = $useTable;
}
if (!empty($importOptions)) {
if (isset($importOptions['schema'])) {
$modelImport = "'model' => '{$importOptions['schema']}'";
}
if (isset($importOptions['records'])) {
$recordImport = "'records' => true";
}
if ($modelImport && $recordImport) {
$modelImport .= ', ';
}
if (!empty($modelImport) || !empty($recordImport)) {
$import = sprintf("array(%s%s)", $modelImport, $recordImport);
}
}
$this->_Schema = new CakeSchema();
$data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
if (!isset($data['tables'][$useTable])) {
$this->err('Could not find your selected table ' . $useTable);
return false;
}
$tableInfo = $data['tables'][$useTable];
if (is_null($modelImport)) {
$schema = $this->_generateSchema($tableInfo);
}
if (!isset($importOptions['records']) && !isset($importOptions['fromTable'])) {
$recordCount = 1;
if (isset($this->params['count'])) {
$recordCount = $this->params['count'];
}
$records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
}
if (isset($importOptions['fromTable'])) {
$records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
}
$out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import', 'fields'));
return $out;
}
/**
* Generate the fixture file, and write to disk
*
* @param string $model name of the model being generated
* @param string $fixture Contents of the fixture file.
* @access public
* @return void
**/
function generateFixtureFile($model, $otherVars) {
$defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
$vars = array_merge($defaults, $otherVars);
$path = $this->path;
if (isset($this->plugin)) {
$path = $this->_pluginPath($this->plugin) . 'tests' . DS . 'fixtures' . DS;
}
$filename = Inflector::underscore($model) . '_fixture.php';
$this->Template->set('model', $model);
$this->Template->set($vars);
$content = $this->Template->generate('classes', 'fixture');
$this->out("\nBaking test fixture for $model...");
$this->createFile($path . $filename, $content);
return $content;
}
/**
* Generates a string representation of a schema.
*
* @param array $table Table schema array
* @return string fields definitions
**/
function _generateSchema($tableInfo) {
$cols = array();
$out = "array(\n";
foreach ($tableInfo as $field => $fieldInfo) {
if (is_array($fieldInfo)) {
if ($field != 'indexes') {
$col = "\t\t'{$field}' => array('type'=>'" . $fieldInfo['type'] . "', ";
$col .= join(', ', $this->_Schema->__values($fieldInfo));
} else {
$col = "\t\t'indexes' => array(";
$props = array();
foreach ((array)$fieldInfo as $key => $index) {
$props[] = "'{$key}' => array(".join(', ', $this->_Schema->__values($index)).")";
}
$col .= join(', ', $props);
}
$col .= ")";
$cols[] = $col;
}
}
$out .= join(",\n", $cols);
$out .= "\n\t)";
return $out;
}
/**
* Generate String representation of Records
*
* @param array $table Table schema array
* @return array Array of records to use in the fixture.
**/
function _generateRecords($tableInfo, $recordCount = 1) {
$records = array();
for ($i = 0; $i < $recordCount; $i++) {
$record = array();
foreach ($tableInfo as $field => $fieldInfo) {
if (empty($fieldInfo['type'])) {
continue;
}
switch ($fieldInfo['type']) {
case 'integer':
$insert = $i + 1;
break;
case 'string';
$isPrimaryUuid = (
isset($fieldInfo['key']) && strtolower($fieldInfo['key']) == 'primary' &&
isset($fieldInfo['length']) && $fieldInfo['length'] == 36
);
if ($isPrimaryUuid) {
$insert = String::uuid();
} else {
$insert = "Lorem ipsum dolor sit amet";
if (!empty($fieldInfo['length'])) {
$insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
}
}
$insert = "'$insert'";
break;
case 'timestamp':
$ts = time();
$insert = "'$ts'";
break;
case 'datetime':
$ts = date('Y-m-d H:i:s');
$insert = "'$ts'";
break;
case 'date':
$ts = date('Y-m-d');
$insert = "'$ts'";
break;
case 'time':
$ts = date('H:i:s');
$insert = "'$ts'";
break;
case 'boolean':
$insert = 1;
break;
case 'text':
$insert = "'Lorem ipsum dolor sit amet, aliquet feugiat.";
$insert .= " Convallis morbi fringilla gravida,";
$insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
$insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
$insert .= " vestibulum massa neque ut et, id hendrerit sit,";
$insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
$insert .= " duis vestibulum nunc mattis convallis.'";
break;
}
$record[$field] = $insert;
}
$records[] = $record;
}
return $records;
}
/**
* Convert a $records array into a a string.
*
* @param array $records Array of records to be converted to string
* @return string A string value of the $records array.
**/
function _makeRecordString($records) {
$out = "array(\n";
foreach ($records as $record) {
$values = array();
foreach ($record as $field => $value) {
$values[] = "\t\t\t'$field' => $value";
}
$out .= "\t\tarray(\n";
$out .= implode(",\n", $values);
$out .= "\n\t\t),\n";
}
$out .= "\t)";
return $out;
}
/**
* Interact with the user to get a custom SQL condition and use that to extract data
* to build a fixture.
*
* @param string $modelName name of the model to take records from.
* @param string $useTable Name of table to use.
* @return array Array of records.
**/
function _getRecordsFromTable($modelName, $useTable = null) {
$condition = null;
$prompt = __("Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1 LIMIT 10", true);
while (!$condition) {
$condition = $this->in($prompt, null, 'WHERE 1=1 LIMIT 10');
}
App::import('Core', 'Model');
$modelObject =& new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
$records = $modelObject->find('all', array(
'conditions' => $condition,
'recursive' => -1
));
$db =& $modelObject->getDataSource();
$schema = $modelObject->schema();
$out = array();
foreach ($records as $record) {
$row = array();
foreach ($record[$modelObject->alias] as $field => $value) {
$row[$field] = $db->value($value, $schema[$field]['type']);
}
$out[] = $row;
}
return $out;
}
/**
* Displays help contents
*
* @access public
*/
function help() {
$this->hr();
$this->out("Usage: cake bake fixture <arg1> <params>");
$this->hr();
$this->out('Commands:');
$this->out("\nfixture <name>\n\tbakes fixture with specified name.");
$this->out("\nfixture all\n\tbakes all fixtures.");
$this->out("");
$this->out('Parameters:');
$this->out("\t-count When using generated data, the number of records to include in the fixture(s).");
$this->out("\t-connection Which database configuration to use for baking.");
$this->out("\t-plugin lowercased_underscored name of plugin to bake fixtures for.");
$this->out("");
$this->_stop();
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,4 @@
<?php <?php
/* SVN FILE: $Id$ */
/** /**
* The Plugin Task handles creating an empty plugin, ready to be used * The Plugin Task handles creating an empty plugin, ready to be used
* *
@ -8,25 +7,20 @@
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake * @package cake
* @subpackage cake.cake.console.libs.tasks * @subpackage cake.cake.console.libs.tasks
* @since CakePHP(tm) v 1.2 * @since CakePHP(tm) v 1.2
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
if (!class_exists('File')) {
uses('file');
}
/** /**
* Task class for creating a plugin * Task class for creating a plugin
* *
@ -62,27 +56,27 @@ class PluginTask extends Shell {
function execute() { function execute() {
if (empty($this->params['skel'])) { if (empty($this->params['skel'])) {
$this->params['skel'] = ''; $this->params['skel'] = '';
if (is_dir(CAKE_CORE_INCLUDE_PATH.DS.'cake'.DS.'console'.DS.'libs'.DS.'templates'.DS.'skel') === true) { if (is_dir(CAKE_CORE_INCLUDE_PATH . DS . CONSOLE_LIBS . 'templates' . DS . 'skel') === true) {
$this->params['skel'] = CAKE_CORE_INCLUDE_PATH.DS.'cake'.DS.'console'.DS.'libs'.DS.'templates'.DS.'skel'; $this->params['skel'] = CAKE_CORE_INCLUDE_PATH . DS . CONSOLE_LIBS . 'templates' . DS . 'skel';
} }
} }
$plugin = null; $plugin = null;
if (isset($this->args[0])) { if (isset($this->args[0])) {
$plugin = Inflector::camelize($this->args[0]); $plugin = Inflector::camelize($this->args[0]);
$pluginPath = Inflector::underscore($plugin) . DS; $pluginPath = $this->_pluginPath($plugin);
$this->Dispatch->shiftArgs(); $this->Dispatch->shiftArgs();
if (is_dir($this->path . $pluginPath)) { if (is_dir($pluginPath)) {
$this->out(sprintf('Plugin: %s', $plugin)); $this->out(sprintf(__('Plugin: %s', true), $plugin));
$this->out(sprintf('Path: %s', $this->path . $pluginPath)); $this->out(sprintf(__('Path: %s', true), $pluginPath));
$this->hr();
} elseif (isset($this->args[0])) { } elseif (isset($this->args[0])) {
$this->err(sprintf('%s in path %s not found.', $plugin, $this->path . $pluginPath)); $this->err(sprintf(__('%s in path %s not found.', true), $plugin, $pluginPath));
$this->_stop(); $this->_stop();
} else { } else {
$this->__interactive($plugin); $this->__interactive($plugin);
} }
} else {
return $this->__interactive();
} }
if (isset($this->args[0])) { if (isset($this->args[0])) {
@ -90,17 +84,16 @@ class PluginTask extends Shell {
$this->Dispatch->shiftArgs(); $this->Dispatch->shiftArgs();
if (in_array($task, $this->tasks)) { if (in_array($task, $this->tasks)) {
$this->{$task}->plugin = $plugin; $this->{$task}->plugin = $plugin;
$this->{$task}->path = $this->path . $pluginPath . Inflector::underscore(Inflector::pluralize($task)) . DS; $this->{$task}->path = $pluginPath . Inflector::underscore(Inflector::pluralize($task)) . DS;
if (!is_dir($this->{$task}->path)) { if (!is_dir($this->{$task}->path)) {
$this->err(sprintf(__("%s directory could not be found.\nBe sure you have created %s", true), $task, $this->{$task}->path)); $this->err(sprintf(__("%s directory could not be found.\nBe sure you have created %s", true), $task, $this->{$task}->path));
} }
$this->{$task}->loadTasks(); $this->{$task}->loadTasks();
$this->{$task}->execute(); return $this->{$task}->execute();
} }
} }
} }
/** /**
* Interactive interface * Interactive interface
* *
@ -116,7 +109,6 @@ class PluginTask extends Shell {
$this->err(sprintf(__("An error occured trying to bake: %s in %s", true), $plugin, $this->path . $pluginPath)); $this->err(sprintf(__("An error occured trying to bake: %s in %s", true), $plugin, $this->path . $pluginPath));
} }
} }
/** /**
* Bake the plugin, create directories and files * Bake the plugin, create directories and files
* *
@ -125,28 +117,49 @@ class PluginTask extends Shell {
* @return bool * @return bool
*/ */
function bake($plugin) { function bake($plugin) {
$pluginPath = Inflector::underscore($plugin); $pluginPath = Inflector::underscore($plugin);
$pathOptions = App::path('plugins');
if (count($pathOptions) > 1) {
$this->findPath($pathOptions);
}
$this->hr(); $this->hr();
$this->out("Plugin Name: $plugin"); $this->out(sprintf(__("Plugin Name: %s", true), $plugin));
$this->out("Plugin Directory: {$this->path}{$pluginPath}"); $this->out(sprintf(__("Plugin Directory: %s", true), $this->path . $pluginPath));
$this->hr(); $this->hr();
$looksGood = $this->in(__('Look okay?', true), array('y', 'n', 'q'), 'y');
$looksGood = $this->in('Look okay?', array('y', 'n', 'q'), 'y'); if (strtolower($looksGood) == 'y') {
if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
$verbose = $this->in(__('Do you want verbose output?', true), array('y', 'n'), 'n'); $verbose = $this->in(__('Do you want verbose output?', true), array('y', 'n'), 'n');
$Folder = new Folder($this->path . $pluginPath); $Folder =& new Folder($this->path . $pluginPath);
$directories = array('models' . DS . 'behaviors', 'controllers' . DS . 'components', 'views' . DS . 'helpers'); $directories = array(
'config' . DS . 'sql',
'models' . DS . 'behaviors',
'controllers' . DS . 'components',
'views' . DS . 'helpers',
'tests' . DS . 'cases' . DS . 'components',
'tests' . DS . 'cases' . DS . 'helpers',
'tests' . DS . 'cases' . DS . 'behaviors',
'tests' . DS . 'cases' . DS . 'controllers',
'tests' . DS . 'cases' . DS . 'models',
'tests' . DS . 'groups',
'tests' . DS . 'fixtures',
'vendors' . DS . 'img',
'vendors' . DS . 'js',
'vendors' . DS . 'css',
'vendors' . DS . 'shells'
);
foreach ($directories as $directory) { foreach ($directories as $directory) {
$Folder->create($this->path . $pluginPath . DS . $directory); $dirPath = $this->path . $pluginPath . DS . $directory;
$Folder->create($dirPath);
$File =& new File($dirPath . DS . 'empty', true);
} }
if (low($verbose) == 'y' || low($verbose) == 'yes') { if (strtolower($verbose) == 'y') {
foreach ($Folder->messages() as $message) { foreach ($Folder->messages() as $message) {
$this->out($message); $this->out($message);
} }
@ -180,6 +193,26 @@ class PluginTask extends Shell {
return true; return true;
} }
/**
* find and change $this->path to the user selection
*
* @return void
**/
function findPath($pathOptions) {
$valid = false;
$max = count($pathOptions);
while (!$valid) {
foreach ($pathOptions as $i => $option) {
$this->out($i + 1 .'. ' . $option);
}
$prompt = __('Choose a plugin path from the paths above.', true);
$choice = $this->in($prompt);
if (intval($choice) > 0 && intval($choice) <= $max) {
$valid = true;
}
}
$this->path = $pathOptions[$choice - 1];
}
/** /**
* Help * Help
* *
@ -191,10 +224,18 @@ class PluginTask extends Shell {
$this->out("Usage: cake bake plugin <arg1> <arg2>..."); $this->out("Usage: cake bake plugin <arg1> <arg2>...");
$this->hr(); $this->hr();
$this->out('Commands:'); $this->out('Commands:');
$this->out("\n\tplugin <name>\n\t\tbakes plugin directory structure"); $this->out('');
$this->out("\n\tplugin <name> model\n\t\tbakes model. Run 'cake bake model help' for more info."); $this->out("plugin <name>");
$this->out("\n\tplugin <name> controller\n\t\tbakes controller. Run 'cake bake controller help' for more info."); $this->out("\tbakes plugin directory structure");
$this->out("\n\tplugin <name> view\n\t\tbakes view. Run 'cake bake view help' for more info."); $this->out('');
$this->out("plugin <name> model");
$this->out("\tbakes model. Run 'cake bake model help' for more info.");
$this->out('');
$this->out("plugin <name> controller");
$this->out("\tbakes controller. Run 'cake bake controller help' for more info.");
$this->out('');
$this->out("plugin <name> view");
$this->out("\tbakes view. Run 'cake bake view help' for more info.");
$this->out(""); $this->out("");
$this->_stop(); $this->_stop();
} }

View file

@ -1,32 +1,24 @@
<?php <?php
/* SVN FILE: $Id$ */
/** /**
* The Project Task handles creating the base application * The Project Task handles creating the base application
* *
* Long description for file
* *
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake * @package cake
* @subpackage cake.cake.scripts.bake * @subpackage cake.cake.console.bake
* @since CakePHP(tm) v 1.2 * @since CakePHP(tm) v 1.2
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
if (!class_exists('File')) {
uses('file');
}
/** /**
* Task class for creating new project apps and plugins * Task class for creating new project apps and plugins
* *
@ -34,6 +26,12 @@ if (!class_exists('File')) {
* @subpackage cake.cake.console.libs.tasks * @subpackage cake.cake.console.libs.tasks
*/ */
class ProjectTask extends Shell { class ProjectTask extends Shell {
/**
* configs path (used in testing).
*
* @var string
**/
var $configPath = null;
/** /**
* Checks that given project path does not already exist, and * Checks that given project path does not already exist, and
* finds the app directory in it. Then it calls bake() with that information. * finds the app directory in it. Then it calls bake() with that information.
@ -68,7 +66,7 @@ class ProjectTask extends Shell {
if ($project) { if ($project) {
$response = false; $response = false;
while ($response == false && is_dir($project) === true && file_exists($project . 'config' . 'core.php')) { while ($response == false && is_dir($project) === true && file_exists($project . 'config' . 'core.php')) {
$response = $this->in('A project already exists in this location: '.$project.' Overwrite?', array('y','n'), 'n'); $response = $this->in('A project already exists in this location: ' . $project . ' Overwrite?', array('y','n'), 'n');
if (strtolower($response) === 'n') { if (strtolower($response) === 'n') {
$response = $project = false; $response = $project = false;
} }
@ -144,7 +142,7 @@ class ProjectTask extends Shell {
$looksGood = $this->in('Look okay?', array('y', 'n', 'q'), 'y'); $looksGood = $this->in('Look okay?', array('y', 'n', 'q'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') { if (strtolower($looksGood) == 'y') {
$verbose = $this->in(__('Do you want verbose output?', true), array('y', 'n'), 'n'); $verbose = $this->in(__('Do you want verbose output?', true), array('y', 'n'), 'n');
$Folder = new Folder($skel); $Folder = new Folder($skel);
@ -157,14 +155,14 @@ class ProjectTask extends Shell {
return false; return false;
} }
if (low($verbose) == 'y' || low($verbose) == 'yes') { if (strtolower($verbose) == 'y') {
foreach ($Folder->messages() as $message) { foreach ($Folder->messages() as $message) {
$this->out($message); $this->out($message);
} }
} }
return true; return true;
} elseif (low($looksGood) == 'q' || low($looksGood) == 'quit') { } elseif (strtolower($looksGood) == 'q') {
$this->out('Bake Aborted.'); $this->out('Bake Aborted.');
} else { } else {
$this->execute(false); $this->execute(false);
@ -181,7 +179,7 @@ class ProjectTask extends Shell {
function createHome($dir) { function createHome($dir) {
$app = basename($dir); $app = basename($dir);
$path = $dir . 'views' . DS . 'pages' . DS; $path = $dir . 'views' . DS . 'pages' . DS;
include(CAKE_CORE_INCLUDE_PATH.DS.'cake'.DS.'console'.DS.'libs'.DS.'templates'.DS.'views'.DS.'home.ctp'); include(CAKE_CORE_INCLUDE_PATH.DS.'cake'.DS.'console'.DS.'libs'.DS.'templates'.DS.'default'.DS.'views'.DS.'home.ctp');
return $this->createFile($path.'home.ctp', $output); return $this->createFile($path.'home.ctp', $output);
} }
/** /**
@ -248,7 +246,8 @@ class ProjectTask extends Shell {
* @access public * @access public
*/ */
function cakeAdmin($name) { function cakeAdmin($name) {
$File =& new File(CONFIGS . 'core.php'); $path = (empty($this->configPath)) ? CONFIGS : $this->configPath;
$File =& new File($path . 'core.php');
$contents = $File->read(); $contents = $File->read();
if (preg_match('%([/\\t\\x20]*Configure::write\(\'Routing.admin\',[\\t\\x20\'a-z]*\\);)%', $contents, $match)) { if (preg_match('%([/\\t\\x20]*Configure::write\(\'Routing.admin\',[\\t\\x20\'a-z]*\\);)%', $contents, $match)) {
$result = str_replace($match[0], "\t" . 'Configure::write(\'Routing.admin\', \''.$name.'\');', $contents); $result = str_replace($match[0], "\t" . 'Configure::write(\'Routing.admin\', \''.$name.'\');', $contents);
@ -262,6 +261,32 @@ class ProjectTask extends Shell {
return false; return false;
} }
} }
/**
* Checks for Configure::read('Routing.admin') and forces user to input it if not enabled
*
* @return string Admin route to use
* @access public
*/
function getAdmin() {
$admin = '';
$cakeAdmin = null;
$adminRoute = Configure::read('Routing.admin');
if (!empty($adminRoute)) {
return $adminRoute . '_';
}
$this->out('You need to enable Configure::write(\'Routing.admin\',\'admin\') in /app/config/core.php to use admin routing.');
$this->out('What would you like the admin route to be?');
$this->out('Example: www.example.com/admin/controller');
while ($admin == '') {
$admin = $this->in("What would you like the admin route to be?", null, 'admin');
}
if ($this->cakeAdmin($admin) !== true) {
$this->out('Unable to write to /app/config/core.php.');
$this->out('You need to enable Configure::write(\'Routing.admin\',\'admin\') in /app/config/core.php to use admin routing.');
$this->_stop();
}
return $admin . '_';
}
/** /**
* Help * Help
* *
@ -273,7 +298,10 @@ class ProjectTask extends Shell {
$this->out("Usage: cake bake project <arg1>"); $this->out("Usage: cake bake project <arg1>");
$this->hr(); $this->hr();
$this->out('Commands:'); $this->out('Commands:');
$this->out("\n\tproject <name>\n\t\tbakes app directory structure.\n\t\tif <name> begins with '/' path is absolute."); $this->out('');
$this->out("project <name>");
$this->out("\tbakes app directory structure.");
$this->out("\tif <name> begins with '/' path is absolute.");
$this->out(""); $this->out("");
$this->_stop(); $this->_stop();
} }

View file

@ -0,0 +1,183 @@
<?php
/**
* Template Task can generate templated output Used in other Tasks
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class TemplateTask extends Shell {
/**
* variables to add to template scope
*
* @var array
**/
var $templateVars = array();
/**
* Paths to look for templates on.
* Contains a list of $theme => $path
*
* @var array
**/
var $templatePaths = array();
/**
* Initialize callback. Setup paths for the template task.
*
* @access public
* @return void
**/
function initialize() {
$this->templatePaths = $this->_findThemes();
}
/**
* Find the paths to all the installed shell themes in the app.
*
* Bake themes are directories not named `skel` inside a `vendors/shells/templates` path.
*
* @return array Array of bake themes that are installed.
**/
function _findThemes() {
$paths = $this->Dispatch->shellPaths;
$themes = array();
foreach ($paths as $path) {
$Folder =& new Folder($path . 'templates', false);
$contents = $Folder->read();
$subDirs = $contents[0];
foreach ($subDirs as $dir) {
if (empty($dir) || $dir == 'skel') {
continue;
}
$templateDir = $path . 'templates' . DS . $dir . DS;
$themes[$dir] = $templateDir;
}
}
return $themes;
}
/**
* Set variable values to the template scope
*
* @param mixed $one A string or an array of data.
* @param mixed $two Value in case $one is a string (which then works as the key).
* Unused if $one is an associative array, otherwise serves as the values to $one's keys.
* @return void
*/
function set($one, $two = null) {
$data = null;
if (is_array($one)) {
if (is_array($two)) {
$data = array_combine($one, $two);
} else {
$data = $one;
}
} else {
$data = array($one => $two);
}
if ($data == null) {
return false;
}
foreach ($data as $name => $value) {
$this->templateVars[$name] = $value;
}
}
/**
* Runs the template
*
* @param string $directory directory / type of thing you want
* @param string $filename template name
* @param string $vars Additional vars to set to template scope.
* @access public
* @return contents of generated code template
**/
function generate($directory, $filename, $vars = null) {
if ($vars !== null) {
$this->set($vars);
}
if (empty($this->templatePaths)) {
$this->initialize();
}
$themePath = $this->getThemePath();
$templateFile = $this->_findTemplate($themePath, $directory, $filename);
if ($templateFile) {
extract($this->templateVars);
ob_start();
ob_implicit_flush(0);
include($templateFile);
$content = ob_get_clean();
return $content;
}
return '';
}
/**
* Find the theme name for the current operation.
* If there is only one theme in $templatePaths it will be used.
* If there is a -theme param in the cli args, it will be used.
* If there is more than one installed theme user interaction will happen
*
* @return string returns the path to the selected theme.
**/
function getThemePath() {
if (count($this->templatePaths) == 1) {
$paths = array_values($this->templatePaths);
return $paths[0];
}
if (!empty($this->params['theme']) && isset($this->templatePaths[$this->params['theme']])) {
return $this->templatePaths[$this->params['theme']];
}
$this->hr();
$this->out(__('You have more than one set of templates installed.', true));
$this->out(__('Please choose the template set you wish to use:', true));
$this->hr();
$i = 1;
$indexedPaths = array();
foreach ($this->templatePaths as $key => $path) {
$this->out($i . '. ' . $key);
$indexedPaths[$i] = $path;
$i++;
}
$index = $this->in(__('Which bake theme would you like to use?', true), range(1, $i - 1), 1);
$themeNames = array_keys($this->templatePaths);
$this->Dispatch->params['theme'] = $themeNames[$index - 1];
return $indexedPaths[$index];
}
/**
* Find a template inside a directory inside a path.
* Will scan all other theme dirs if the template is not found in the first directory.
*
* @param string $path The initial path to look for the file on. If it is not found fallbacks will be used.
* @param string $directory Subdirectory to look for ie. 'views', 'objects'
* @param string $filename lower_case_underscored filename you want.
* @access public
* @return string filename will exit program if template is not found.
**/
function _findTemplate($path, $directory, $filename) {
$themeFile = $path . $directory . DS . $filename . '.ctp';
if (file_exists($themeFile)) {
return $themeFile;
}
foreach ($this->templatePaths as $path) {
$templatePath = $path . $directory . DS . $filename . '.ctp';
if (file_exists($templatePath)) {
return $templatePath;
}
}
$this->err(sprintf(__('Could not find template for %s', true), $filename));
$this->_stop();
return false;
}
}
?>

View file

@ -1,27 +1,21 @@
<?php <?php
/* SVN FILE: $Id$ */
/** /**
* The TestTask handles creating and updating test files. * The TestTask handles creating and updating test files.
* *
* Long description for file
*
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake * @package cake
* @subpackage cake.cake.console.libs.tasks * @subpackage cake.cake.console.libs.tasks
* @since CakePHP(tm) v 1.2 * @since CakePHP(tm) v 1.3
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
/** /**
@ -45,6 +39,31 @@ class TestTask extends Shell {
* @access public * @access public
*/ */
var $path = TESTS; var $path = TESTS;
/**
* Tasks used.
*
* @var array
**/
var $tasks = array('Template');
/**
* class types that methods can be generated for
*
* @var array
**/
var $classTypes = array('Model', 'Controller', 'Component', 'Behavior', 'Helper');
/**
* Internal list of fixtures that have been added so far.
*
* @var string
**/
var $_fixtures = array();
/**
* Flag for interactive mode
*
* @var boolean
**/
var $interactive = false;
/** /**
* Execution method always used for tasks * Execution method always used for tasks
* *
@ -60,8 +79,8 @@ class TestTask extends Shell {
} }
if (count($this->args) > 1) { if (count($this->args) > 1) {
$class = Inflector::underscore($this->args[0]); $type = Inflector::underscore($this->args[0]);
if ($this->bake($class, $this->args[1])) { if ($this->bake($type, $this->args[1])) {
$this->out('done'); $this->out('done');
} }
} }
@ -71,133 +90,304 @@ class TestTask extends Shell {
* *
* @access private * @access private
*/ */
function __interactive($class = null) { function __interactive($type = null) {
$this->interactive = true;
$this->hr(); $this->hr();
$this->out(sprintf("Bake Tests\nPath: %s", $this->path)); $this->out(__('Bake Tests', true));
$this->out(sprintf(__("Path: %s", true), $this->path));
$this->hr(); $this->hr();
$key = null; $selection = null;
$options = array('Behavior', 'Helper', 'Component', 'Model', 'Controller'); if ($type) {
$type = Inflector::camelize($type);
if ($class !== null) { if (!in_array($type, $this->classTypes)) {
$class = Inflector::camelize($class); unset($type);
if (in_array($class, $options)) {
$key = array_search($class);
} }
} }
if (!$type) {
while ($class == null) { $type = $this->getObjectType();
$cases = array();
$this->hr();
$this->out("Select a class:");
$this->hr();
$keys = array();
foreach ($options as $key => $option) {
$this->out(++$key . '. ' . $option);
$keys[] = $key;
}
$keys[] = 'q';
$key = $this->in(__("Enter the class to test or (q)uit", true), $keys, 'q');
if ($key != 'q') {
if (isset($options[--$key])) {
$class = $options[$key];
}
if ($class) {
$name = $this->in(__("Enter the name for the test or (q)uit", true), null, 'q');
if ($name !== 'q') {
$case = null;
while ($case !== 'q') {
$case = $this->in(__("Enter a test case or (q)uit", true), null, 'q');
if ($case !== 'q') {
$cases[] = $case;
}
}
if ($this->bake($class, $name, $cases)) {
$this->out(__("Test baked\n", true));
$type = null;
}
$class = null;
}
}
} else {
$this->_stop();
}
} }
$className = $this->getClassName($type);
return $this->bake($type, $className);
} }
/** /**
* Writes File * Completes final steps for generating data to create test case.
* *
* @param string $type Type of object to bake test case for ie. Model, Controller
* @param string $className the 'cake name' for the class ie. Posts for the PostsController
* @access public * @access public
*/ */
function bake($class, $name = null, $cases = array()) { function bake($type, $className) {
if (!$name) { if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($type, $className)) {
return false; $this->out(__('Bake is detecting possible fixtures..', true));
$testSubject =& $this->buildTestSubject($type, $className);
$this->generateFixtureList($testSubject);
} elseif ($this->interactive) {
$this->getUserFixtures();
}
$fullClassName = $this->getRealClassName($type, $className);
$methods = array();
if (class_exists($fullClassName)) {
$methods = $this->getTestableMethods($fullClassName);
}
$mock = $this->hasMockClass($type, $fullClassName);
$construction = $this->generateConstructor($type, $fullClassName);
$plugin = null;
if ($this->plugin) {
$plugin = $this->plugin . '.';
} }
if (!is_array($cases)) { $this->Template->set('fixtures', $this->_fixtures);
$cases = array($cases); $this->Template->set('plugin', $plugin);
} $this->Template->set(compact('className', 'methods', 'type', 'fullClassName', 'mock', 'construction'));
$out = $this->Template->generate('classes', 'test');
if (strpos($this->path, $class) === false) { $filename = $this->testCaseFileName($type, $className);
$this->filePath = $this->path . 'cases' . DS . Inflector::tableize($class) . DS; $made = $this->createFile($filename, $out);
if ($made) {
return $out;
} }
return false;
$class = Inflector::classify($class);
$name = Inflector::classify($name);
$import = $name;
if (isset($this->plugin)) {
$import = $this->plugin . '.' . $name;
}
$extras = $this->__extras($class);
$out = "App::import('$class', '$import');\n";
if ($class == 'Model') {
$class = null;
}
$out .= "class Test{$name} extends {$name}{$class} {\n";
$out .= "{$extras}";
$out .= "}\n\n";
$out .= "class {$name}{$class}Test extends CakeTestCase {\n";
$out .= "\n\tfunction startTest() {";
$out .= "\n\t\t\$this->{$name} = new Test{$name}();";
$out .= "\n\t}\n";
$out .= "\n\tfunction test{$name}Instance() {\n";
$out .= "\t\t\$this->assertTrue(is_a(\$this->{$name}, '{$name}{$class}'));\n\t}\n";
foreach ($cases as $case) {
$case = Inflector::classify($case);
$out .= "\n\tfunction test{$case}() {\n\n\t}\n";
}
$out .= "}\n";
$this->out("Baking unit test for $name...");
$this->out($out);
$ok = $this->in(__('Is this correct?', true), array('y', 'n'), 'y');
if ($ok == 'n') {
return false;
}
$header = '$Id';
$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $name ." Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
return $this->createFile($this->filePath . Inflector::underscore($name) . '.test.php', $content);
} }
/** /**
* Handles the extra stuff needed * Interact with the user and get their chosen type. Can exit the script.
* *
* @access private * @return string Users chosen type.
*/ **/
function __extras($class) { function getObjectType() {
$extras = null; $this->hr();
switch ($class) { $this->out(__("Select an object type:", true));
case 'Model': $this->hr();
$extras = "\n\tvar \$cacheSources = false;";
$extras .= "\n\tvar \$useDbConfig = 'test_suite';\n"; $keys = array();
break; foreach ($this->classTypes as $key => $option) {
$this->out(++$key . '. ' . $option);
$keys[] = $key;
} }
return $extras; $keys[] = 'q';
$selection = $this->in(__("Enter the type of object to bake a test for or (q)uit", true), $keys, 'q');
if ($selection == 'q') {
return $this->_stop();
}
return $this->classTypes[$selection - 1];
}
/**
* Get the user chosen Class name for the chosen type
*
* @param string $objectType Type of object to list classes for i.e. Model, Controller.
* @return string Class name the user chose.
**/
function getClassName($objectType) {
$options = Configure::listObjects(strtolower($objectType));
$this->out(sprintf(__('Choose a %s class', true), $objectType));
$keys = array();
foreach ($options as $key => $option) {
$this->out(++$key . '. ' . $option);
$keys[] = $key;
}
$selection = $this->in(__('Choose an existing class, or enter the name of a class that does not exist', true));
if (isset($options[$selection - 1])) {
return $options[$selection - 1];
}
return $selection;
}
/**
* Checks whether the chosen type can find its own fixtures.
* Currently only model, and controller are supported
*
* @return boolean
**/
function typeCanDetectFixtures($type) {
$type = strtolower($type);
return ($type == 'controller' || $type == 'model');
}
/**
* Check if a class with the given type is loaded or can be loaded.
*
* @return boolean
**/
function isLoadableClass($type, $class) {
return App::import($type, $class);
}
/**
* Construct an instance of the class to be tested.
* So that fixtures can be detected
*
* @return object
**/
function &buildTestSubject($type, $class) {
ClassRegistry::flush();
App::import($type, $class);
$class = $this->getRealClassName($type, $class);
if (strtolower($type) == 'model') {
$instance =& ClassRegistry::init($class);
} else {
$instance =& new $class();
}
return $instance;
}
/**
* Gets the real class name from the cake short form.
*
* @return string Real classname
**/
function getRealClassName($type, $class) {
if (strtolower($type) == 'model') {
return $class;
}
return $class . $type;
}
/**
* Get methods declared in the class given.
* No parent methods will be returned
*
* @param string $className Name of class to look at.
* @return array Array of method names.
**/
function getTestableMethods($className) {
$classMethods = get_class_methods($className);
$parentMethods = get_class_methods(get_parent_class($className));
$thisMethods = array_diff($classMethods, $parentMethods);
$out = array();
foreach ($thisMethods as $method) {
if (substr($method, 0, 1) != '_') {
$out[] = $method;
}
}
return $out;
}
/**
* Generate the list of fixtures that will be required to run this test based on
* loaded models.
*
* @param object The object you want to generate fixtures for.
* @return array Array of fixtures to be included in the test.
**/
function generateFixtureList(&$subject) {
$this->_fixtures = array();
if (is_a($subject, 'Model')) {
$this->_processModel($subject);
} elseif (is_a($subject, 'Controller')) {
$this->_processController($subject);
}
return array_values($this->_fixtures);
}
/**
* Process a model recursively and pull out all the
* model names converting them to fixture names.
*
* @return void
* @access protected
**/
function _processModel(&$subject) {
$this->_addFixture($subject->name);
$associated = $subject->getAssociated();
foreach ($associated as $alias => $type) {
$className = $subject->{$alias}->name;
if (!isset($this->_fixtures[$className])) {
$this->_processModel($subject->{$alias});
}
if ($type == 'hasAndBelongsToMany') {
$joinModel = Inflector::classify($subject->hasAndBelongsToMany[$alias]['joinTable']);
if (!isset($this->_fixtures[$joinModel])) {
$this->_processModel($subject->{$joinModel});
}
}
}
}
/**
* Process all the models attached to a controller
* and generate a fixture list.
*
* @return void
* @access protected
**/
function _processController(&$subject) {
$subject->constructClasses();
$models = array(Inflector::classify($subject->name));
if (!empty($subject->uses)) {
$models = $subject->uses;
}
foreach ($models as $model) {
$this->_processModel($subject->{$model});
}
}
/**
* Add classname to the fixture list.
* Sets the app. or plugin.plugin_name. prefix.
*
* @return void
* @access protected
**/
function _addFixture($name) {
$parent = get_parent_class($name);
$prefix = 'app.';
if (strtolower($parent) != 'appmodel' && strtolower(substr($parent, -8)) == 'appmodel') {
$pluginName = substr($parent, 0, strlen($parent) -8);
$prefix = 'plugin.' . Inflector::underscore($pluginName) . '.';
}
$fixture = $prefix . Inflector::underscore($name);
$this->_fixtures[$name] = $fixture;
}
/**
* Interact with the user to get additional fixtures they want to use.
*
* @return void
**/
function getUserFixtures() {
$proceed = $this->in(__('Bake could not detect fixtures, would you like to add some?', true), array('y','n'), 'n');
$fixtures = array();
if (strtolower($proceed) == 'y') {
$fixtureList = $this->in(__("Please provide a comma separated list of the fixtures names you'd like to use.\nExample: 'app.comment, app.post, plugin.forums.post'", true));
$fixtureListTrimmed = str_replace(' ', '', $fixtureList);
$fixtures = explode(',', $fixtureListTrimmed);
}
$this->_fixtures = array_merge($this->_fixtures, $fixtures);
return $fixtures;
}
/**
* Is a mock class required for this type of test?
* Controllers require a mock class.
*
* @return boolean
**/
function hasMockClass($type) {
$type = strtolower($type);
return $type == 'controller';
}
/**
* Generate a constructor code snippet for the type and classname
*
* @return string Constructor snippet for the thing you are building.
**/
function generateConstructor($type, $fullClassName) {
$type = strtolower($type);
if ($type == 'model') {
return "ClassRegistry::init('$fullClassName');\n";
}
if ($type == 'controller') {
return "new Test$fullClassName();\n\t\t\$this->{$fullClassName}->constructClasses();\n";
}
return "new $fullClassName()\n";
}
/**
* make the filename for the test case. resolve the suffixes for controllers
* and get the plugin path if needed.
*
* @return string filename the test should be created on
**/
function testCaseFileName($type, $className) {
$path = $this->path;
if (isset($this->plugin)) {
$path = $this->_pluginPath($this->plugin) . 'tests' . DS;
}
$path .= 'cases' . DS . Inflector::tableize($type) . DS;
if (strtolower($type) == 'controller') {
$className = $this->getRealClassName($type, $className);
}
return $path . Inflector::underscore($className) . '.test.php';
} }
} }
?> ?>

View file

@ -1,5 +1,4 @@
<?php <?php
/* SVN FILE: $Id$ */
/** /**
* The View Tasks handles creating and updating view files. * The View Tasks handles creating and updating view files.
* *
@ -8,20 +7,17 @@
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org) * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake * @package cake
* @subpackage cake.cake.console.libs.tasks * @subpackage cake.cake.console.libs.tasks
* @since CakePHP(tm) v 1.2 * @since CakePHP(tm) v 1.2
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
App::import('Core', 'Controller'); App::import('Core', 'Controller');
@ -45,7 +41,7 @@ class ViewTask extends Shell {
* @var array * @var array
* @access public * @access public
*/ */
var $tasks = array('Project', 'Controller'); var $tasks = array('Project', 'Controller', 'DbConfig', 'Template');
/** /**
* path to VIEWS directory * path to VIEWS directory
* *
@ -99,6 +95,9 @@ class ViewTask extends Shell {
} }
if (isset($this->args[0])) { if (isset($this->args[0])) {
if (!isset($this->connection)) {
$this->connection = 'default';
}
$controller = $action = $alias = null; $controller = $action = $alias = null;
$this->controllerName = Inflector::camelize($this->args[0]); $this->controllerName = Inflector::camelize($this->args[0]);
$this->controllerPath = Inflector::underscore($this->controllerName); $this->controllerPath = Inflector::underscore($this->controllerName);
@ -115,34 +114,86 @@ class ViewTask extends Shell {
$action = $this->template; $action = $this->template;
} }
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
if (in_array($action, $this->scaffoldActions)) { if (in_array($action, $this->scaffoldActions)) {
$this->bake($action, true); $this->bake($action, true);
} elseif ($action) { } elseif ($action) {
$this->bake($action, true); $this->bake($action, true);
} else { } else {
$vars = $this->__loadController(); $vars = $this->__loadController();
if ($vars) { $methods = $this->_methodsToBake();
$methods = array_diff(
$methods = array_diff( array_map('strtolower', get_class_methods($this->controllerName . 'Controller')),
array_map('strtolower', get_class_methods($this->controllerName . 'Controller')), array_map('strtolower', get_class_methods('appcontroller'))
array_map('strtolower', get_class_methods('appcontroller')) );
); if (empty($methods)) {
if (empty($methods)) { $methods = $this->scaffoldActions;
$methods = $this->scaffoldActions; }
} $adminRoute = Configure::read('Routing.admin');
$adminDelete = null; if ($adminRoute && isset($this->params['admin'])) {
foreach ($methods as $i => $method) {
$adminRoute = Configure::read('Routing.admin'); if (strpos($method, $adminRoute . '_') === false) {
if (!empty($adminRoute)) { unset($methods[$i]);
$adminDelete = $adminRoute.'_delete';
}
foreach ($methods as $method) {
if ($method{0} != '_' && !in_array($method, array('delete', $adminDelete))) {
$content = $this->getContent($method, $vars);
$this->bake($method, $content);
} }
} }
} }
$adminDelete = null;
if (!empty($adminRoute)) {
$adminDelete = $adminRoute . '_delete';
}
foreach ($methods as $method) {
if ($method{0} != '_' && !in_array($method, array('delete', $adminDelete))) {
$content = $this->getContent($method, $vars);
$this->bake($method, $content);
}
}
}
}
}
/**
* Get a list of actions that can / should have views baked for them.
*
* @return array Array of action names that should be baked
**/
function _methodsToBake() {
$methods = array_diff(
array_map('strtolower', get_class_methods($this->controllerName . 'Controller')),
array_map('strtolower', get_class_methods('appcontroller'))
);
if (empty($methods)) {
$methods = $this->scaffoldActions;
}
$adminRoute = Configure::read('Routing.admin');
foreach ($methods as $i => $method) {
if ($method == 'delete' || $method = $adminRoute . '_delete' || $method{0} == '_') {
unset($methods[$i]);
}
if ($adminRoute && isset($this->params['admin']) && strpos($method, $adminRoute . '_') === false) {
unset($methods[$i]);
}
}
return $methods;
}
/**
* Bake All views for All controllers.
*
* @return void
**/
function all() {
$actions = $this->scaffoldActions;
$this->Controller->interactive = false;
$tables = $this->Controller->listAll($this->connection, false);
$this->interactive = false;
foreach ($tables as $table) {
$model = $this->_modelName($table);
$this->controllerName = $this->_controllerName($model);
$this->controllerPath = Inflector::underscore($this->controllerName);
if (App::import('Model', $model)) {
$vars = $this->__loadController();
$this->bakeActions($actions, $vars);
} }
} }
} }
@ -155,70 +206,48 @@ class ViewTask extends Shell {
$this->hr(); $this->hr();
$this->out(sprintf("Bake View\nPath: %s", $this->path)); $this->out(sprintf("Bake View\nPath: %s", $this->path));
$this->hr(); $this->hr();
$wannaDoAdmin = 'n';
$wannaDoScaffold = 'y';
$this->interactive = false;
if (empty($this->connection)) {
$this->connection = $this->DbConfig->getConfig();
}
$this->Controller->connection = $this->connection;
$this->controllerName = $this->Controller->getName(); $this->controllerName = $this->Controller->getName();
$this->controllerPath = low(Inflector::underscore($this->controllerName)); $this->controllerPath = strtolower(Inflector::underscore($this->controllerName));
$interactive = $this->in("Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite {$this->controllerName} views if it exist.", array('y','n'), 'y'); $prompt = sprintf(__("Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist.", true), $this->controllerName);
$interactive = $this->in($prompt, array('y', 'n'), 'n');
if (low($interactive) == 'y' || low($interactive) == 'yes') { if (strtolower($interactive) == 'n') {
$this->interactive = true; $this->interactive = false;
$wannaDoScaffold = $this->in("Would you like to create some scaffolded views (index, add, view, edit) for this controller?\nNOTE: Before doing so, you'll need to create your controller and model classes (including associated models).", array('y','n'), 'n');
} }
if (low($wannaDoScaffold) == 'y' || low($wannaDoScaffold) == 'yes') { $prompt = __("Would you like to create some CRUD views\n(index, add, view, edit) for this controller?\nNOTE: Before doing so, you'll need to create your controller\nand model classes (including associated models).", true);
$wannaDoAdmin = $this->in("Would you like to create the views for admin routing?", array('y','n'), 'y'); $wannaDoScaffold = $this->in($prompt, array('y','n'), 'y');
}
$admin = false;
if ((low($wannaDoAdmin) == 'y' || low($wannaDoAdmin) == 'yes')) { $wannaDoAdmin = $this->in(__("Would you like to create the views for admin routing?", true), array('y','n'), 'n');
$admin = $this->getAdmin();
}
if (low($wannaDoScaffold) == 'y' || low($wannaDoScaffold) == 'yes') { if (strtolower($wannaDoScaffold) == 'y' || strtolower($wannaDoAdmin) == 'y') {
$actions = $this->scaffoldActions;
if ($admin) {
foreach ($actions as $action) {
$actions[] = $admin . $action;
}
}
$vars = $this->__loadController(); $vars = $this->__loadController();
if ($vars) { if (strtolower($wannaDoScaffold) == 'y') {
foreach ($actions as $action) { $actions = $this->scaffoldActions;
$content = $this->getContent($action, $vars); $this->bakeActions($actions, $vars);
$this->bake($action, $content); }
if (strtolower($wannaDoAdmin) == 'y') {
$admin = $this->Project->getAdmin();
$regularActions = $this->scaffoldActions;
$adminActions = array();
foreach ($regularActions as $action) {
$adminActions[] = $admin . $action;
} }
$this->bakeActions($adminActions, $vars);
} }
$this->hr(); $this->hr();
$this->out(''); $this->out('');
$this->out('View Scaffolding Complete.'."\n"); $this->out(__("View Scaffolding Complete.\n", true));
} else { } else {
$action = ''; $this->customAction();
while ($action == '') {
$action = $this->in('Action Name? (use camelCased function name)');
if ($action == '') {
$this->out('The action name you supplied was empty. Please try again.');
}
}
$this->out('');
$this->hr();
$this->out('The following view will be created:');
$this->hr();
$this->out("Controller Name: {$this->controllerName}");
$this->out("Action Name: {$action}");
$this->out("Path: ".$this->params['app'] . DS . $this->controllerPath . DS . Inflector::underscore($action) . ".ctp");
$this->hr();
$looksGood = $this->in('Look okay?', array('y','n'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
$this->bake($action);
$this->_stop();
} else {
$this->out('Bake Aborted.');
}
} }
} }
/** /**
@ -247,7 +276,7 @@ class ViewTask extends Shell {
$this->_stop(); $this->_stop();
} }
$controllerClassName = $this->controllerName . 'Controller'; $controllerClassName = $this->controllerName . 'Controller';
$controllerObj = & new $controllerClassName(); $controllerObj =& new $controllerClassName();
$controllerObj->constructClasses(); $controllerObj->constructClasses();
$modelClass = $controllerObj->modelClass; $modelClass = $controllerObj->modelClass;
$modelObj =& ClassRegistry::getObject($controllerObj->modelKey); $modelObj =& ClassRegistry::getObject($controllerObj->modelKey);
@ -277,6 +306,47 @@ class ViewTask extends Shell {
return compact('modelClass', 'schema', 'primaryKey', 'displayField', 'singularVar', 'pluralVar', return compact('modelClass', 'schema', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
'singularHumanName', 'pluralHumanName', 'fields','associations'); 'singularHumanName', 'pluralHumanName', 'fields','associations');
} }
/**
* Bake a view file for each of the supplied actions
*
* @param array $actions Array of actions to make files for.
* @return void
**/
function bakeActions($actions, $vars) {
foreach ($actions as $action) {
$content = $this->getContent($action, $vars);
$this->bake($action, $content);
}
}
/**
* handle creation of baking a custom action view file
*
* @return void
**/
function customAction() {
$action = '';
while ($action == '') {
$action = $this->in(__('Action Name? (use lowercase_underscored function name)', true));
if ($action == '') {
$this->out(__('The action name you supplied was empty. Please try again.', true));
}
}
$this->out('');
$this->hr();
$this->out(__('The following view will be created:', true));
$this->hr();
$this->out(sprintf(__('Controller Name: %s', true), $this->controllerName));
$this->out(sprintf(__('Action Name: %s', true), $action));
$this->out(sprintf(__('Path: %s', true), $this->params['app'] . DS . $this->controllerPath . DS . Inflector::underscore($action) . ".ctp"));
$this->hr();
$looksGood = $this->in(__('Look okay?', true), array('y','n'), 'y');
if (strtolower($looksGood) == 'y') {
$this->bake($action);
$this->_stop();
} else {
$this->out(__('Bake Aborted.', true));
}
}
/** /**
* Assembles and writes bakes the view file. * Assembles and writes bakes the view file.
* *
@ -287,20 +357,14 @@ class ViewTask extends Shell {
*/ */
function bake($action, $content = '') { function bake($action, $content = '') {
if ($content === true) { if ($content === true) {
$content = $this->getContent(); $content = $this->getContent($action);
} }
$filename = $this->path . $this->controllerPath . DS . Inflector::underscore($action) . '.ctp'; $path = $this->path;
$Folder =& new Folder($this->path . $this->controllerPath, true); if (isset($this->plugin)) {
$errors = $Folder->errors(); $path = $this->_pluginPath($this->plugin) . 'views' . DS;
if (empty($errors)) {
$path = $Folder->slashTerm($Folder->pwd());
return $this->createFile($filename, $content);
} else {
foreach ($errors as $error) {
$this->err($error);
}
} }
return false; $filename = $path . $this->controllerPath . DS . Inflector::underscore($action) . '.ctp';
return $this->createFile($filename, $content);
} }
/** /**
* Builds content from template and variables * Builds content from template and variables
@ -318,30 +382,23 @@ class ViewTask extends Shell {
$adminRoute = Configure::read('Routing.admin'); $adminRoute = Configure::read('Routing.admin');
if (!empty($adminRoute) && strpos($template, $adminRoute) !== false) { if (!empty($adminRoute) && strpos($template, $adminRoute) !== false) {
$template = str_replace($adminRoute.'_', '', $template); $template = str_replace($adminRoute . '_', '', $template);
} }
if (in_array($template, array('add', 'edit'))) { if (in_array($template, array('add', 'edit'))) {
$action = $template; $action = $template;
$template = 'form'; $template = 'form';
} }
$loaded = false;
foreach ($this->Dispatch->shellPaths as $path) {
$templatePath = $path . 'templates' . DS . 'views' . DS .Inflector::underscore($template).'.ctp';
if (file_exists($templatePath) && is_file($templatePath)) {
$loaded = true;
break;
}
}
if (!$vars) { if (!$vars) {
$vars = $this->__loadController(); $vars = $this->__loadController();
} }
if ($loaded) {
extract($vars); $this->Template->set('action', $action);
ob_start(); $this->Template->set('plugin', $this->plugin);
ob_implicit_flush(0); $this->Template->set($vars);
include($templatePath); $output = $this->Template->generate('views', $template);
$content = ob_get_clean();
return $content; if (!empty($output)) {
return $output;
} }
$this->hr(); $this->hr();
$this->err(sprintf(__('Template for %s could not be found', true), $template)); $this->err(sprintf(__('Template for %s could not be found', true), $template));
@ -357,10 +414,25 @@ class ViewTask extends Shell {
$this->out("Usage: cake bake view <arg1> <arg2>..."); $this->out("Usage: cake bake view <arg1> <arg2>...");
$this->hr(); $this->hr();
$this->out('Commands:'); $this->out('Commands:');
$this->out("\n\tview <controller>\n\t\twill read the given controller for methods\n\t\tand bake corresponding views.\n\t\tIf var scaffold is found it will bake the scaffolded actions\n\t\t(index,view,add,edit)"); $this->out('');
$this->out("\n\tview <controller> <action>\n\t\twill bake a template. core templates: (index, add, edit, view)"); $this->out("view <controller>");
$this->out("\n\tview <controller> <template> <alias>\n\t\twill use the template specified but name the file based on the alias"); $this->out("\tWill read the given controller for methods");
$this->out(""); $this->out("\tand bake corresponding views.");
$this->out("\tUsing the -admin flag will only bake views for actions");
$this->out("\tthat begin with Routing.admin.");
$this->out("\tIf var scaffold is found it will bake the CRUD actions");
$this->out("\t(index,view,add,edit)");
$this->out('');
$this->out("view <controller> <action>");
$this->out("\tWill bake a template. core templates: (index, add, edit, view)");
$this->out('');
$this->out("view <controller> <template> <alias>");
$this->out("\tWill use the template specified");
$this->out("\tbut name the file based on the alias");
$this->out('');
$this->out("view all");
$this->out("\tBake all CRUD action views for all controllers.");
$this->out("\tRequires that models and controllers exist.");
$this->_stop(); $this->_stop();
} }
/** /**

View file

@ -0,0 +1,142 @@
<?php
/**
* Bake Template for Controller action generation.
*
*
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.console.libs.template.objects
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
function <?php echo $admin ?>index() {
$this-><?php echo $currentModelName ?>->recursive = 0;
$this->set('<?php echo $pluralName ?>', $this->paginate());
}
function <?php echo $admin ?>view($id = null) {
if (!$id) {
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('Invalid <?php echo $singularHumanName ?>', true));
$this->redirect(array('action' => 'index'));
<?php else: ?>
$this->flash(__('Invalid <?php echo $singularHumanName; ?>', true), array('action' => 'index'));
<?php endif; ?>
}
$this->set('<?php echo $singularName; ?>', $this-><?php echo $currentModelName; ?>->read(null, $id));
}
<?php $compact = array(); ?>
function <?php echo $admin ?>add() {
if (!empty($this->data)) {
$this-><?php echo $currentModelName; ?>->create();
if ($this-><?php echo $currentModelName; ?>->save($this->data)) {
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('The <?php echo $singularHumanName; ?> has been saved', true));
$this->redirect(array('action' => 'index'));
<?php else: ?>
$this->flash(__('<?php echo $currentModelName; ?> saved.', true), array('action' => 'index'));
<?php endif; ?>
} else {
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('The <?php echo $singularHumanName; ?> could not be saved. Please, try again.', true));
<?php endif; ?>
}
}
<?php
foreach (array('belongsTo', 'hasAndBelongsToMany') as $assoc):
foreach ($modelObj->{$assoc} as $associationName => $relation):
if (!empty($associationName)):
$otherModelName = $this->_modelName($associationName);
$otherPluralName = $this->_pluralName($associationName);
echo "\t\t\${$otherPluralName} = \$this->{$currentModelName}->{$otherModelName}->find('list');\n";
$compact[] = "'{$otherPluralName}'";
endif;
endforeach;
endforeach;
if (!empty($compact)):
echo "\t\t\$this->set(compact(".join(', ', $compact)."));\n";
endif;
?>
}
<?php $compact = array(); ?>
function <?php echo $admin; ?>edit($id = null) {
if (!$id && empty($this->data)) {
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('Invalid <?php echo $singularHumanName; ?>', true));
$this->redirect(array('action' => 'index'));
<?php else: ?>
$this->flash(__('Invalid <?php echo $singularHumanName; ?>', true), array('action' => 'index'));
<?php endif; ?>
}
if (!empty($this->data)) {
if ($this-><?php echo $currentModelName; ?>->save($this->data)) {
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('The <?php echo $singularHumanName; ?> has been saved', true));
$this->redirect(array('action' => 'index'));
<?php else: ?>
$this->flash(__('The <?php echo $singularHumanName; ?> has been saved.', true), array('action' => 'index'));
<?php endif; ?>
} else {
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('The <?php echo $singularHumanName; ?> could not be saved. Please, try again.', true));
<?php endif; ?>
}
}
if (empty($this->data)) {
$this->data = $this-><?php echo $currentModelName; ?>->read(null, $id);
}
<?php
foreach (array('belongsTo', 'hasAndBelongsToMany') as $assoc):
foreach ($modelObj->{$assoc} as $associationName => $relation):
if (!empty($associationName)):
$otherModelName = $this->_modelName($associationName);
$otherPluralName = $this->_pluralName($associationName);
echo "\t\t\${$otherPluralName} = \$this->{$currentModelName}->{$otherModelName}->find('list');\n";
$compact[] = "'{$otherPluralName}'";
endif;
endforeach;
endforeach;
if (!empty($compact)):
echo "\t\t\$this->set(compact(".join(', ', $compact)."));\n";
endif;
?>
}
function <?php echo $admin; ?>delete($id = null) {
if (!$id) {
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('Invalid id for <?php echo $singularHumanName; ?>', true));
$this->redirect(array('action'=>'index'));
<?php else: ?>
$this->flash(__('Invalid <?php echo $singularHumanName; ?>', true), array('action' => 'index'));
<?php endif; ?>
}
if ($this-><?php echo $currentModelName; ?>->del($id)) {
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('<?php echo $singularHumanName; ?> deleted', true));
$this->redirect(array('action'=>'index'));
<?php else: ?>
$this->flash(__('<?php echo $singularHumanName; ?> deleted', true), array('action' => 'index'));
<?php endif; ?>
}
<?php if ($wannaUseSession): ?>
$this->Session->setFlash(__('<?php echo $singularHumanName; ?> was not deleted', true));
<?php else: ?>
$this->flash(__('<?php echo $singularHumanName; ?> was not deleted', true), array('action' => 'index'));
<?php endif; ?>
$this->redirect(array('action' => 'index'));
}

View file

@ -0,0 +1,57 @@
<?php
/**
* Controller bake template file
*
* Allows templating of Controllers generated from bake.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
echo "<?php\n";
?>
class <?php echo $controllerName; ?>Controller extends <?php echo $plugin; ?>AppController {
var $name = '<?php echo $controllerName; ?>';
<?php if ($isScaffold): ?>
var $scaffold;
<?php else: ?>
<?php
echo "\tvar \$helpers = array('Html', 'Form'";
if (count($helpers)):
foreach ($helpers as $help):
echo ", '" . Inflector::camelize($help) . "'";
endforeach;
endif;
echo ");\n";
if (count($components)):
echo "\tvar \$components = array(";
for ($i = 0, $len = count($components); $i < $len; $i++):
if ($i != $len - 1):
echo "'" . Inflector::camelize($components[$i]) . "', ";
else:
echo "'" . Inflector::camelize($components[$i]) . "'";
endif;
endfor;
echo ");\n";
endif;
echo $actions;
endif; ?>
}
<?php echo "?>"; ?>

View file

@ -0,0 +1,42 @@
<?php
/**
* Fixture Template file
*
* Fixture Template used when baking fixtures with bake
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php echo '<?php' . "\n"; ?>
/* <?php echo $model; ?> Fixture generated on: <?php echo date('Y-m-d H:m:s') . " : ". time(); ?> */
class <?php echo $model; ?>Fixture extends CakeTestFixture {
var $name = '<?php echo $model; ?>';
<?php if ($table): ?>
var $table = '<?php echo $table; ?>';
<?php endif; ?>
<?php if ($import): ?>
var $import = <?php echo $import; ?>;
<?php endif; ?>
<?php if ($schema): ?>
var $fields = <?php echo $schema; ?>;
<?php endif;?>
<?php if ($records): ?>
var $records = <?php echo $records; ?>;
<?php endif;?>
}
<?php echo '?>'; ?>

View file

@ -0,0 +1,130 @@
<?php
/**
* Model template file.
*
* Used by bake to create new Model files.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.console.libs.templates.objects
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
echo "<?php\n"; ?>
class <?php echo $name ?> extends <?php echo $plugin; ?>AppModel {
var $name = '<?php echo $name; ?>';
<?php if ($useDbConfig != 'default'): ?>
var $useDbConfig = '<?php echo $useDbConfig; ?>';
<?php endif;?>
<?php if ($useTable && $useTable !== Inflector::tableize($name)):
$table = "'$useTable'";
echo "\tvar \$useTable = $table;\n";
endif;
if ($primaryKey !== 'id'): ?>
var $primaryKey = '<?php echo $primaryKey; ?>';
<?php endif;
if ($displayField): ?>
var $displayField = '<?php echo $displayField; ?>';
<?php endif;
if (!empty($validate)):
echo "\tvar \$validate = array(\n";
foreach ($validate as $field => $validations):
echo "\t\t'$field' => array(\n";
foreach ($validations as $key => $validator):
echo "\t\t\t'$key' => array('rule' => array('$validator')),\n";
endforeach;
echo "\t\t),\n";
endforeach;
echo "\t);\n";
endif;
?>
//The Associations below have been created with all possible keys, those that are not needed can be removed
<?php
foreach (array('hasOne', 'belongsTo') as $assocType):
if (!empty($associations[$assocType])):
$typeCount = count($associations[$assocType]);
echo "\n\tvar \$$assocType = array(";
foreach ($associations[$assocType] as $i => $relation):
$out = "\n\t\t'{$relation['alias']}' => array(\n";
$out .= "\t\t\t'className' => '{$relation['className']}',\n";
$out .= "\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n";
$out .= "\t\t\t'conditions' => '',\n";
$out .= "\t\t\t'fields' => '',\n";
$out .= "\t\t\t'order' => ''\n";
$out .= "\t\t)";
if ($i + 1 < $typeCount) {
$out .= ",";
}
echo $out;
endforeach;
echo "\n\t);\n";
endif;
endforeach;
if (!empty($associations['hasMany'])):
$belongsToCount = count($associations['hasMany']);
echo "\n\tvar \$hasMany = array(";
foreach ($associations['hasMany'] as $i => $relation):
$out = "\n\t\t'{$relation['alias']}' => array(\n";
$out .= "\t\t\t'className' => '{$relation['className']}',\n";
$out .= "\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n";
$out .= "\t\t\t'dependent' => false,\n";
$out .= "\t\t\t'conditions' => '',\n";
$out .= "\t\t\t'fields' => '',\n";
$out .= "\t\t\t'order' => '',\n";
$out .= "\t\t\t'limit' => '',\n";
$out .= "\t\t\t'offset' => '',\n";
$out .= "\t\t\t'exclusive' => '',\n";
$out .= "\t\t\t'finderQuery' => '',\n";
$out .= "\t\t\t'counterQuery' => ''\n";
$out .= "\t\t)";
if ($i + 1 < $belongsToCount) {
$out .= ",";
}
echo $out;
endforeach;
echo "\n\t);\n\n";
endif;
if (!empty($associations['hasAndBelongsToMany'])):
$habtmCount = count($associations['hasAndBelongsToMany']);
echo "\n\tvar \$hasAndBelongsToMany = array(";
foreach ($associations['hasAndBelongsToMany'] as $i => $relation):
$out = "\n\t\t'{$relation['alias']}' => array(\n";
$out .= "\t\t\t'className' => '{$relation['className']}',\n";
$out .= "\t\t\t'joinTable' => '{$relation['joinTable']}',\n";
$out .= "\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n";
$out .= "\t\t\t'associationForeignKey' => '{$relation['associationForeignKey']}',\n";
$out .= "\t\t\t'unique' => true,\n";
$out .= "\t\t\t'conditions' => '',\n";
$out .= "\t\t\t'fields' => '',\n";
$out .= "\t\t\t'order' => '',\n";
$out .= "\t\t\t'limit' => '',\n";
$out .= "\t\t\t'offset' => '',\n";
$out .= "\t\t\t'finderQuery' => '',\n";
$out .= "\t\t\t'deleteQuery' => '',\n";
$out .= "\t\t\t'insertQuery' => ''\n";
$out .= "\t\t)";
if ($i + 1 < $habtmCount) {
$out .= ",";
}
echo $out;
endforeach;
echo "\n\t);\n\n";
endif;
?>
}
<?php echo '?>'; ?>

View file

@ -0,0 +1,57 @@
<?php
/**
* Test Case bake template
*
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.console.libs.templates.objects
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
echo "<?php\n";
echo "/* ". $className ." Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n";
?>
App::import('<?php echo $type; ?>', '<?php echo $plugin . $className;?>');
<?php if ($mock and strtolower($type) == 'controller'): ?>
class Test<?php echo $fullClassName; ?> extends <?php echo $fullClassName; ?> {
var $autoRender = false;
function redirect($url, $status = null, $exit = true) {
$this->redirectUrl = $url;
}
}
<?php endif; ?>
class <?php echo $fullClassName; ?>TestCase extends CakeTestCase {
<?php if (!empty($fixtures)): ?>
var $fixtures = array('<?php echo join("', '", $fixtures); ?>');
<?php endif; ?>
function startTest() {
$this-><?php echo $className . ' =& ' . $construction; ?>
}
function endTest() {
unset($this-><?php echo $className;?>);
ClassRegistry::flush();
}
<?php foreach ($methods as $method): ?>
function test<?php echo Inflector::classify($method); ?>() {
}
<?php endforeach;?>
}
<?php echo '?>'; ?>

View file

@ -86,7 +86,7 @@ if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR); trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
} }
$corePath = Configure::corePaths('cake'); $corePath = App::core('cake');
if (isset($corePath[0])) { if (isset($corePath[0])) {
define('TEST_CAKE_CORE_INCLUDE_PATH', rtrim($corePath[0], DS) . DS); define('TEST_CAKE_CORE_INCLUDE_PATH', rtrim($corePath[0], DS) . DS);
} else { } else {

View file

@ -81,7 +81,7 @@ class TestSuiteShell extends Shell {
* @access public * @access public
*/ */
function initialize() { function initialize() {
$corePath = Configure::corePaths('cake'); $corePath = App::core('cake');
if (isset($corePath[0])) { if (isset($corePath[0])) {
define('TEST_CAKE_CORE_INCLUDE_PATH', rtrim($corePath[0], DS) . DS); define('TEST_CAKE_CORE_INCLUDE_PATH', rtrim($corePath[0], DS) . DS);
} else { } else {

View file

@ -515,10 +515,10 @@ class Dispatcher extends Object {
parse_str($uri[1], $_GET); parse_str($uri[1], $_GET);
} }
$uri = $uri[0]; $uri = $uri[0];
} elseif (empty($uri) && is_string(env('QUERY_STRING'))) { } else {
$uri = env('QUERY_STRING'); $uri = env('QUERY_STRING');
} }
if (strpos($uri, 'index.php') !== false) { if (is_string($uri) && strpos($uri, 'index.php') !== false) {
list(, $uri) = explode('index.php', $uri, 2); list(, $uri) = explode('index.php', $uri, 2);
} }
if (empty($uri) || $uri == '/' || $uri == '//') { if (empty($uri) || $uri == '/' || $uri == '//') {

View file

@ -192,7 +192,7 @@ class Cache extends Object {
} }
$settings = array_merge($_this->__config[$_this->__name], $settings); $settings = array_merge($_this->__config[$_this->__name], $settings);
} }
$_this->_Engine[$engine]->init($settings); $_this->engine($engine, $settings);
} }
return $_this->settings($engine); return $_this->settings($engine);

View file

@ -502,7 +502,7 @@ class CakeSession extends Object {
case 'cache': case 'cache':
if (empty($_SESSION)) { if (empty($_SESSION)) {
if (!class_exists('Cache')) { if (!class_exists('Cache')) {
uses('Cache'); require LIBS . 'cache.php';
} }
if ($iniSet) { if ($iniSet) {
ini_set('session.use_trans_sid', 0); ini_set('session.use_trans_sid', 0);

View file

@ -120,7 +120,11 @@ class CakeSocket extends Object {
$this->setLastError($errStr, $errNum); $this->setLastError($errStr, $errNum);
} }
return $this->connected = is_resource($this->connection); $this->connected = is_resource($this->connection);
if ($this->connected) {
stream_set_timeout($this->connection, $this->config['timeout']);
}
return $this->connected;
} }
/** /**
@ -218,7 +222,13 @@ class CakeSocket extends Object {
} }
if (!feof($this->connection)) { if (!feof($this->connection)) {
return fread($this->connection, $length); $buffer = fread($this->connection, $length);
$info = stream_get_meta_data($this->connection);
if ($info['timed_out']) {
$this->setLastError(E_WARNING, __('Connection timed out', true));
return false;
}
return $buffer;
} else { } else {
return false; return false;
} }

View file

@ -92,19 +92,15 @@ class Configure extends Object {
$config = array($config => $value); $config = array($config => $value);
} }
foreach ($config as $names => $value) { foreach ($config as $name => $value) {
$name = $_this->__configVarNames($names); if (strpos($name, '.') === false) {
$_this->{$name} = $value;
switch (count($name)) { } else {
case 3: $names = explode('.', $name, 2);
$_this->{$name[0]}[$name[1]][$name[2]] = $value; if (!isset($_this->{$names[0]})) {
break; $_this->{$names[0]} = array();
case 2: }
$_this->{$name[0]}[$name[1]] = $value; $_this->{$names[0]} = Set::insert($_this->{$names[0]}, $names[1], $value);
break;
case 1:
$_this->{$name[0]} = $value;
break;
} }
} }
@ -154,26 +150,20 @@ class Configure extends Object {
} }
return $_this->debug; return $_this->debug;
} }
$name = $_this->__configVarNames($var);
switch (count($name)) { if (strpos($var, '.') !== false) {
case 3: $names = explode('.', $var, 2);
if (isset($_this->{$name[0]}[$name[1]][$name[2]])) { $var = $names[0];
return $_this->{$name[0]}[$name[1]][$name[2]];
}
break;
case 2:
if (isset($_this->{$name[0]}[$name[1]])) {
return $_this->{$name[0]}[$name[1]];
}
break;
case 1:
if (isset($_this->{$name[0]})) {
return $_this->{$name[0]};
}
break;
} }
return null; if (!isset($_this->{$var})) {
return null;
}
if (!empty($names[1])) {
return Set::extract($_this->{$var}, $names[1]);
}
return $_this->{$var};
} }
/** /**
* Used to delete a variable from the Configure instance. * Used to delete a variable from the Configure instance.
@ -189,13 +179,14 @@ class Configure extends Object {
*/ */
function delete($var = null) { function delete($var = null) {
$_this =& Configure::getInstance(); $_this =& Configure::getInstance();
$name = $_this->__configVarNames($var);
if (count($name) > 1) { if (strpos($var, '.') === false) {
unset($_this->{$name[0]}[$name[1]]); unset($_this->{$var});
} else { return;
unset($_this->{$name[0]});
} }
$names = explode('.', $var, 2);
$_this->{$names[0]} = Set::remove($_this->{$names[0]}, $names[1]);
} }
/** /**
* Loads a file from app/config/configure_file.php. * Loads a file from app/config/configure_file.php.
@ -332,22 +323,6 @@ class Configure extends Object {
} }
} }
} }
/**
* Checks $name for dot notation to create dynamic Configure::$var as an array when needed.
*
* @param mixed $name Name to split
* @return array Name separated in items through dot notation
* @access private
*/
function __configVarNames($name) {
if (is_string($name)) {
if (strpos($name, ".")) {
return explode(".", $name);
}
return array($name);
}
return $name;
}
/** /**
* @deprecated * @deprecated
* @see App::objects() * @see App::objects()
@ -414,14 +389,14 @@ class Configure extends Object {
} }
if (Cache::config('_cake_core_') === false) { if (Cache::config('_cake_core_') === false) {
Cache::config('_cake_core_', array_merge($cache['settings'], array( Cache::config('_cake_core_', array_merge((array)$cache['settings'], array(
'prefix' => $prefix . 'cake_core_', 'path' => $path . DS . 'persistent' . DS, 'prefix' => $prefix . 'cake_core_', 'path' => $path . DS . 'persistent' . DS,
'serialize' => true, 'duration' => $duration 'serialize' => true, 'duration' => $duration
))); )));
} }
if (Cache::config('_cake_model_') === false) { if (Cache::config('_cake_model_') === false) {
Cache::config('_cake_model_', array_merge($cache['settings'], array( Cache::config('_cake_model_', array_merge((array)$cache['settings'], array(
'prefix' => $prefix . 'cake_model_', 'path' => $path . DS . 'models' . DS, 'prefix' => $prefix . 'cake_model_', 'path' => $path . DS . 'models' . DS,
'serialize' => true, 'duration' => $duration 'serialize' => true, 'duration' => $duration
))); )));

View file

@ -346,6 +346,7 @@ class EmailComponent extends Object{
$this->subject = null; $this->subject = null;
$this->additionalParams = null; $this->additionalParams = null;
$this->smtpError = null; $this->smtpError = null;
$this->attachments = array();
$this->__header = array(); $this->__header = array();
$this->__boundary = null; $this->__boundary = null;
$this->__message = array(); $this->__message = array();
@ -490,7 +491,6 @@ class EmailComponent extends Object{
$this->__header[] = 'Content-Type: text/html; charset=' . $this->charset; $this->__header[] = 'Content-Type: text/html; charset=' . $this->charset;
} elseif ($this->sendAs === 'both') { } elseif ($this->sendAs === 'both') {
$this->__header[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->__boundary . '"'; $this->__header[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->__boundary . '"';
$this->__header[] = '';
} }
$this->__header[] = 'Content-Transfer-Encoding: 7bit'; $this->__header[] = 'Content-Transfer-Encoding: 7bit';
@ -503,12 +503,16 @@ class EmailComponent extends Object{
*/ */
function __formatMessage($message) { function __formatMessage($message) {
if (!empty($this->attachments)) { if (!empty($this->attachments)) {
$prefix = array( $prefix = array('--' . $this->__boundary);
'--' . $this->__boundary, if ($this->sendAs === 'text') {
'Content-Type: text/plain; charset=' . $this->charset, $prefix[] = 'Content-Type: text/plain; charset=' . $this->charset;
'Content-Transfer-Encoding: 7bit', } elseif ($this->sendAs === 'html') {
'' $prefix[] = 'Content-Type: text/html; charset=' . $this->charset;
); } elseif ($this->sendAs === 'both') {
$prefix[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->__boundary . '"';
}
$prefix[] = 'Content-Transfer-Encoding: 7bit';
$prefix[] = '';
$message = array_merge($prefix, $message); $message = array_merge($prefix, $message);
} }
return $message; return $message;

View file

@ -585,7 +585,7 @@ class RequestHandlerComponent extends Object {
if (empty($this->__renderType)) { if (empty($this->__renderType)) {
$controller->viewPath .= '/' . $type; $controller->viewPath .= '/' . $type;
} else { } else {
$remove = preg_replace("/(?:\/{$type})$/", '/' . $type, $controller->viewPath); $remove = preg_replace("/(?:\/{$this->__renderType})$/", '/' . $type, $controller->viewPath);
$controller->viewPath = $remove; $controller->viewPath = $remove;
} }
$this->__renderType = $type; $this->__renderType = $type;

View file

@ -425,7 +425,7 @@ class Debugger extends Object {
} elseif (strpos($path, ROOT) === 0) { } elseif (strpos($path, ROOT) === 0) {
return str_replace(ROOT, 'ROOT', $path); return str_replace(ROOT, 'ROOT', $path);
} }
$corePaths = Configure::corePaths('cake'); $corePaths = App::core('cake');
foreach ($corePaths as $corePath) { foreach ($corePaths as $corePath) {
if (strpos($path, $corePath) === 0) { if (strpos($path, $corePath) === 0) {
return str_replace($corePath, 'CORE' .DS . 'cake' .DS, $path); return str_replace($corePath, 'CORE' .DS . 'cake' .DS, $path);

View file

@ -221,8 +221,11 @@ class HttpSocket extends CakeSocket {
$this->request['header']['Content-Length'] = strlen($this->request['body']); $this->request['header']['Content-Length'] = strlen($this->request['body']);
} }
$connectionType = @$this->request['header']['Connection']; $connectionType = null;
$this->request['header'] = $this->_buildHeader($this->request['header']).$cookies; if (isset($this->request['header']['Connection'])) {
$connectionType = $this->request['header']['Connection'];
}
$this->request['header'] = $this->_buildHeader($this->request['header']) . $cookies;
if (empty($this->request['line'])) { if (empty($this->request['line'])) {
$this->request['line'] = $this->_buildRequestLine($this->request); $this->request['line'] = $this->_buildRequestLine($this->request);
@ -396,7 +399,11 @@ class HttpSocket extends CakeSocket {
} }
$response['header'] = $this->_parseHeader($response['raw']['header']); $response['header'] = $this->_parseHeader($response['raw']['header']);
$decoded = $this->_decodeBody($response['raw']['body'], @$response['header']['Transfer-Encoding']); $transferEncoding = null;
if (isset($response['header']['Transfer-Encoding'])) {
$transferEncoding = $response['header']['Transfer-Encoding'];
}
$decoded = $this->_decodeBody($response['raw']['body'], $transferEncoding);
$response['body'] = $decoded['body']; $response['body'] = $decoded['body'];
if (!empty($decoded['header'])) { if (!empty($decoded['header'])) {

View file

@ -62,7 +62,7 @@ class I18n extends Object {
* Current language used for translations * Current language used for translations
* *
* @var string * @var string
* @access private; * @access private
*/ */
var $__lang = null; var $__lang = null;
/** /**
@ -94,7 +94,9 @@ class I18n extends Object {
* @var array * @var array
* @access private * @access private
*/ */
var $__categories = array('LC_CTYPE', 'LC_NUMERIC', 'LC_TIME', 'LC_COLLATE', 'LC_MONETARY', 'LC_MESSAGES', 'LC_ALL'); var $__categories = array(
'LC_ALL', 'LC_COLLATE', 'LC_CTYPE', 'LC_MONETARY', 'LC_NUMERIC', 'LC_TIME', 'LC_MESSAGES'
);
/** /**
* Return a static instance of the I18n class * Return a static instance of the I18n class
* *
@ -111,7 +113,7 @@ class I18n extends Object {
} }
/** /**
* Used by the translation functions in basics.php * Used by the translation functions in basics.php
* Can also be used like I18n::translate(); but only if the uses('i18n'); has been used to load the class. * Can also be used like I18n::translate(); but only if the App::import('I18n'); has been used to load the class.
* *
* @param string $singular String to translate * @param string $singular String to translate
* @param string $plural Plural string (if any) * @param string $plural Plural string (if any)
@ -121,7 +123,7 @@ class I18n extends Object {
* @return string translated strings. * @return string translated strings.
* @access public * @access public
*/ */
function translate($singular, $plural = null, $domain = null, $category = null, $count = null) { function translate($singular, $plural = null, $domain = null, $category = 6, $count = null) {
$_this =& I18n::getInstance(); $_this =& I18n::getInstance();
if (strpos($singular, "\r\n") !== false) { if (strpos($singular, "\r\n") !== false) {

View file

@ -481,9 +481,11 @@ class DboMysql extends DboMysqlBase {
if ($parent != null) { if ($parent != null) {
return $parent; return $parent;
} elseif ($data === null || (is_array($data) && empty($data))) { }
if ($data === null || (is_array($data) && empty($data))) {
return 'NULL'; return 'NULL';
} elseif ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') { }
if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
return "''"; return "''";
} }
if (empty($column)) { if (empty($column)) {

View file

@ -952,11 +952,11 @@ class DboOracle extends DboSource {
if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) { if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
if (!isset($resultSet) || !is_array($resultSet)) { if (!isset($resultSet) || !is_array($resultSet)) {
if (Configure::read() > 0) { if (Configure::read() > 0) {
e('<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:', true), $model->alias) . ' '); echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:', true), $model->alias) . ' ';
if (isset($this->error) && $this->error != null) { if (isset($this->error) && $this->error != null) {
e($this->error); echo $this->error;
} }
e('</div>'); echo '</div>';
} }
return null; return null;
} }

View file

@ -200,9 +200,8 @@ class DboSource extends DataSource {
if ($this->error) { if ($this->error) {
$this->showQuery($sql); $this->showQuery($sql);
return false; return false;
} else {
return $this->_result;
} }
return $this->_result;
} }
/** /**
* DataSource Query abstraction * DataSource Query abstraction
@ -743,11 +742,11 @@ class DboSource extends DataSource {
if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) { if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
if (!isset($resultSet) || !is_array($resultSet)) { if (!isset($resultSet) || !is_array($resultSet)) {
if (Configure::read() > 0) { if (Configure::read() > 0) {
e('<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:', true), $model->alias) . ' '); echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:', true), $model->alias) . ' ';
if (isset($this->error) && $this->error != null) { if (isset($this->error) && $this->error != null) {
e($this->error); echo $this->error;
} }
e('</div>'); echo '</div>';
} }
return null; return null;
} }
@ -1515,12 +1514,12 @@ class DboSource extends DataSource {
return $join; return $join;
} }
/** /**
* Returns the an SQL calculation, i.e. COUNT() or MAX() * Returns an SQL calculation, i.e. COUNT() or MAX()
* *
* @param model $model * @param model $model
* @param string $func Lowercase name of SQL function, i.e. 'count' or 'max' * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
* @param array $params Function parameters (any values must be quoted manually) * @param array $params Function parameters (any values must be quoted manually)
* @return string An SQL calculation function * @return string An SQL calculation function
* @access public * @access public
*/ */
function calculate(&$model, $func, $params = array()) { function calculate(&$model, $func, $params = array()) {
@ -1843,9 +1842,9 @@ class DboSource extends DataSource {
if (array_keys($value) === array_values(array_keys($value))) { if (array_keys($value) === array_values(array_keys($value))) {
$count = count($value); $count = count($value);
if ($count === 1) { if ($count === 1) {
$data = $this->name($key) . ' = ('; $data = $this->__quoteFields($key) . ' = (';
} else { } else {
$data = $this->name($key) . ' IN ('; $data = $this->__quoteFields($key) . ' IN (';
} }
if ($quoteValues || strpos($value[0], '-!') !== 0) { if ($quoteValues || strpos($value[0], '-!') !== 0) {
if (is_object($model)) { if (is_object($model)) {
@ -1908,7 +1907,9 @@ class DboSource extends DataSource {
} }
} }
$type = (is_object($model) ? $model->getColumnType($key) : null); $type = (is_object($model) ? $model->getColumnType($key) : null);
$null = ($value === null || (is_array($value) && empty($value))); $null = ($value === null || (is_array($value) && empty($value)));
if (strtolower($operator) === 'not') { if (strtolower($operator) === 'not') {
@ -1917,6 +1918,7 @@ class DboSource extends DataSource {
); );
return $data[0]; return $data[0];
} }
$value = $this->value($value, $type); $value = $this->value($value, $type);
if ($key !== '?') { if ($key !== '?') {
@ -1957,6 +1959,7 @@ class DboSource extends DataSource {
break; break;
} }
} }
return "{$key} {$operator} {$value}"; return "{$key} {$operator} {$value}";
} }
/** /**

View file

@ -369,7 +369,7 @@ class Model extends Overloadable {
} elseif ($table) { } elseif ($table) {
$this->useTable = $table; $this->useTable = $table;
} }
if ($ds !== null) { if ($ds !== null) {
$this->useDbConfig = $ds; $this->useDbConfig = $ds;
} }
@ -824,8 +824,11 @@ class Model extends Overloadable {
$type = $this->getColumnType($field); $type = $this->getColumnType($field);
if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) { if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
$useNewDate = (isset($data['year']) || isset($data['month']) || isset($data['day']) || isset($data['hour']) || isset($data['minute'])); $useNewDate = (isset($data['year']) || isset($data['month']) ||
isset($data['day']) || isset($data['hour']) || isset($data['minute']));
$dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec'); $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
$timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
$format = $db->columns[$type]['format']; $format = $db->columns[$type]['format'];
@ -837,27 +840,42 @@ class Model extends Overloadable {
if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) { if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
$data['hour'] = '00'; $data['hour'] = '00';
} }
if ($type == 'time') {
foreach ($dateFields as $key => $val) { foreach ($timeFields as $key => $val) {
if (in_array($val, array('hour', 'min', 'sec'))) { if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
if (!isset($data[$val]) || $data[$val] === '0' || empty($data[$val])) {
$data[$val] = '00'; $data[$val] = '00';
} elseif ($data[$val] === '') {
$data[$val] = '';
} else { } else {
$data[$val] = sprintf('%02d', $data[$val]); $data[$val] = sprintf('%02d', $data[$val]);
} }
if (!empty($data[$val])) {
$date[$key] = $data[$val];
} else {
return null;
}
} }
if (in_array($type, array('datetime', 'timestamp', 'date')) && !isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) { }
return null;
} elseif (isset($data[$val]) && !empty($data[$val])) { if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
$date[$key] = $data[$val]; foreach ($dateFields as $key => $val) {
if ($val == 'hour' || $val == 'min' || $val == 'sec') {
if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
$data[$val] = '00';
} else {
$data[$val] = sprintf('%02d', $data[$val]);
}
}
if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
return null;
}
if (isset($data[$val]) && !empty($data[$val])) {
$date[$key] = $data[$val];
}
} }
} }
$date = str_replace(array_keys($date), array_values($date), $format); $date = str_replace(array_keys($date), array_values($date), $format);
if ($type == 'time' && $date == '00:00:00') { if ($useNewDate && !empty($date)) {
return null;
}
if ($useNewDate && (!empty($date))) {
return $date; return $date;
} }
} }
@ -1322,7 +1340,7 @@ class Model extends Overloadable {
unset($values); unset($values);
} elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) { } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row; $newData[] = $row;
} elseif (isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) { } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row[$join]; $newData[] = $row[$join];
} }
} }

View file

@ -460,8 +460,6 @@ class Router extends Object {
if (isset($names[$key])) { if (isset($names[$key])) {
$out[$names[$key]] = $_this->stripEscape($found); $out[$names[$key]] = $_this->stripEscape($found);
} elseif (isset($names[$key]) && empty($names[$key]) && empty($out[$names[$key]])) {
break;
} else { } else {
$argOptions['context'] = array('action' => $out['action'], 'controller' => $out['controller']); $argOptions['context'] = array('action' => $out['action'], 'controller' => $out['controller']);
extract($_this->getArgs($found, $argOptions)); extract($_this->getArgs($found, $argOptions));
@ -1082,7 +1080,7 @@ class Router extends Object {
if (isset($params[$key])) { if (isset($params[$key])) {
$string = $params[$key]; $string = $params[$key];
unset($params[$key]); unset($params[$key]);
} else { } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
$key = $key . '/'; $key = $key . '/';
} }
$out = str_replace(':' . $key, $string, $out); $out = str_replace(':' . $key, $string, $out);
@ -1200,7 +1198,7 @@ class Router extends Object {
$paths = Router::getPaths(); $paths = Router::getPaths();
if (!empty($paths['base']) && stristr($url, $paths['base'])) { if (!empty($paths['base']) && stristr($url, $paths['base'])) {
$url = preg_replace('/' . preg_quote($paths['base'], '/') . '/', '', $url, 1); $url = preg_replace('/^' . preg_quote($paths['base'], '/') . '/', '', $url, 1);
} }
$url = '/' . $url; $url = '/' . $url;
@ -1245,7 +1243,7 @@ class Router extends Object {
* @access public * @access public
* @static * @static
*/ */
function stripPlugin($base, $plugin) { function stripPlugin($base, $plugin = null) {
if ($plugin != null) { if ($plugin != null) {
$base = preg_replace('/(?:' . $plugin . ')/', '', $base); $base = preg_replace('/(?:' . $plugin . ')/', '', $base);
$base = str_replace('//', '', $base); $base = str_replace('//', '', $base);
@ -1258,7 +1256,6 @@ class Router extends Object {
} }
return $base; return $base;
} }
/** /**
* Strip escape characters from parameter values. * Strip escape characters from parameter values.
* *

View file

@ -958,7 +958,7 @@ class AjaxHelper extends AppHelper {
$keys = array_keys($this->__ajaxBuffer); $keys = array_keys($this->__ajaxBuffer);
if (count($divs) == 1 && in_array($divs[0], $keys)) { if (count($divs) == 1 && in_array($divs[0], $keys)) {
e($this->__ajaxBuffer[$divs[0]]); echo $this->__ajaxBuffer[$divs[0]];
} else { } else {
foreach ($this->__ajaxBuffer as $key => $val) { foreach ($this->__ajaxBuffer as $key => $val) {
if (in_array($key, $divs)) { if (in_array($key, $divs)) {
@ -969,14 +969,13 @@ class AjaxHelper extends AppHelper {
$out .= 'for (n in __ajaxUpdater__) { if (typeof __ajaxUpdater__[n] == "string"'; $out .= 'for (n in __ajaxUpdater__) { if (typeof __ajaxUpdater__[n] == "string"';
$out .= ' && $(n)) Element.update($(n), unescape(decodeURIComponent('; $out .= ' && $(n)) Element.update($(n), unescape(decodeURIComponent(';
$out .= '__ajaxUpdater__[n]))); }'; $out .= '__ajaxUpdater__[n]))); }';
e($this->Javascript->codeBlock($out, false)); echo $this->Javascript->codeBlock($out, false);
} }
$scripts = $this->Javascript->getCache(); $scripts = $this->Javascript->getCache();
if (!empty($scripts)) { if (!empty($scripts)) {
e($this->Javascript->codeBlock($scripts, false)); echo $this->Javascript->codeBlock($scripts, false);
} }
$this->_stop(); $this->_stop();
} }
} }

View file

@ -325,7 +325,7 @@ class HtmlHelper extends AppHelper {
/** /**
* Creates a link element for CSS stylesheets. * Creates a link element for CSS stylesheets.
* *
* @param mixed $path The name of a CSS style sheet or an array containing names of * @param mixed $path The name of a CSS style sheet or an array containing names of
* CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot * CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot
* of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css. * of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
* @param string $rel Rel attribute. Defaults to "stylesheet". If equal to 'import' the stylesheet will be imported. * @param string $rel Rel attribute. Defaults to "stylesheet". If equal to 'import' the stylesheet will be imported.
@ -537,10 +537,11 @@ class HtmlHelper extends AppHelper {
} elseif ($path[0] === '/') { } elseif ($path[0] === '/') {
$path = $this->webroot($path); $path = $this->webroot($path);
} elseif (strpos($path, '://') === false) { } elseif (strpos($path, '://') === false) {
if ((Configure::read('Asset.timestamp') == true && Configure::read() > 0) || Configure::read('Asset.timestamp') === 'force') {
$path .= '?' . @filemtime(str_replace('/', DS, WWW_ROOT . IMAGES_URL . $path));
}
$path = $this->webroot(IMAGES_URL . $path); $path = $this->webroot(IMAGES_URL . $path);
if ((Configure::read('Asset.timestamp') == true && Configure::read() > 0) || Configure::read('Asset.timestamp') === 'force') {
$path .= '?' . @filemtime(str_replace('/', DS, WWW_ROOT . $path));
}
} }
if (!isset($options['alt'])) { if (!isset($options['alt'])) {
@ -744,4 +745,4 @@ class HtmlHelper extends AppHelper {
return $out; return $out;
} }
} }
?> ?>

View file

@ -60,10 +60,10 @@ class JavascriptHelper extends AppHelper {
* @access public * @access public
*/ */
var $tags = array( var $tags = array(
'javascriptblock' => '<script type="text/javascript">%s</script>',
'javascriptstart' => '<script type="text/javascript">', 'javascriptstart' => '<script type="text/javascript">',
'javascriptlink' => '<script type="text/javascript" src="%s"></script>', 'javascriptend' => '</script>',
'javascriptend' => '</script>' 'javascriptblock' => '<script type="text/javascript">%s</script>',
'javascriptlink' => '<script type="text/javascript" src="%s"></script>'
); );
/** /**
* Holds options passed to codeBlock(), saved for when block is dumped to output * Holds options passed to codeBlock(), saved for when block is dumped to output
@ -173,42 +173,28 @@ class JavascriptHelper extends AppHelper {
$options = array(); $options = array();
} }
$defaultOptions = array('allowCache' => true, 'safe' => true, 'inline' => true); $defaultOptions = array('allowCache' => true, 'safe' => true, 'inline' => true);
$options = array_merge($defaultOptions, compact('safe'), $options); $options = array_merge($defaultOptions, $options);
if ($this->_cacheEvents && $this->_cacheAll && $options['allowCache'] && $script !== null) { if (empty($script)) {
$this->__scriptBuffer = @ob_get_contents();
$this->_blockOptions = $options;
$this->inBlock = true;
@ob_end_clean();
ob_start();
return null;
}
if ($this->_cacheEvents && $this->_cacheAll && $options['allowCache']) {
$this->_cachedEvents[] = $script; $this->_cachedEvents[] = $script;
return null;
}
if ($options['safe'] || $this->safe) {
$script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
}
if ($options['inline']) {
return sprintf($this->tags['javascriptblock'], $script);
} else { } else {
$block = ($script !== null); $view =& ClassRegistry::getObject('view');
$safe = ($options['safe'] || $this->safe); $view->addScript(sprintf($this->tags['javascriptblock'], $script));
if ($safe && !($this->_cacheAll && $options['allowCache'])) {
$script = "\n" . '//<![CDATA[' . "\n" . $script;
if ($block) {
$script .= "\n" . '//]]>' . "\n";
}
}
if ($script === null) {
$this->__scriptBuffer = @ob_get_contents();
$this->_blockOptions = $options;
$this->inBlock = true;
@ob_end_clean();
ob_start();
return null;
} else if (!$block) {
$this->_blockOptions = $options;
}
if ($options['inline']) {
if ($block) {
return sprintf($this->tags['javascriptblock'], $script);
} else {
$safe = ($safe ? "\n" . '//<![CDATA[' . "\n" : '');
return $this->tags['javascriptstart'] . $safe;
}
} elseif ($block) {
$view =& ClassRegistry::getObject('view');
$view->addScript(sprintf($this->tags['javascriptblock'], $script));
}
} }
} }
/** /**
@ -217,26 +203,23 @@ class JavascriptHelper extends AppHelper {
* @return mixed * @return mixed
*/ */
function blockEnd() { function blockEnd() {
if (!isset($this->inBlock) || !$this->inBlock) {
return;
}
$script = @ob_get_contents(); $script = @ob_get_contents();
@ob_end_clean(); @ob_end_clean();
ob_start(); ob_start();
echo $this->__scriptBuffer; echo $this->__scriptBuffer;
$this->__scriptBuffer = null; $this->__scriptBuffer = null;
$options = $this->_blockOptions; $options = $this->_blockOptions;
$safe = ((isset($options['safe']) && $options['safe']) || $this->safe);
$this->_blockOptions = array(); $this->_blockOptions = array();
$this->inBlock = false; $this->inBlock = false;
if (isset($options['inline']) && !$options['inline']) { if (empty($script)) {
$view =& ClassRegistry::getObject('view');
$view->addScript(sprintf($this->tags['javascriptblock'], $script));
}
if (!empty($script) && $this->_cacheAll && $options['allowCache']) {
$this->_cachedEvents[] = $script;
return null; return null;
} }
return ife($safe, "\n" . '//]]>' . "\n", '').$this->tags['javascriptend'];
return $this->codeBlock($script, $options);
} }
/** /**
* Returns a JavaScript include tag (SCRIPT element). If the filename is prefixed with "/", * Returns a JavaScript include tag (SCRIPT element). If the filename is prefixed with "/",

View file

@ -223,11 +223,12 @@ class PaginatorHelper extends AppHelper {
} }
$dir = 'asc'; $dir = 'asc';
$sortKey = $this->sortKey($options['model']); $sortKey = $this->sortKey($options['model']);
$isSorted = ($sortKey === $key); $isSorted = ($sortKey === $key || $sortKey === $this->defaultModel() . '.' . $key);
if ($isSorted && $this->sortDir($options['model']) === 'asc') { if ($isSorted && $this->sortDir($options['model']) === 'asc') {
$dir = 'desc'; $dir = 'desc';
} }
if (is_array($title) && array_key_exists($dir, $title)) { if (is_array($title) && array_key_exists($dir, $title)) {
$title = $title[$dir]; $title = $title[$dir];
} }
@ -491,11 +492,15 @@ class PaginatorHelper extends AppHelper {
$end = $params['page'] + ($modulus - $params['page']) + 1; $end = $params['page'] + ($modulus - $params['page']) + 1;
} }
if ($first && $start > (int)$first) { if ($first) {
if ($start == $first + 1) { if ($start > (int)$first) {
$out .= $this->first($first, array('tag' => $tag, 'after' => $separator)); if ($start == $first + 1) {
} else { $out .= $this->first($first, array('tag' => $tag, 'after' => $separator, 'separator' => $separator));
$out .= $this->first($first, array('tag' => $tag)); } else {
$out .= $this->first($first, array('tag' => $tag, 'separator' => $separator));
}
} elseif ($start == 2) {
$out .= $this->Html->tag($tag, $this->link(1, array('page' => 1), $options)) . $separator;
} }
} }
@ -523,11 +528,15 @@ class PaginatorHelper extends AppHelper {
$out .= $after; $out .= $after;
if ($last && $end <= $params['pageCount'] - (int)$last) { if ($last) {
if ($end + 1 == $params['pageCount']) { if ($end <= $params['pageCount'] - (int)$last) {
$out .= $this->last($last, array('tag' => $tag, 'before' => $separator)); if ($end + 1 == $params['pageCount']) {
} else { $out .= $this->last($last, array('tag' => $tag, 'before' => $separator, 'separator' => $separator));
$out .= $this->last($last, array('tag' => $tag)); } else {
$out .= $this->last($last, array('tag' => $tag, 'separator' => $separator));
}
} elseif ($end == $params['pageCount'] - 1) {
$out .= $separator . $this->Html->tag($tag, $this->link($params['pageCount'], array('page' => $params['pageCount']), $options));
} }
} }

View file

@ -25,9 +25,8 @@
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
if (!class_exists('cakesession')) { if (!class_exists('cakesession')) {
uses('session'); require LIBS . 'cake_session.php';
} }
/** /**
* Session Helper. * Session Helper.
* *
@ -142,10 +141,10 @@ class SessionHelper extends CakeSession {
$out = $flash['message']; $out = $flash['message'];
} else { } else {
$view =& ClassRegistry::getObject('view'); $view =& ClassRegistry::getObject('view');
list($tmpLayout, $tmpVars, $tmpTitle) = array($view->layout, $view->viewVars, $view->pageTitle); list($tmpVars, $tmpTitle) = array($view->viewVars, $view->pageTitle);
list($view->layout, $view->viewVars, $view->pageTitle) = array($flash['layout'], $flash['params'], ''); list($view->viewVars, $view->pageTitle) = array($flash['params'], '');
$out = $view->renderLayout($flash['message']); $out = $view->renderLayout($flash['message'], $flash['layout']);
list($view->layout, $view->viewVars, $view->pageTitle) = array($tmpLayout, $tmpVars, $tmpTitle); list($view->viewVars, $view->pageTitle) = array($tmpVars, $tmpTitle);
} }
echo($out); echo($out);
parent::del('Message.' . $key); parent::del('Message.' . $key);

View file

@ -277,17 +277,20 @@ class TextHelper extends AppHelper {
} }
$pos = strpos(strtolower($text), strtolower($phrase)); $pos = strpos(strtolower($text), strtolower($phrase));
$startPos = 0; $startPos = 0;
if ($pos > $radius) { if ($pos > $radius) {
$startPos = $pos - $radius; $startPos = $pos - $radius;
} }
$textLen = strlen($text); $textLen = strlen($text);
$endPos = $pos + $phraseLen + $radius; $endPos = $pos + $phraseLen + $radius;
if ($endPos >= $textLen) { if ($endPos >= $textLen) {
$endPos = $textLen; $endPos = $textLen;
} }
$excerpt = substr($text, $startPos, $endPos - $startPos);
$excerpt = substr($text, $startPos, $endPos - $startPos);
if ($startPos != 0) { if ($startPos != 0) {
$excerpt = substr_replace($excerpt, $ending, 0, $phraseLen); $excerpt = substr_replace($excerpt, $ending, 0, $phraseLen);
} }
@ -317,25 +320,5 @@ class TextHelper extends AppHelper {
} }
return $r; return $r;
} }
/**
* Text-to-html parser, similar to Textile or RedCloth, only with a little different syntax.
*
* @param string $text String to "flay"
* @param boolean $allowHtml Set to true if if html is allowed
* @return string "Flayed" text
* @access public
* @todo Change this. We need a real Textile parser.
* @codeCoverageIgnoreStart
*/
function flay($text, $allowHtml = false) {
trigger_error(__('(TextHelper::flay) Deprecated: the Flay library is no longer supported and will be removed in a future version.', true), E_USER_WARNING);
if (!class_exists('Flay')) {
uses('flay');
}
return Flay::toHtml($text, false, $allowHtml);
}
/**
* @codeCoverageIgnoreEnd
*/
} }
?> ?>

View file

@ -481,7 +481,7 @@ class TimeHelper extends AppHelper {
* @return bool * @return bool
*/ */
function wasWithinLast($timeInterval, $dateString, $userOffset = null) { function wasWithinLast($timeInterval, $dateString, $userOffset = null) {
$tmp = r(' ', '', $timeInterval); $tmp = str_replace(' ', '', $timeInterval);
if (is_numeric($tmp)) { if (is_numeric($tmp)) {
$timeInterval = $tmp . ' ' . __('days', true); $timeInterval = $tmp . ' ' . __('days', true);
} }

View file

@ -1,2 +1,2 @@
<?php e($xml->header()); ?> <?php echo $xml->header(); ?>
<?php echo $content_for_layout; ?> <?php echo $content_for_layout; ?>

View file

@ -417,6 +417,10 @@ class View extends Object {
*/ */
function renderLayout($content_for_layout, $layout = null) { function renderLayout($content_for_layout, $layout = null) {
$layoutFileName = $this->_getLayoutFileName($layout); $layoutFileName = $this->_getLayoutFileName($layout);
if (empty($layoutFileName)) {
return $this->output;
}
$debug = ''; $debug = '';
if (isset($this->viewVars['cakeDebug']) && Configure::read() > 2) { if (isset($this->viewVars['cakeDebug']) && Configure::read() > 2) {
@ -892,7 +896,7 @@ class View extends Object {
$paths = array(); $paths = array();
$viewPaths = App::path('views'); $viewPaths = App::path('views');
if ($plugin !== null) { if (!empty($plugin)) {
$count = count($viewPaths); $count = count($viewPaths);
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
$paths[] = $viewPaths[$i] . 'plugins' . DS . $plugin . DS; $paths[] = $viewPaths[$i] . 'plugins' . DS . $plugin . DS;

View file

@ -95,11 +95,28 @@ class BasicsTest extends CakeTestCase {
$_SERVER = $_ENV = array(); $_SERVER = $_ENV = array();
$this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = 'on'; $_SERVER['HTTPS'] = 'on';
$this->assertTrue(env('HTTPS')); $this->assertTrue(env('HTTPS'));
$_SERVER['HTTPS'] = '1';
$this->assertTrue(env('HTTPS'));
$_SERVER['HTTPS'] = 'I am not empty';
$this->assertTrue(env('HTTPS'));
$_SERVER['HTTPS'] = 1;
$this->assertTrue(env('HTTPS'));
$_SERVER['HTTPS'] = 'off'; $_SERVER['HTTPS'] = 'off';
$this->assertFalse(env('HTTPS')); $this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = false;
$this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = '';
$this->assertFalse(env('HTTPS'));
$_SERVER = array(); $_SERVER = array();
@ -389,16 +406,16 @@ class BasicsTest extends CakeTestCase {
function test__c() { function test__c() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
$result = __c('Plural Rule 1', 5, true); $result = __c('Plural Rule 1', 6, true);
$expected = 'Plural Rule 1 (translated)'; $expected = 'Plural Rule 1 (translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = __c('Plural Rule 1 (from core)', 5, true); $result = __c('Plural Rule 1 (from core)', 6, true);
$expected = 'Plural Rule 1 (from core translated)'; $expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
ob_start(); ob_start();
__c('Plural Rule 1 (from core)', 5); __c('Plural Rule 1 (from core)', 6);
$result = ob_get_clean(); $result = ob_get_clean();
$expected = 'Plural Rule 1 (from core translated)'; $expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
@ -412,24 +429,24 @@ class BasicsTest extends CakeTestCase {
function test__dc() { function test__dc() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
$result = __dc('default', 'Plural Rule 1', 5, true); $result = __dc('default', 'Plural Rule 1', 6, true);
$expected = 'Plural Rule 1 (translated)'; $expected = 'Plural Rule 1 (translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = __dc('default', 'Plural Rule 1 (from core)', 5, true); $result = __dc('default', 'Plural Rule 1 (from core)', 6, true);
$expected = 'Plural Rule 1 (from core translated)'; $expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = __dc('core', 'Plural Rule 1', 5, true); $result = __dc('core', 'Plural Rule 1', 6, true);
$expected = 'Plural Rule 1'; $expected = 'Plural Rule 1';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = __dc('core', 'Plural Rule 1 (from core)', 5, true); $result = __dc('core', 'Plural Rule 1 (from core)', 6, true);
$expected = 'Plural Rule 1 (from core translated)'; $expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
ob_start(); ob_start();
__dc('default', 'Plural Rule 1 (from core)', 5); __dc('default', 'Plural Rule 1 (from core)', 6);
$result = ob_get_clean(); $result = ob_get_clean();
$expected = 'Plural Rule 1 (from core translated)'; $expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
@ -443,20 +460,20 @@ class BasicsTest extends CakeTestCase {
function test__dcn() { function test__dcn() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
$result = __dcn('default', '%d = 1', '%d = 0 or > 1', 0, 5, true); $result = __dcn('default', '%d = 1', '%d = 0 or > 1', 0, 6, true);
$expected = '%d = 0 or > 1 (translated)'; $expected = '%d = 0 or > 1 (translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = __dcn('default', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 1, 5, true); $result = __dcn('default', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 1, 6, true);
$expected = '%d = 1 (from core translated)'; $expected = '%d = 1 (from core translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = __dcn('core', '%d = 1', '%d = 0 or > 1', 0, 5, true); $result = __dcn('core', '%d = 1', '%d = 0 or > 1', 0, 6, true);
$expected = '%d = 0 or > 1'; $expected = '%d = 0 or > 1';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
ob_start(); ob_start();
__dcn('default', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 1, 5); __dcn('default', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 1, 6);
$result = ob_get_clean(); $result = ob_get_clean();
$expected = '%d = 1 (from core translated)'; $expected = '%d = 1 (from core translated)';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);

View file

@ -1,9 +1,7 @@
<?php <?php
/* SVN FILE: $Id$ */ /* SVN FILE: $Id$ */
/** /**
* TestTaskTest file * ApiShellTest file
*
* Test Case for test generation shell task
* *
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
@ -51,12 +49,12 @@ Mock::generatePartial(
); );
/** /**
* TestTaskTest class * ApiShellTest class
* *
* @package cake * @package cake
* @subpackage cake.tests.cases.console.libs.tasks * @subpackage cake.tests.cases.console.libs.tasks
*/ */
class TestTaskTest extends CakeTestCase { class ApiShellTest extends CakeTestCase {
/** /**
* setUp method * setUp method
* *
@ -106,10 +104,10 @@ class TestTaskTest extends CakeTestCase {
'16. setAction($action)', '16. setAction($action)',
'17. validate()', '17. validate()',
'18. validateErrors()' '18. validateErrors()'
)A )
); );
$this->Shell->expectAt(1, 'out', $expected); $this->Shell->expectAt(1, 'out', $expected);
$this->Shell->args = array('controller'); $this->Shell->args = array('controller');
$this->Shell->paths['controller'] = CAKE_CORE_INCLUDE_PATH . DS . LIBS . 'controller' . DS; $this->Shell->paths['controller'] = CAKE_CORE_INCLUDE_PATH . DS . LIBS . 'controller' . DS;
$this->Shell->main(); $this->Shell->main();

View file

@ -0,0 +1,117 @@
<?php
/**
* BakeShell Test Case
*
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'bake.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'model.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'controller.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'db_config.php';
Mock::generatePartial(
'ShellDispatcher', 'BakeShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'BakeShell', 'MockBakeShell',
array('in', 'hr', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
Mock::generate('DbConfigTask', 'BakeShellMockDbConfigTask');
Mock::generate('ModelTask', 'BakeShellMockModelTask');
Mock::generate('ControllerTask', 'BakeShellMockControllerTask');
if (!class_exists('UsersController')) {
class UsersController extends Controller {
var $name = 'Users';
}
}
class BakeShellTestCase extends CakeTestCase {
/**
* fixtures
*
* @var array
**/
var $fixtures = array('core.user');
/**
* start test
*
* @return void
**/
function startTest() {
$this->Dispatch =& new BakeShellMockShellDispatcher();
$this->Shell =& new MockBakeShell();
$this->Shell->Dispatch =& $this->Dispatch;
$this->Shell->Dispatch->shellPaths = App::path('shells');
}
/**
* endTest method
*
* @return void
**/
function endTest() {
unset($this->Dispatch, $this->Shell);
}
/**
* test bake all
*
* @return void
**/
function testAllWithModelName() {
$this->Shell->Model =& new BakeShellMockModelTask();
$this->Shell->Controller =& new BakeShellMockControllerTask();
$this->Shell->View =& new BakeShellMockModelTask();
$this->Shell->DbConfig =& new BakeShellMockDbConfigTask();
$this->Shell->DbConfig->expectOnce('getConfig');
$this->Shell->DbConfig->setReturnValue('getConfig', 'test_suite');
$this->Shell->Model->setReturnValue('bake', true);
$this->Shell->Model->expectNever('getName');
$this->Shell->Model->expectOnce('bake');
$this->Shell->Controller->expectOnce('bake');
$this->Shell->Controller->setReturnValue('bake', true);
$this->Shell->View->expectOnce('execute');
$this->Shell->expectAt(0, 'out', array('Bake All'));
$this->Shell->expectAt(1, 'out', array('User Model was baked.'));
$this->Shell->expectAt(2, 'out', array('User Controller was baked.'));
$this->Shell->expectAt(3, 'out', array('User Views were baked.'));
$this->Shell->expectAt(4, 'out', array('Bake All complete'));
$this->Shell->params = array();
$this->Shell->args = array('User');
$this->Shell->all();
}
}

View file

@ -0,0 +1,459 @@
<?php
/**
* ControllerTask Test Case
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'project.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'controller.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'model.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'test.php';
Mock::generatePartial(
'ShellDispatcher', 'TestControllerTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ControllerTask', 'MockControllerTask',
array('in', 'hr', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
Mock::generatePartial(
'ModelTask', 'ControllerMockModelTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
Mock::generatePartial(
'ProjectTask', 'ControllerMockProjectTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest', 'getAdmin')
);
Mock::generate('TestTask', 'ControllerMockTestTask');
$imported = App::import('Model', 'Article');
$imported = $imported || App::import('Model', 'Comment');
$imported = $imported || App::import('Model', 'Tag');
if (!$imported) {
define('ARTICLE_MODEL_CREATED', true);
App::import('Core', 'Model');
class Article extends Model {
var $name = 'Article';
var $hasMany = array('Comment');
var $hasAndBelongsToMany = array('Tag');
}
}
/**
* ControllerTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ControllerTaskTest extends CakeTestCase {
/**
* fixtures
*
* @var array
**/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestControllerTaskMockShellDispatcher();
$this->Task =& new MockControllerTask($this->Dispatcher);
$this->Task->Dispatch =& new $this->Dispatcher;
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->Template =& new TemplateTask($this->Task->Dispatch);
$this->Task->Template->params['theme'] = 'default';
$this->Task->Model =& new ControllerMockModelTask($this->Task->Dispatch);
$this->Task->Project =& new ControllerMockProjectTask($this->Task->Dispatch);
$this->Task->Test =& new ControllerMockTestTask();
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* test ListAll
*
* @return void
**/
function testListAll() {
$this->Task->connection = 'test_suite';
$this->Task->interactive = true;
$this->Task->expectAt(1, 'out', array('1. Articles'));
$this->Task->expectAt(2, 'out', array('2. ArticlesTags'));
$this->Task->expectAt(3, 'out', array('3. Comments'));
$this->Task->expectAt(4, 'out', array('4. Tags'));
$expected = array('Articles', 'ArticlesTags', 'Comments', 'Tags');
$result = $this->Task->listAll('test_suite');
$this->assertEqual($result, $expected);
$this->Task->expectAt(6, 'out', array('1. Articles'));
$this->Task->expectAt(7, 'out', array('2. ArticlesTags'));
$this->Task->expectAt(8, 'out', array('4. Comments'));
$this->Task->expectAt(9, 'out', array('5. Tags'));
$this->Task->interactive = false;
$result = $this->Task->listAll();
$expected = array('articles', 'articles_tags', 'comments', 'tags');
$this->assertEqual($result, $expected);
}
/**
* Test that getName interacts with the user and returns the controller name.
*
* @return void
**/
function testGetName() {
$this->Task->setReturnValue('in', 1);
$this->Task->setReturnValueAt(0, 'in', 'q');
$this->Task->expectOnce('_stop');
$this->Task->getName('test_suite');
$this->Task->setReturnValueAt(1, 'in', 1);
$result = $this->Task->getName('test_suite');
$expected = 'Articles';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(2, 'in', 3);
$result = $this->Task->getName('test_suite');
$expected = 'Comments';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(3, 'in', 10);
$result = $this->Task->getName('test_suite');
$this->Task->expectOnce('err');
}
/**
* test helper interactions
*
* @return void
**/
function testDoHelpers() {
$this->Task->setReturnValue('in', 'n');
$result = $this->Task->doHelpers();
$this->assertEqual($result, array());
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', ' Javascript, Ajax, CustomOne ');
$result = $this->Task->doHelpers();
$expected = array('Javascript', 'Ajax', 'CustomOne');
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(3, 'in', 'y');
$this->Task->setReturnValueAt(4, 'in', ' Javascript, Ajax, CustomOne, , ');
$result = $this->Task->doHelpers();
$expected = array('Javascript', 'Ajax', 'CustomOne');
$this->assertEqual($result, $expected);
}
/**
* test component interactions
*
* @return void
**/
function testDoComponents() {
$this->Task->setReturnValue('in', 'n');
$result = $this->Task->doComponents();
$this->assertEqual($result, array());
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', ' RequestHandler, Security ');
$result = $this->Task->doComponents();
$expected = array('RequestHandler', 'Security');
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(3, 'in', 'y');
$this->Task->setReturnValueAt(4, 'in', ' RequestHandler, Security, , ');
$result = $this->Task->doComponents();
$expected = array('RequestHandler', 'Security');
$this->assertEqual($result, $expected);
}
/**
* test Confirming controller user interaction
*
* @return void
**/
function testConfirmController() {
$controller = 'Posts';
$scaffold = false;
$helpers = array('Ajax', 'Time');
$components = array('Acl', 'Auth');
$uses = array('Comment', 'User');
$this->Task->expectAt(2, 'out', array("Controller Name:\n\t$controller"));
$this->Task->expectAt(3, 'out', array("Helpers:\n\tAjax, Time"));
$this->Task->expectAt(4, 'out', array("Components:\n\tAcl, Auth"));
$this->Task->confirmController($controller, $scaffold, $helpers, $components);
}
/**
* test the bake method
*
* @return void
**/
function testBake() {
$helpers = array('Ajax', 'Time');
$components = array('Acl', 'Auth');
$this->Task->setReturnValue('createFile', true);
$result = $this->Task->bake('Articles', '--actions--', $helpers, $components);
$this->assertPattern('/class ArticlesController extends AppController/', $result);
$this->assertPattern('/\$components \= array\(\'Acl\', \'Auth\'\)/', $result);
$this->assertPattern('/\$helpers \= array\(\'Html\', \'Form\', \'Ajax\', \'Time\'\)/', $result);
$this->assertPattern('/\-\-actions\-\-/', $result);
$result = $this->Task->bake('Articles', 'scaffold', $helpers, $components);
$this->assertPattern('/class ArticlesController extends AppController/', $result);
$this->assertPattern('/var \$scaffold/', $result);
$this->assertNoPattern('/helpers/', $result);
$this->assertNoPattern('/components/', $result);
}
/**
* test bake() with a -plugin param
*
* @return void
**/
function testBakeWithPlugin() {
$this->Task->plugin = 'ControllerTest';
$helpers = array('Ajax', 'Time');
$components = array('Acl', 'Auth');
$uses = array('Comment', 'User');
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'controllers' . DS . 'articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->bake('Articles', '--actions--', array(), array(), array());
$this->Task->plugin = 'controllerTest';
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'controllers' . DS . 'articles_controller.php';
$this->Task->expectAt(1, 'createFile', array(
$path, new PatternExpectation('/ArticlesController extends ControllerTestAppController/')));
$this->Task->bake('Articles', '--actions--', array(), array(), array());
}
/**
* test that bakeActions is creating the correct controller Code. (Using sessions)
*
* @return void
**/
function testBakeActionsUsingSessions() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Testing bakeActions requires Article, Comment & Tag Model to be undefined. %s');
if ($skip) {
return;
}
$result = $this->Task->bakeActions('Articles', null, true);
$this->assertTrue(strpos($result, 'function index() {') !== false);
$this->assertTrue(strpos($result, '$this->Article->recursive = 0;') !== false);
$this->assertTrue(strpos($result, "\$this->set('articles', \$this->paginate());") !== false);
$this->assertTrue(strpos($result, 'function view($id = null)') !== false);
$this->assertTrue(strpos($result, "\$this->Session->setFlash(__('Invalid Article', true))") !== false);
$this->assertTrue(strpos($result, "\$this->set('article', \$this->Article->read(null, \$id)") !== false);
$this->assertTrue(strpos($result, 'function add()') !== false);
$this->assertTrue(strpos($result, 'if (!empty($this->data))') !== false);
$this->assertTrue(strpos($result, 'if ($this->Article->save($this->data))') !== false);
$this->assertTrue(strpos($result, "\$this->Session->setFlash(__('The Article has been saved', true))") !== false);
$this->assertTrue(strpos($result, 'function edit($id = null)') !== false);
$this->assertTrue(strpos($result, "\$this->Session->setFlash(__('The Article could not be saved. Please, try again.', true));") !== false);
$this->assertTrue(strpos($result, 'function delete($id = null)') !== false);
$this->assertTrue(strpos($result, 'if ($this->Article->del($id))') !== false);
$this->assertTrue(strpos($result, "\$this->Session->setFlash(__('Article deleted', true))") !== false);
$result = $this->Task->bakeActions('Articles', 'admin_', true);
$this->assertTrue(strpos($result, 'function admin_index() {') !== false);
$this->assertTrue(strpos($result, 'function admin_add()') !== false);
$this->assertTrue(strpos($result, 'function admin_view($id = null)') !== false);
$this->assertTrue(strpos($result, 'function admin_edit($id = null)') !== false);
$this->assertTrue(strpos($result, 'function admin_delete($id = null)') !== false);
}
/**
* Test baking with Controller::flash() or no sessions.
*
* @return void
**/
function testBakeActionsWithNoSessions() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Testing bakeActions requires Article, Tag, Comment Models to be undefined. %s');
if ($skip) {
return;
}
$result = $this->Task->bakeActions('Articles', null, false);
$this->assertTrue(strpos($result, 'function index() {') !== false);
$this->assertTrue(strpos($result, '$this->Article->recursive = 0;') !== false);
$this->assertTrue(strpos($result, "\$this->set('articles', \$this->paginate());") !== false);
$this->assertTrue(strpos($result, 'function view($id = null)') !== false);
$this->assertTrue(strpos($result, "\$this->flash(__('Invalid Article', true), array('action' => 'index'))") !== false);
$this->assertTrue(strpos($result, "\$this->set('article', \$this->Article->read(null, \$id)") !== false);
$this->assertTrue(strpos($result, 'function add()') !== false);
$this->assertTrue(strpos($result, 'if (!empty($this->data))') !== false);
$this->assertTrue(strpos($result, 'if ($this->Article->save($this->data))') !== false);
$this->assertTrue(strpos($result, "\$this->flash(__('The Article has been saved.', true), array('action' => 'index'))") !== false);
$this->assertTrue(strpos($result, 'function edit($id = null)') !== false);
$this->assertTrue(strpos($result, "\$this->Article->Tag->find('list')") !== false);
$this->assertTrue(strpos($result, "\$this->set(compact('tags'))") !== false);
$this->assertTrue(strpos($result, 'function delete($id = null)') !== false);
$this->assertTrue(strpos($result, 'if ($this->Article->del($id))') !== false);
$this->assertTrue(strpos($result, "\$this->flash(__('Article deleted', true), array('action' => 'index'))") !== false);
}
/**
* test baking a test
*
* @return void
**/
function testBakeTest() {
$this->Task->plugin = 'ControllerTest';
$this->Task->connection = 'test_suite';
$this->Task->Test->expectOnce('bake', array('Controller', 'Articles'));
$this->Task->bakeTest('Articles');
$this->assertEqual($this->Task->plugin, $this->Task->Test->plugin);
$this->assertEqual($this->Task->connection, $this->Task->Test->connection);
}
/**
* test Interactive mode.
*
* @return void
**/
function testInteractive() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path';
$this->Task->setReturnValue('in', '1');
$this->Task->setReturnValueAt(1, 'in', 'y'); // build interactive
$this->Task->setReturnValueAt(2, 'in', 'n'); // build no scaffolds
$this->Task->setReturnValueAt(3, 'in', 'y'); // build normal methods
$this->Task->setReturnValueAt(4, 'in', 'n'); // build admin methods
$this->Task->setReturnValueAt(5, 'in', 'n'); // helpers?
$this->Task->setReturnValueAt(6, 'in', 'n'); // components?
$this->Task->setReturnValueAt(7, 'in', 'y'); // use sessions
$this->Task->setReturnValueAt(8, 'in', 'y'); // looks good
$this->Task->execute();
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticlesController/')));
}
/**
* test that execute runs all when the first arg == all
*
* @return void
**/
function testExecuteIntoAll() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute into all could not be run as an Article, Tag or Comment model was already loaded. %s');
if ($skip) {
return;
}
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->Test->expectCallCount('bake', 1);
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticlesController/')));
$this->Task->execute();
}
/**
* test that `cake bake controller foo scaffold` works.
*
* @return void
**/
function testExecuteWithScaffoldParam() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
if ($skip) {
return;
}
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('Articles', 'scaffold');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array(
$filename, new NoPatternExpectation('/admin_index/')
));
$this->Task->execute();
}
/**
* test that `cake bake controller foo scaffold admin` works
*
* @return void
**/
function testExecuteWithAdminScaffoldParams() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold admin param requires no Article, Tag or Comment model to be defined. %s');
if ($skip) {
return;
}
$this->Task->Project->setReturnValue('getAdmin', 'admin_');
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('Articles', 'scaffold', 'admin');
$filename = '/my/path/articles_controller.php';
$this->Task->expect('createFile', array(
$filename, new PatternExpectation('/admin_index/')
));
$this->Task->execute();
}
}
?>

View file

@ -0,0 +1,149 @@
<?php
/**
* DBConfigTask Test Case
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'db_config.php';
//require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
Mock::generatePartial(
'ShellDispatcher', 'TestDbConfigTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'DbConfigTask', 'MockDbConfigTask',
array('in', 'hr', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
class TEST_DATABASE_CONFIG {
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'database_name',
'prefix' => '',
);
var $otherOne = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'other_one',
'prefix' => '',
);
}
/**
* DbConfigTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class DbConfigTaskTest extends CakeTestCase {
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestDbConfigTaskMockShellDispatcher();
$this->Task =& new MockDbConfigTask($this->Dispatcher);
$this->Task->Dispatch =& new $this->Dispatcher;
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->params['working'] = rtrim(APP, '/');
$this->Task->databaseClassName = 'TEST_DATABASE_CONFIG';
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* Test the getConfig method.
*
* @return void
**/
function testGetConfig() {
$this->Task->setReturnValueAt(0, 'in', 'otherOne');
$result = $this->Task->getConfig();
$this->assertEqual($result, 'otherOne');
}
/**
* test that initialize sets the path up.
*
* @return void
**/
function testInitialize() {
$this->assertTrue(empty($this->Task->path));
$this->Task->initialize();
$this->assertFalse(empty($this->Task->path));
$this->assertEqual($this->Task->path, APP . 'config' . DS);
}
/**
* test execute and by extension __interactive
*
* @return void
**/
function testExecuteIntoInteractive() {
$this->Task->initialize();
$this->Task->expectOnce('_stop');
$this->Task->setReturnValue('in', 'y');
$this->Task->setReturnValueAt(0, 'in', 'default');
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->setReturnValueAt(2, 'in', 'localhost');
$this->Task->setReturnValueAt(3, 'in', 'n');
$this->Task->setReturnValueAt(4, 'in', 'root');
$this->Task->setReturnValueAt(5, 'in', 'password');
$this->Task->setReturnValueAt(6, 'in', 'cake_test');
$this->Task->setReturnValueAt(7, 'in', 'n');
$this->Task->setReturnValueAt(8, 'in', 'y');
$this->Task->setReturnValueAt(9, 'in', 'y');
$this->Task->setReturnValueAt(10, 'in', 'y');
$this->Task->setReturnValueAt(11, 'in', 'n');
$result = $this->Task->execute();
}
}
?>

View file

@ -0,0 +1,259 @@
<?php
/**
* FixtureTask Test case
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'fixture.php';
Mock::generatePartial(
'ShellDispatcher', 'TestFixtureTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'FixtureTask', 'MockFixtureTask',
array('in', 'out', 'err', 'createFile', '_stop')
);
Mock::generatePartial(
'Shell', 'MockFixtureModelTask',
array('in', 'out', 'err', 'createFile', '_stop', 'getName', 'getTable', 'listAll')
);
/**
* FixtureTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class FixtureTaskTest extends CakeTestCase {
/**
* fixtures
*
* @var array
**/
var $fixtures = array('core.article', 'core.comment');
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestFixtureTaskMockShellDispatcher();
$this->Task =& new MockFixtureTask();
$this->Task->Model =& new MockFixtureModelTask();
$this->Task->Dispatch = new $this->Dispatcher;
$this->Task->Template =& new TemplateTask($this->Task->Dispatch);
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->Template->initialize();
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* test that initialize sets the path
*
* @return void
**/
function testConstruct() {
$this->Dispatch->params['working'] = '/my/path';
$Task =& new FixtureTask($this->Dispatch);
$expected = '/my/path/tests/fixtures/';
$this->assertEqual($Task->path, $expected);
}
/**
* test import option array generation
*
* @return void
**/
function testImportOptions() {
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'y');
$result = $this->Task->importOptions('Article');
$expected = array('schema' => 'Article', 'records' => true);
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(2, 'in', 'n');
$this->Task->setReturnValueAt(3, 'in', 'n');
$this->Task->setReturnValueAt(4, 'in', 'n');
$result = $this->Task->importOptions('Article');
$expected = array();
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(5, 'in', 'n');
$this->Task->setReturnValueAt(6, 'in', 'n');
$this->Task->setReturnValueAt(7, 'in', 'y');
$result = $this->Task->importOptions('Article');
$expected = array('fromTable' => true);
$this->assertEqual($result, $expected);
}
/**
* test generating a fixture with database conditions.
*
* @return void
**/
function testImportRecordsFromDatabaseWithConditions() {
$this->Task->setReturnValueAt(0, 'in', 'WHERE 1=1 LIMIT 10');
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article', false, array('fromTable' => true, 'schema' => 'Article', 'records' => false));
$this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result);
$this->assertPattern('/var \$records/', $result);
$this->assertPattern('/var \$import/', $result);
$this->assertPattern("/'title' => 'First Article'/", $result, 'Missing import data %s');
$this->assertPattern('/Second Article/', $result, 'Missing import data %s');
$this->assertPattern('/Third Article/', $result, 'Missing import data %s');
}
/**
* test that execute passes runs bake depending with named model.
*
* @return void
**/
function testExecuteWithNamedModel() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
}
/**
* test that execute runs all() when args[0] = all
*
* @return void
**/
function testExecuteIntoAll() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->Model->setReturnValue('listAll', array('articles', 'comments'));
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
$filename = '/my/path/comment_fixture.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class CommentFixture/')));
$this->Task->execute();
}
/**
* test interactive mode of execute
*
* @return void
**/
function testExecuteInteractive() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->setReturnValue('in', 'y');
$this->Task->Model->setReturnValue('getName', 'Article');
$this->Task->Model->setReturnValue('getTable', 'articles', array('Article'));
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
}
/**
* Test that bake works
*
* @return void
**/
function testBake() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article');
$this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result);
$this->assertPattern('/var \$fields/', $result);
$this->assertPattern('/var \$records/', $result);
$this->assertNoPattern('/var \$import/', $result);
$result = $this->Task->bake('Article', 'comments');
$this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result);
$this->assertPattern('/var \$name \= \'Article\';/', $result);
$this->assertPattern('/var \$table \= \'comments\';/', $result);
$result = $this->Task->bake('Article', 'comments', array('records' => true));
$this->assertPattern("/var \\\$import \= array\('records' \=\> true\);/", $result);
$this->assertNoPattern('/var \$records/', $result);
$result = $this->Task->bake('Article', 'comments', array('schema' => 'Article'));
$this->assertPattern("/var \\\$import \= array\('model' \=\> 'Article'\);/", $result);
$this->assertNoPattern('/var \$fields/', $result);
$result = $this->Task->bake('Article', 'comments', array('schema' => 'Article', 'records' => true));
$this->assertPattern("/var \\\$import \= array\('model' \=\> 'Article'\, 'records' \=\> true\);/", $result);
$this->assertNoPattern('/var \$fields/', $result);
$this->assertNoPattern('/var \$records/', $result);
}
/**
* Test that file generation includes headers and correct path for plugins.
*
* @return void
**/
function testGenerateFixtureFile() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/Article/')));
$result = $this->Task->generateFixtureFile('Article', array());
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/\<\?php(.*)\?\>/ms')));
$result = $this->Task->generateFixtureFile('Article', array());
}
/**
* test generating files into plugins.
*
* @return void
**/
function testGeneratePluginFixtureFile() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->plugin = 'TestFixture';
$filename = APP . 'plugins' . DS . 'test_fixture' . DS . 'tests' . DS . 'fixtures' . DS . 'article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/Article/')));
$result = $this->Task->generateFixtureFile('Article', array());
}
}
?>

View file

@ -0,0 +1,727 @@
<?php
/**
* TestTaskTest file
*
* Test Case for test generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2006-2009, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2006-2009, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.3
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'model.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'fixture.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
Mock::generatePartial(
'ShellDispatcher', 'TestModelTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ModelTask', 'MockModelTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
Mock::generate(
'Model', 'MockModelTaskModel'
);
Mock::generate(
'FixtureTask', 'MockModelTaskFixtureTask'
);
/**
* ModelTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ModelTaskTest extends CakeTestCase {
/**
* fixtures
*
* @var array
**/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag', 'core.category_thread');
/**
* starTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestModelTaskMockShellDispatcher();
$this->Task =& new MockModelTask($this->Dispatcher);
$this->Task->Dispatch =& new $this->Dispatcher;
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->Template =& new TemplateTask($this->Task->Dispatch);
$this->Task->Fixture =& new MockModelTaskFixtureTask();
$this->Task->Test =& new MockModelTaskFixtureTask();
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* Test that listAll scans the database connection and lists all the tables in it.s
*
* @return void
**/
function testListAll() {
$this->Task->expectAt(1, 'out', array('1. Article'));
$this->Task->expectAt(2, 'out', array('2. ArticlesTag'));
$this->Task->expectAt(3, 'out', array('3. CategoryThread'));
$this->Task->expectAt(4, 'out', array('4. Comment'));
$this->Task->expectAt(5, 'out', array('5. Tag'));
$result = $this->Task->listAll('test_suite');
$expected = array('articles', 'articles_tags', 'category_threads', 'comments', 'tags');
$this->assertEqual($result, $expected);
$this->Task->expectAt(7, 'out', array('1. Article'));
$this->Task->expectAt(8, 'out', array('2. ArticlesTag'));
$this->Task->expectAt(9, 'out', array('3. CategoryThread'));
$this->Task->expectAt(10, 'out', array('4. Comment'));
$this->Task->expectAt(11, 'out', array('5. Tag'));
$this->Task->connection = 'test_suite';
$result = $this->Task->listAll();
$expected = array('articles', 'articles_tags', 'category_threads', 'comments', 'tags');
$this->assertEqual($result, $expected);
}
/**
* Test that getName interacts with the user and returns the model name.
*
* @return void
**/
function testGetName() {
$this->Task->setReturnValue('in', 1);
$this->Task->setReturnValueAt(0, 'in', 'q');
$this->Task->expectOnce('_stop');
$this->Task->getName('test_suite');
$this->Task->setReturnValueAt(1, 'in', 1);
$result = $this->Task->getName('test_suite');
$expected = 'Article';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(2, 'in', 4);
$result = $this->Task->getName('test_suite');
$expected = 'Comment';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(3, 'in', 10);
$result = $this->Task->getName('test_suite');
$this->Task->expectOnce('err');
}
/**
* Test table name interactions
*
* @return void
**/
function testGetTableName() {
$this->Task->setReturnValueAt(0, 'in', 'y');
$result = $this->Task->getTable('Article', 'test_suite');
$expected = 'articles';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->setReturnValueAt(2, 'in', 'my_table');
$result = $this->Task->getTable('Article', 'test_suite');
$expected = 'my_table';
$this->assertEqual($result, $expected);
}
/**
* test that initializing the validations works.
*
* @return void
**/
function testInitValidations() {
$result = $this->Task->initValidations();
$this->assertTrue(in_array('notempty', $result));
}
/**
* test that individual field validation works, with interactive = false
* tests the guessing features of validation
*
* @return void
**/
function testFieldValidationGuessing() {
$this->Task->interactive = false;
$this->Task->initValidations();
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty');
$result = $this->Task->fieldValidation('text', array('type' => 'date', 'length' => 10, 'null' => false));
$expected = array('date' => 'date');
$result = $this->Task->fieldValidation('text', array('type' => 'time', 'length' => 10, 'null' => false));
$expected = array('time' => 'time');
$result = $this->Task->fieldValidation('email', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('email' => 'email');
$result = $this->Task->fieldValidation('test', array('type' => 'integer', 'length' => 10, 'null' => false));
$expected = array('numeric' => 'numeric');
$result = $this->Task->fieldValidation('test', array('type' => 'boolean', 'length' => 10, 'null' => false));
$expected = array('numeric' => 'numeric');
}
/**
* test that interactive field validation works and returns multiple validators.
*
* @return void
**/
function testInteractiveFieldValidation() {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '20');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', '16');
$this->Task->setReturnValueAt(3, 'in', 'n');
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty', 'maxlength' => 'maxlength');
$this->assertEqual($result, $expected);
}
/**
* test the validation Generation routine
*
* @return void
**/
function testNonInteractiveDoValidation() {
$Model =& new MockModelTaskModel();
$Model->primaryKey = 'id';
$Model->setReturnValue('schema', array(
'id' => array(
'type' => 'integer',
'length' => 11,
'null' => false,
'key' => 'primary',
),
'name' => array(
'type' => 'string',
'length' => 20,
'null' => false,
),
'email' => array(
'type' => 'string',
'length' => 255,
'null' => false,
),
'some_date' => array(
'type' => 'date',
'length' => '',
'null' => false,
),
'some_time' => array(
'type' => 'time',
'length' => '',
'null' => false,
),
'created' => array(
'type' => 'datetime',
'length' => '',
'null' => false,
)
));
$this->Task->interactive = false;
$result = $this->Task->doValidation($Model);
$expected = array(
'name' => array(
'notempty' => 'notempty'
),
'email' => array(
'email' => 'email',
),
'some_date' => array(
'date' => 'date'
),
'some_time' => array(
'time' => 'time'
),
);
$this->assertEqual($result, $expected);
}
/**
* test that finding primary key works
*
* @return void
**/
function testFindPrimaryKey() {
$fields = array(
'one' => array(),
'two' => array(),
'key' => array('key' => 'primary')
);
$this->Task->expectAt(0, 'in', array('*', null, 'key'));
$this->Task->setReturnValue('in', 'my_field');
$result = $this->Task->findPrimaryKey($fields);
$expected = 'my_field';
$this->assertEqual($result, $expected);
}
/**
* test finding Display field
*
* @return void
**/
function testFindDisplayField() {
$fields = array('id' => array(), 'tagname' => array(), 'body' => array(),
'created' => array(), 'modified' => array());
$this->Task->setReturnValue('in', 'n');
$this->Task->setReturnValueAt(0, 'in', 'n');
$result = $this->Task->findDisplayField($fields);
$this->assertFalse($result);
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', 2);
$result = $this->Task->findDisplayField($fields);
$this->assertEqual($result, 'tagname');
}
/**
* test that belongsTo generation works.
*
* @return void
**/
function testBelongsToGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Comment'));
$result = $this->Task->findBelongsTo($model, array());
$expected = array(
'belongsTo' => array(
array(
'alias' => 'Article',
'className' => 'Article',
'foreignKey' => 'article_id',
),
array(
'alias' => 'User',
'className' => 'User',
'foreignKey' => 'user_id',
),
)
);
$this->assertEqual($result, $expected);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$result = $this->Task->findBelongsTo($model, array());
$expected = array(
'belongsTo' => array(
array(
'alias' => 'ParentCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
)
);
$this->assertEqual($result, $expected);
}
/**
* test that hasOne and/or hasMany relations are generated properly.
*
* @return void
**/
function testHasManyHasOneGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Article'));
$this->Task->connection = 'test_suite';
$this->Task->listAll();
$result = $this->Task->findHasOneAndMany($model, array());
$expected = array(
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
),
),
'hasOne' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
),
),
);
$this->assertEqual($result, $expected);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$result = $this->Task->findHasOneAndMany($model, array());
$expected = array(
'hasOne' => array(
array(
'alias' => 'ChildCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
),
'hasMany' => array(
array(
'alias' => 'ChildCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
)
);
$this->assertEqual($result, $expected);
}
/**
* test that habtm generation works
*
* @return void
**/
function testHasAndBelongsToManyGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Article'));
$this->Task->connection = 'test_suite';
$this->Task->listAll();
$result = $this->Task->findHasAndBelongsToMany($model, array());
$expected = array(
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
),
),
);
$this->assertEqual($result, $expected);
}
/**
* test non interactive doAssociations
*
* @return void
**/
function testDoAssociationsNonInteractive() {
$this->Task->connection = 'test_suite';
$this->Task->interactive = false;
$model = new Model(array('ds' => 'test_suite', 'name' => 'Article'));
$result = $this->Task->doAssociations($model);
$expected = array(
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
),
),
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
),
),
);
}
/**
* Ensure that the fixutre object is correctly called.
*
* @return void
**/
function testBakeFixture() {
$this->Task->Fixture->expectAt(0, 'bake', array('Article', 'articles'));
$this->Task->bakeFixture('Article', 'articles');
$this->assertEqual($this->Task->plugin, $this->Task->Fixture->plugin);
$this->assertEqual($this->Task->connection, $this->Task->Fixture->connection);
}
/**
* Ensure that the test object is correctly called.
*
* @return void
**/
function testBakeTest() {
$this->Task->Test->expectAt(0, 'bake', array('Model', 'Article'));
$this->Task->bakeTest('Article');
$this->assertEqual($this->Task->plugin, $this->Task->Test->plugin);
$this->assertEqual($this->Task->connection, $this->Task->Test->connection);
}
/**
* test confirming of associations, and that when an association is hasMany
* a question for the hasOne is also not asked.
*
* @return void
**/
function testConfirmAssociations() {
$associations = array(
'hasOne' => array(
array(
'alias' => 'ChildCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
),
'hasMany' => array(
array(
'alias' => 'ChildCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
),
'belongsTo' => array(
array(
'alias' => 'User',
'className' => 'User',
'foreignKey' => 'user_id',
),
)
);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$this->Task->setReturnValueAt(0, 'in', 'y');
$result = $this->Task->confirmAssociations($model, $associations);
$this->assertTrue(empty($result['hasOne']));
$this->Task->setReturnValue('in', 'n');
$result = $this->Task->confirmAssociations($model, $associations);
$this->assertTrue(empty($result['hasMany']));
$this->assertTrue(empty($result['hasOne']));
}
/**
* test that inOptions generates questions and only accepts a valid answer
*
* @return void
**/
function testInOptions() {
$options = array('one', 'two', 'three');
$this->Task->expectAt(0, 'out', array('1. one'));
$this->Task->expectAt(1, 'out', array('2. two'));
$this->Task->expectAt(2, 'out', array('3. three'));
$this->Task->setReturnValueAt(0, 'in', 10);
$this->Task->expectAt(3, 'out', array('1. one'));
$this->Task->expectAt(4, 'out', array('2. two'));
$this->Task->expectAt(5, 'out', array('3. three'));
$this->Task->setReturnValueAt(1, 'in', 2);
$result = $this->Task->inOptions($options, 'Pick a number');
$this->assertEqual($result, 1);
}
/**
* test baking validation
*
* @return void
**/
function testBakeValidation() {
$validate = array(
'name' => array(
'notempty' => 'notempty'
),
'email' => array(
'email' => 'email',
),
'some_date' => array(
'date' => 'date'
),
'some_time' => array(
'time' => 'time'
)
);
$result = $this->Task->bake('Article', compact('validate'));
$this->assertPattern('/class Article extends AppModel \{/', $result);
$this->assertPattern('/\$name \= \'Article\'/', $result);
$this->assertPattern('/\$validate \= array\(/', $result);
$pattern = '/' . preg_quote("'notempty' => array('rule' => array('notempty')),", '/') . '/';
$this->assertPattern($pattern, $result);
}
/**
* test baking relations
*
* @return void
**/
function testBakeRelations() {
$associations = array(
'belongsTo' => array(
array(
'alias' => 'SomethingElse',
'className' => 'SomethingElse',
'foreignKey' => 'something_else_id',
),
array(
'alias' => 'User',
'className' => 'User',
'foreignKey' => 'user_id',
),
),
'hasOne' => array(
array(
'alias' => 'OtherModel',
'className' => 'OtherModel',
'foreignKey' => 'other_model_id',
),
),
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'parent_id',
),
),
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
),
)
);
$result = $this->Task->bake('Article', compact('associations'));
$this->assertPattern('/\$hasAndBelongsToMany \= array\(/', $result);
$this->assertPattern('/\$hasMany \= array\(/', $result);
$this->assertPattern('/\$belongsTo \= array\(/', $result);
$this->assertPattern('/\$hasOne \= array\(/', $result);
$this->assertPattern('/Tag/', $result);
$this->assertPattern('/OtherModel/', $result);
$this->assertPattern('/SomethingElse/', $result);
$this->assertPattern('/Comment/', $result);
}
/**
* test bake() with a -plugin param
*
* @return void
**/
function testBakeWithPlugin() {
$this->Task->plugin = 'ControllerTest';
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'models' . DS . 'article.php';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->bake('Article', array(), array());
$this->Task->plugin = 'controllerTest';
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'models' . DS . 'article.php';
$this->Task->expectAt(1, 'createFile', array(
$path, new PatternExpectation('/Article extends ControllerTestAppModel/')));
$this->Task->bake('Article', array(), array());
}
/**
* test that execute passes runs bake depending with named model.
*
* @return void
**/
function testExecuteWithNamedModel() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$filename = '/my/path/article.php';
$this->Task->setReturnValue('_checkUnitTest', 1);
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article extends AppModel/')));
$this->Task->execute();
}
/**
* test that execute runs all() when args[0] = all
*
* @return void
**/
function testExecuteIntoAll() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->Fixture->expectCallCount('bake', 5);
$this->Task->Test->expectCallCount('bake', 5);
$filename = '/my/path/article.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article/')));
$filename = '/my/path/articles_tag.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class ArticlesTag/')));
$filename = '/my/path/category_thread.php';
$this->Task->expectAt(2, 'createFile', array($filename, new PatternExpectation('/class CategoryThread/')));
$filename = '/my/path/comment.php';
$this->Task->expectAt(3, 'createFile', array($filename, new PatternExpectation('/class Comment/')));
$filename = '/my/path/tag.php';
$this->Task->expectAt(4, 'createFile', array($filename, new PatternExpectation('/class Tag/')));
$this->Task->execute();
}
/**
* test the interactive side of bake.
*
* @return void
**/
function testExecuteIntoInteractive() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '1'); //choose article
$this->Task->setReturnValueAt(1, 'in', 'n'); //no validation
$this->Task->setReturnValueAt(2, 'in', 'y'); //yes to associations
$this->Task->setReturnValueAt(3, 'in', 'y'); //yes to comment relation
$this->Task->setReturnValueAt(4, 'in', 'y'); //yes to user relation
$this->Task->setReturnValueAt(5, 'in', 'y'); //yes to tag relation
$this->Task->setReturnValueAt(6, 'in', 'n'); //no to additional assocs
$this->Task->setReturnValueAt(7, 'in', 'y'); //yes to looksGood?
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->Test->expectOnce('bake');
$this->Task->Fixture->expectOnce('bake');
$filename = '/my/path/article.php';
$this->Task->expectOnce('createFile');
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article/')));
$this->Task->execute();
}
/**
* test using bake interactively with a table that does not exist.
*
* @return void
**/
function testExecuteWithNonExistantTableName() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->expectOnce('_stop');
$this->Task->expectOnce('err');
$this->Task->setReturnValueAt(0, 'in', 'Foobar');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->execute();
}
}
?>

View file

@ -0,0 +1,252 @@
<?php
/* SVN FILE: $Id$ */
/**
* PluginTask Test file
*
* Test Case for plugin generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2006-2009, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2006-2009, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.3.0
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'plugin.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'model.php';
Mock::generatePartial(
'ShellDispatcher', 'TestPluginTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'PluginTask', 'MockPluginTask',
array('in', '_stop', 'err', 'out', 'createFile')
);
Mock::generate('ModelTask', 'PluginTestMockModelTask');
/**
* PluginTaskPlugin class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class PluginTaskTest extends CakeTestCase {
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestPluginTaskMockShellDispatcher();
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockPluginTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->path = TMP . 'tests' . DS;
}
/**
* startCase methods
*
* @return void
**/
function startCase() {
$this->_paths = $paths = App::path('plugins');
$this->_testPath = array_push($paths, TMP . 'tests' . DS);
App::build(array('plugins' => $paths));
}
/**
* endCase
*
* @return void
**/
function endCase() {
App::build(array('plugins' => $this->_paths));
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* test bake()
*
* @return void
**/
function testBakeFoldersAndFiles() {
$this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->bake('BakeTestPlugin');
$path = $this->Task->path . 'bake_test_plugin';
$this->assertTrue(is_dir($path), 'No plugin dir %s');
$this->assertTrue(is_dir($path . DS . 'config'), 'No config dir %s');
$this->assertTrue(is_dir($path . DS . 'config' . DS . 'sql'), 'No config dir %s');
$this->assertTrue(file_exists($path . DS . 'config' . DS . 'sql' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'controllers'), 'No controllers dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers' . DS .'components'), 'No components dir %s');
$this->assertTrue(file_exists($path . DS . 'controllers' . DS . 'components' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'models'), 'No models dir %s');
$this->assertTrue(file_exists($path . DS . 'models' . DS . 'behaviors' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'views'), 'No views dir %s');
$this->assertTrue(is_dir($path . DS . 'views' . DS . 'helpers'), 'No helpers dir %s');
$this->assertTrue(file_exists($path . DS . 'views' . DS . 'helpers' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'tests'), 'No tests dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases'), 'No cases dir %s');
$this->assertTrue(
is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'components'), 'No components cases dir %s'
);
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'components' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'behaviors'), 'No behaviors cases dir %s');
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'behaviors' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'helpers'), 'No helpers cases dir %s');
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'helpers' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'models'), 'No models cases dir %s');
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'models' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(
is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'controllers'),
'No controllers cases dir %s'
);
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'controllers' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'groups'), 'No groups dir %s');
$this->assertTrue(file_exists($path . DS . 'tests' . DS . 'groups' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
$this->assertTrue(file_exists($path . DS . 'tests' . DS . 'fixtures' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'vendors'), 'No vendors dir %s');
$this->assertTrue(is_dir($path . DS . 'vendors' . DS . 'css'), 'No vendors css dir %s');
$this->assertTrue(file_exists($path . DS . 'vendors' . DS . 'css' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'vendors' . DS . 'js'), 'No vendors js dir %s');
$this->assertTrue(file_exists($path . DS . 'vendors' . DS . 'js' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'vendors' . DS . 'img'), 'No vendors img dir %s');
$this->assertTrue(file_exists($path . DS . 'vendors' . DS . 'img' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'vendors' . DS . 'shells'), 'No vendors shells dir %s');
$this->assertTrue(file_exists($path . DS . 'vendors' . DS . 'shells' . DS . 'empty'), 'No empty file %s');
$file = $path . DS . 'bake_test_plugin_app_controller.php';
$this->Task->expectAt(0, 'createFile', array($file, '*'), 'No AppController %s');
$file = $path . DS . 'bake_test_plugin_app_model.php';
$this->Task->expectAt(1, 'createFile', array($file, '*'), 'No AppModel %s');
$Folder =& new Folder($this->Task->path . 'bake_test_plugin');
$Folder->delete();
}
/**
* test execute with no args, flowing into interactive,
*
* @return void
**/
function testExecuteWithNoArgs() {
$this->Task->setReturnValueAt(0, 'in', 'TestPlugin');
$this->Task->setReturnValueAt(1, 'in', '2');
$this->Task->setReturnValueAt(2, 'in', 'y');
$this->Task->setReturnValueAt(3, 'in', 'n');
$path = $this->Task->path . 'test_plugin';
$file = $path . DS . 'test_plugin_app_controller.php';
$this->Task->expectAt(0, 'createFile', array($file, '*'), 'No AppController %s');
$file = $path . DS . 'test_plugin_app_model.php';
$this->Task->expectAt(1, 'createFile', array($file, '*'), 'No AppModel %s');
$this->Task->args = array();
$this->Task->execute();
}
/**
* Test Execute
*
* @return void
**/
function testExecuteWithOneArg() {
$this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->Dispatch->args = array('BakeTestPlugin');
$this->Task->args =& $this->Task->Dispatch->args;
$path = $this->Task->path . 'bake_test_plugin';
$file = $path . DS . 'bake_test_plugin_app_controller.php';
$this->Task->expectAt(0, 'createFile', array($file, '*'), 'No AppController %s');
$file = $path . DS . 'bake_test_plugin_app_model.php';
$this->Task->expectAt(1, 'createFile', array($file, '*'), 'No AppModel %s');
$this->Task->execute();
$Folder =& new Folder($this->Task->path . 'bake_test_plugin');
$Folder->delete();
}
/**
* test execute chaining into MVC parts
*
* @return void
**/
function testExecuteWithTwoArgs() {
$this->Task->Model =& new PluginTestMockModelTask();
$this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y');
$Folder =& new Folder($this->Task->path . 'bake_test_plugin', true);
$this->Task->Dispatch->args = array('BakeTestPlugin', 'model');
$this->Task->args =& $this->Task->Dispatch->args;
$this->Task->Model->expectOnce('loadTasks');
$this->Task->Model->expectOnce('execute');
$this->Task->execute();
$Folder->delete();
}
}
?>

View file

@ -0,0 +1,172 @@
<?php
/**
* ProjectTask Test file
*
* Test Case for project generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2006-2009, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2006-2009, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.3.0
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
if (!class_exists('ProjectTask')) {
require CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'project.php';
}
Mock::generatePartial(
'ShellDispatcher', 'TestProjectTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ProjectTask', 'MockProjectTask',
array('in', '_stop', 'err', 'out', 'createFile')
);
/**
* ProjectTask Test class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ProjectTaskTest extends CakeTestCase {
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestProjectTaskMockShellDispatcher();
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockProjectTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->path = TMP . 'tests' . DS;
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
$Folder =& new Folder($this->Task->path . 'bake_test_app');
$Folder->delete();
}
/**
* creates a test project that is used for testing project task.
*
* @return void
**/
function _setupTestProject() {
$skel = CAKE_CORE_INCLUDE_PATH . DS . CONSOLE_LIBS . 'templates' . DS . 'skel';
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->bake($this->Task->path . 'bake_test_app', $skel);
}
/**
* test bake() method and directory creation.
*
* @return void
**/
function testBake() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app';
$this->assertTrue(is_dir($path), 'No project dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers'), 'No controllers dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers' . DS .'components'), 'No components dir %s');
$this->assertTrue(is_dir($path . DS . 'models'), 'No models dir %s');
$this->assertTrue(is_dir($path . DS . 'views'), 'No views dir %s');
$this->assertTrue(is_dir($path . DS . 'views' . DS . 'helpers'), 'No helpers dir %s');
$this->assertTrue(is_dir($path . DS . 'tests'), 'No tests dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases'), 'No cases dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'groups'), 'No groups dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
}
/**
* test generation of Security.salt
*
* @return void
**/
function testSecuritySaltGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$result = $this->Task->securitySalt($path);
$this->assertTrue($result);
$file =& new File($path . 'config' . DS . 'core.php');
$contents = $file->read();
$this->assertNoPattern('/DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi/', $contents, 'Default Salt left behind. %s');
}
/**
* test getAdmin method, and that it returns Routing.admin or writes to config file.
*
* @return void
**/
function testGetAdmin() {
Configure::write('Routing.admin', 'admin');
$result = $this->Task->getAdmin();
$this->assertEqual($result, 'admin_');
Configure::write('Routing.admin', null);
$this->_setupTestProject();
$this->Task->configPath = $this->Task->path . 'bake_test_app' . DS . 'config' . DS;
$this->Task->setReturnValue('in', 'super_duper_admin');
$result = $this->Task->getAdmin();
$this->assertEqual($result, 'super_duper_admin_');
}
/**
* Test execute method with one param to destination folder.
*
* @return void
**/
function testExecute() {
$this->Task->params['skel'] = CAKE_CORE_INCLUDE_PATH . DS . CONSOLE_LIBS . 'templates' . DS . 'skel';
$this->Task->params['working'] = TMP . 'tests' . DS;
$path = $this->Task->path . 'bake_test_app';
$this->Task->setReturnValue('in', 'y');
$this->Task->setReturnValueAt(0, 'in', $path);
$this->Task->execute();
$this->assertTrue(is_dir($path), 'No project dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers'), 'No controllers dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers' . DS .'components'), 'No components dir %s');
$this->assertTrue(is_dir($path . DS . 'models'), 'No models dir %s');
$this->assertTrue(is_dir($path . DS . 'views'), 'No views dir %s');
$this->assertTrue(is_dir($path . DS . 'views' . DS . 'helpers'), 'No helpers dir %s');
$this->assertTrue(is_dir($path . DS . 'tests'), 'No tests dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases'), 'No cases dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'groups'), 'No groups dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
}
}
?>

View file

@ -0,0 +1,167 @@
<?php
/**
* TemplateTask file
*
* Test Case for TemplateTask generation shell task
*
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
Mock::generatePartial(
'ShellDispatcher', 'TestTemplateTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'TemplateTask', 'MockTemplateTask',
array('in', 'out', 'err', 'createFile', '_stop')
);
/**
* TemplateTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TemplateTaskTest extends CakeTestCase {
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestTemplateTaskMockShellDispatcher();
$this->Task =& new MockTemplateTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Dispatch->shellPaths = App::path('shells');
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* test that set sets variables
*
* @return void
**/
function testSet() {
$this->Task->set('one', 'two');
$this->assertTrue(isset($this->Task->templateVars['one']));
$this->assertEqual($this->Task->templateVars['one'], 'two');
$this->Task->set(array('one' => 'three', 'four' => 'five'));
$this->assertTrue(isset($this->Task->templateVars['one']));
$this->assertEqual($this->Task->templateVars['one'], 'three');
$this->assertTrue(isset($this->Task->templateVars['four']));
$this->assertEqual($this->Task->templateVars['four'], 'five');
}
/**
* test finding themes installed in
*
* @return void
**/
function testFindingInstalledThemesForBake() {
$consoleLibs = CAKE_CORE_INCLUDE_PATH . DS . CONSOLE_LIBS;
$this->Task->Dispatch->shellPaths = array($consoleLibs);
$this->Task->initialize();
$this->assertEqual($this->Task->templatePaths, array('default' => $consoleLibs . 'templates' . DS . 'default' . DS));
}
/**
* test getting the correct theme name. Ensure that with only one theme, or a theme param
* that the user is not bugged. If there are more, find and return the correct theme name
*
* @return void
**/
function testGetThemePath() {
$defaultTheme = CAKE_CORE_INCLUDE_PATH . DS . CONSOLE_LIBS . 'templates' . DS . 'default' .DS;
$this->Task->templatePaths = array('default' => $defaultTheme);
$this->Task->expectCallCount('in', 1);
$result = $this->Task->getThemePath();
$this->assertEqual($result, $defaultTheme);
$this->Task->templatePaths = array('default' => $defaultTheme, 'other' => '/some/path');
$this->Task->params['theme'] = 'other';
$result = $this->Task->getThemePath();
$this->assertEqual($result, '/some/path');
$this->Task->params = array();
$this->Task->setReturnValueAt(0, 'in', '1');
$result = $this->Task->getThemePath();
$this->assertEqual($result, $defaultTheme);
$this->assertEqual($this->Dispatcher->params['theme'], 'default');
}
/**
* test generate
*
* @return void
**/
function testGenerate() {
$this->Task->Dispatch->shellPaths = array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'shells' . DS
);
$this->Task->initialize();
$result = $this->Task->generate('classes', 'test_object', array('test' => 'foo'));
$expected = "I got rendered\nfoo";
$this->assertEqual($result, $expected);
}
/**
* test generate with a missing template in the chosen theme.
* ensure fallback to default works.
*
* @return void
**/
function testGenerateWithTemplateFallbacks() {
$this->Task->Dispatch->shellPaths = array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'shells' . DS,
CAKE_CORE_INCLUDE_PATH . DS . CONSOLE_LIBS
);
$this->Task->initialize();
$this->Task->params['theme'] = 'test';
$this->Task->set(array(
'model' => 'Article',
'table' => 'articles',
'import' => false,
'records' => false,
'schema' => ''
));
$result = $this->Task->generate('classes', 'fixture');
$this->assertPattern('/ArticleFixture extends CakeTestFixture/', $result);
}
}
?>

View file

@ -8,23 +8,21 @@
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP : Rapid Development Framework (http://www.cakephp.org) * CakePHP : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2006-2008, Cake Software Foundation, Inc. * Copyright 2006-2009, Cake Software Foundation, Inc.
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright 2006-2008, Cake Software Foundation, Inc. * @copyright Copyright 2006-2009, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake * @package cake
* @subpackage cake.tests.cases.console.libs.tasks * @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726 * @since CakePHP v 1.2.0.7726
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
App::import('Core', 'Shell'); App::import('Core', 'Shell');
App::import('Core', array('Controller', 'Model'));
if (!defined('DISABLE_AUTO_DISPATCH')) { if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true); define('DISABLE_AUTO_DISPATCH', true);
@ -39,16 +37,82 @@ if (!class_exists('ShellDispatcher')) {
if (!class_exists('TestTask')) { if (!class_exists('TestTask')) {
require CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'test.php'; require CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'test.php';
require CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
} }
Mock::generatePartial( Mock::generatePartial(
'ShellDispatcher', 'TestTestTaskMockShellDispatcher', 'ShellDispatcher', 'TestTestTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment') array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
); );
Mock::generatePartial( Mock::generatePartial(
'TestTask', 'MockTestTask', 'TestTask', 'MockTestTask',
array('in', 'out', 'createFile') array('in', '_stop', 'err', 'out', 'createFile', 'isLoadableClass')
); );
/**
* Test subject models for fixture generation
**/
class TestTaskArticle extends Model {
var $name = 'TestTaskArticle';
var $useTable = 'articles';
var $hasMany = array(
'Comment' => array(
'className' => 'TestTask.TestTaskComment',
'foreignKey' => 'article_id',
)
);
var $hasAndBelongsToMany = array(
'Tag' => array(
'className' => 'TestTaskTag',
'joinTable' => 'articles_tags',
'foreignKey' => 'article_id',
'associationForeignKey' => 'tag_id'
)
);
function doSomething() {
}
function doSomethingElse() {
}
function _innerMethod() {
}
}
class TestTaskTag extends Model {
var $name = 'TestTaskTag';
var $useTable = 'tags';
var $hasAndBelongsToMany = array(
'Article' => array(
'className' => 'TestTaskArticle',
'joinTable' => 'articles_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'article_id'
)
);
}
/**
* Simulated Plugin
**/
class TestTaskAppModel extends Model {
}
class TestTaskComment extends TestTaskAppModel {
var $name = 'TestTaskComment';
var $useTable = 'comments';
var $belongsTo = array(
'Article' => array(
'className' => 'TestTaskArticle',
'foreignKey' => 'article_id',
)
);
}
class TestTaskCommentsController extends Controller {
var $name = 'TestTaskComments';
var $uses = array('TestTaskComment', 'TestTaskTag');
}
/** /**
* TestTaskTest class * TestTaskTest class
* *
@ -56,24 +120,28 @@ Mock::generatePartial(
* @subpackage cake.tests.cases.console.libs.tasks * @subpackage cake.tests.cases.console.libs.tasks
*/ */
class TestTaskTest extends CakeTestCase { class TestTaskTest extends CakeTestCase {
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/** /**
* setUp method * startTest method
* *
* @return void * @return void
* @access public * @access public
*/ */
function setUp() { function startTest() {
$this->Dispatcher =& new TestTestTaskMockShellDispatcher(); $this->Dispatcher =& new TestTestTaskMockShellDispatcher();
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockTestTask($this->Dispatcher); $this->Task =& new MockTestTask($this->Dispatcher);
$this->Task->Dispatch = new $this->Dispatcher; $this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Template =& new TemplateTask($this->Dispatcher);
} }
/** /**
* tearDown method * endTest method
* *
* @return void * @return void
* @access public * @access public
*/ */
function tearDown() { function endTest() {
ClassRegistry::flush(); ClassRegistry::flush();
} }
/** /**
@ -88,13 +156,296 @@ class TestTaskTest extends CakeTestCase {
$this->Task->Dispatch->expectNever('stderr'); $this->Task->Dispatch->expectNever('stderr');
$this->Task->Dispatch->expectNever('_stop'); $this->Task->Dispatch->expectNever('_stop');
$this->Task->setReturnValueAt(0, 'in', 'y'); $this->Task->setReturnValue('in', 'y');
$this->Task->expectAt(0, 'createFile', array($file, '*')); $this->Task->expectAt(0, 'createFile', array($file, '*'));
$this->Task->bake('Model', 'MyClass'); $this->Task->bake('Model', 'MyClass');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->expectAt(1, 'createFile', array($file, '*')); $this->Task->expectAt(1, 'createFile', array($file, '*'));
$this->Task->bake('Model', 'MyClass'); $this->Task->bake('Model', 'MyClass');
$file = TESTS . 'cases' . DS . 'controllers' . DS . 'comments_controller.test.php';
$this->Task->expectAt(2, 'createFile', array($file, '*'));
$this->Task->bake('Controller', 'Comments');
}
/**
* Test that method introspection pulls all relevant non parent class
* methods into the test case.
*
* @return void
**/
function testMethodIntrospection() {
$result = $this->Task->getTestableMethods('TestTaskArticle');
$expected = array('doSomething', 'doSomethingElse');
$this->assertEqual($result, $expected);
}
/**
* test that the generation of fixtures works correctly.
*
* @return void
**/
function testFixtureArrayGenerationFromModel() {
$subject = ClassRegistry::init('TestTaskArticle');
$result = $this->Task->generateFixtureList($subject);
$expected = array('plugin.test_task.test_task_comment', 'app.articles_tags',
'app.test_task_article', 'app.test_task_tag');
$this->assertEqual(sort($result), sort($expected));
}
/**
* test that the generation of fixtures works correctly.
*
* @return void
**/
function testFixtureArrayGenerationFromController() {
$subject = new TestTaskCommentsController();
$result = $this->Task->generateFixtureList($subject);
$expected = array('plugin.test_task.test_task_comment', 'app.articles_tags',
'app.test_task_article', 'app.test_task_tag');
$this->assertEqual(sort($result), sort($expected));
}
/**
* test user interaction to get object type
*
* @return void
**/
function testGetObjectType() {
$this->Task->expectOnce('_stop');
$this->Task->setReturnValueAt(0, 'in', 'q');
$this->Task->getObjectType();
$this->Task->setReturnValueAt(1, 'in', 2);
$result = $this->Task->getObjectType();
$this->assertEqual($result, $this->Task->classTypes[1]);
}
/**
* creating test subjects should clear the registry so the registry is always fresh
*
* @return void
**/
function testRegistryClearWhenBuildingTestObjects() {
ClassRegistry::flush();
$model = ClassRegistry::init('TestTaskComment');
$model->bindModel(array(
'belongsTo' => array(
'Random' => array(
'className' => 'TestTaskArticle',
'foreignKey' => 'article_id',
)
)
));
$keys = ClassRegistry::keys();
$this->assertTrue(in_array('random', $keys));
$object =& $this->Task->buildTestSubject('Model', 'TestTaskComment');
$keys = ClassRegistry::keys();
$this->assertFalse(in_array('random', $keys));
}
/**
* test that getClassName returns the user choice as a classname.
*
* @return void
**/
function testGetClassName() {
$objects = Configure::listObjects('model');
$skip = $this->skipIf(empty($objects), 'No models in app, this test will fail. %s');
if ($skip) {
return;
}
$this->Task->setReturnValueAt(0, 'in', 'MyCustomClass');
$result = $this->Task->getClassName('Model');
$this->assertEqual($result, 'MyCustomClass');
$this->Task->setReturnValueAt(1, 'in', 1);
$result = $this->Task->getClassName('Model');
$options = Configure::listObjects('model');
$this->assertEqual($result, $options[0]);
}
/**
* Test the user interaction for defining additional fixtures.
*
* @return void
**/
function testGetUserFixtures() {
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'app.pizza, app.topping, app.side_dish');
$result = $this->Task->getUserFixtures();
$expected = array('app.pizza', 'app.topping', 'app.side_dish');
$this->assertEqual($result, $expected);
}
/**
* test that resolving classnames works
*
* @return void
**/
function testGetRealClassname() {
$result = $this->Task->getRealClassname('Model', 'Post');
$this->assertEqual($result, 'Post');
$result = $this->Task->getRealClassname('Controller', 'Posts');
$this->assertEqual($result, 'PostsController');
$result = $this->Task->getRealClassname('Helper', 'Form');
$this->assertEqual($result, 'FormHelper');
$result = $this->Task->getRealClassname('Behavior', 'Containable');
$this->assertEqual($result, 'ContainableBehavior');
$result = $this->Task->getRealClassname('Component', 'Auth');
$this->assertEqual($result, 'AuthComponent');
}
/**
* test baking files.
*
* @return void
**/
function testBakeModelTest() {
$this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('isLoadableClass', true);
$result = $this->Task->bake('Model', 'TestTaskArticle');
$this->assertPattern('/App::import\(\'Model\', \'TestTaskArticle\'\)/', $result);
$this->assertPattern('/class TestTaskArticleTestCase extends CakeTestCase/', $result);
$this->assertPattern('/function startTest\(\)/', $result);
$this->assertPattern("/\\\$this->TestTaskArticle \=\& ClassRegistry::init\('TestTaskArticle'\)/", $result);
$this->assertPattern('/function endTest\(\)/', $result);
$this->assertPattern('/unset\(\$this->TestTaskArticle\)/', $result);
$this->assertPattern('/function testDoSomething\(\)/', $result);
$this->assertPattern('/function testDoSomethingElse\(\)/', $result);
$this->assertPattern("/'app\.test_task_article'/", $result);
$this->assertPattern("/'plugin\.test_task\.test_task_comment'/", $result);
$this->assertPattern("/'app\.test_task_tag'/", $result);
$this->assertPattern("/'app\.articles_tag'/", $result);
}
/**
* test baking controller test files, ensure that the stub class is generated.
*
* @return void
**/
function testBakeControllerTest() {
$this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('isLoadableClass', true);
$result = $this->Task->bake('Controller', 'TestTaskComments');
$this->assertPattern('/App::import\(\'Controller\', \'TestTaskComments\'\)/', $result);
$this->assertPattern('/class TestTaskCommentsControllerTestCase extends CakeTestCase/', $result);
$this->assertPattern('/class TestTestTaskCommentsController extends TestTaskCommentsController/', $result);
$this->assertPattern('/var \$autoRender = false/', $result);
$this->assertPattern('/function redirect\(\$url, \$status = null, \$exit = true\)/', $result);
$this->assertPattern('/function startTest\(\)/', $result);
$this->assertPattern("/\\\$this->TestTaskComments \=\& new TestTestTaskCommentsController()/", $result);
$this->assertPattern('/function endTest\(\)/', $result);
$this->assertPattern('/unset\(\$this->TestTaskComments\)/', $result);
$this->assertPattern("/'app\.test_task_article'/", $result);
$this->assertPattern("/'plugin\.test_task\.test_task_comment'/", $result);
$this->assertPattern("/'app\.test_task_tag'/", $result);
$this->assertPattern("/'app\.articles_tag'/", $result);
}
/**
* test Constructor generation ensure that constructClasses is called for controllers
*
* @return void
**/
function testGenerateContsructor() {
$result = $this->Task->generateConstructor('controller', 'PostsController');
$expected = "new TestPostsController();\n\t\t\$this->PostsController->constructClasses();\n";
$this->assertEqual($result, $expected);
$result = $this->Task->generateConstructor('model', 'Post');
$expected = "ClassRegistry::init('Post');\n";
$this->assertEqual($result, $expected);
$result = $this->Task->generateConstructor('helper', 'FormHelper');
$expected = "new FormHelper()\n";
$this->assertEqual($result, $expected);
}
/**
* Test that mock class generation works for the appropriate classes
*
* @return void
**/
function testMockClassGeneration() {
$result = $this->Task->hasMockClass('controller');
$this->assertTrue($result);
}
/**
* test bake() with a -plugin param
*
* @return void
**/
function testBakeWithPlugin() {
$this->Task->plugin = 'TestTest';
$path = APP . 'plugins' . DS . 'test_test' . DS . 'tests' . DS . 'cases' . DS . 'helpers' . DS . 'form.test.php';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->bake('Helper', 'Form');
}
/**
* Test filename generation for each type + plugins
*
* @return void
**/
function testTestCaseFileName() {
$this->Task->path = '/my/path/tests/';
$result = $this->Task->testCaseFileName('Model', 'Post');
$expected = $this->Task->path . 'cases' . DS . 'models' . DS . 'post.test.php';
$this->assertEqual($result, $expected);
$result = $this->Task->testCaseFileName('Helper', 'Form');
$expected = $this->Task->path . 'cases' . DS . 'helpers' . DS . 'form.test.php';
$this->assertEqual($result, $expected);
$result = $this->Task->testCaseFileName('Controller', 'Posts');
$expected = $this->Task->path . 'cases' . DS . 'controllers' . DS . 'posts_controller.test.php';
$this->assertEqual($result, $expected);
$result = $this->Task->testCaseFileName('Behavior', 'Containable');
$expected = $this->Task->path . 'cases' . DS . 'behaviors' . DS . 'containable.test.php';
$this->assertEqual($result, $expected);
$result = $this->Task->testCaseFileName('Component', 'Auth');
$expected = $this->Task->path . 'cases' . DS . 'components' . DS . 'auth.test.php';
$this->assertEqual($result, $expected);
$this->Task->plugin = 'TestTest';
$result = $this->Task->testCaseFileName('Model', 'Post');
$expected = APP . 'plugins' . DS . 'test_test' . DS . 'tests' . DS . 'cases' . DS . 'models' . DS . 'post.test.php';
$this->assertEqual($result, $expected);
}
/**
* test execute with a type defined
*
* @return void
**/
function testExecuteWithOneArg() {
$this->Task->args[0] = 'Model';
$this->Task->setReturnValueAt(0, 'in', 'TestTaskTag');
$this->Task->setReturnValue('isLoadableClass', true);
$this->Task->expectAt(0, 'createFile', array('*', new PatternExpectation('/class TestTaskTagTestCase extends CakeTestCase/')));
$this->Task->execute();
}
/**
* test execute with type and class name defined
*
* @return void
**/
function testExecuteWithTwoArgs() {
$this->Task->args = array('Model', 'TestTaskTag');
$this->Task->setReturnValueAt(0, 'in', 'TestTaskTag');
$this->Task->setReturnValue('isLoadableClass', true);
$this->Task->expectAt(0, 'createFile', array('*', new PatternExpectation('/class TestTaskTagTestCase extends CakeTestCase/')));
$this->Task->execute();
} }
} }
?> ?>

View file

@ -0,0 +1,426 @@
<?php
/**
* ViewTask Test file
*
* Test Case for view generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2006-2008, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2006-2008, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'view.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'controller.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'project.php';
Mock::generatePartial(
'ShellDispatcher', 'TestViewTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ViewTask', 'MockViewTask',
array('in', '_stop', 'err', 'out', 'createFile')
);
Mock::generate('ControllerTask', 'ViewTaskMockControllerTask');
Mock::generate('ProjectTask', 'ViewTaskMockProjectTask');
class ViewTaskComment extends Model {
var $name = 'ViewTaskComment';
var $useTable = 'comments';
var $belongsTo = array(
'Article' => array(
'className' => 'ViewTaskArticle',
'foreignKey' => 'article_id'
)
);
}
class ViewTaskArticle extends Model {
var $name = 'ViewTaskArticle';
var $useTable = 'articles';
}
class ViewTaskCommentsController extends Controller {
var $name = 'ViewTaskComments';
function index() {
}
function add() {
}
}
class ViewTaskArticlesController extends Controller {
var $name = 'ViewTaskArticles';
function index() {
}
function add() {
}
function admin_index() {
}
function admin_add() {
}
function admin_view() {
}
function admin_edit() {
}
function admin_delete() {
}
}
/**
* ViewTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskTest extends CakeTestCase {
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestViewTaskMockShellDispatcher();
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockViewTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Template =& new TemplateTask($this->Dispatcher);
$this->Task->Controller =& new ViewTaskMockControllerTask();
$this->Task->Project =& new ViewTaskMockProjectTask();
$this->Task->path = TMP;
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* Test getContent and parsing of Templates.
*
* @return void
**/
function testGetContent() {
$vars = array(
'modelClass' => 'TestViewModel',
'schema' => array(),
'primaryKey' => 'id',
'displayField' => 'name',
'singularVar' => 'testViewModel',
'pluralVar' => 'testViewModels',
'singularHumanName' => 'Test View Model',
'pluralHumanName' => 'Test View Models',
'fields' => array('id', 'name', 'body'),
'associations' => array()
);
$result = $this->Task->getContent('view', $vars);
$this->assertPattern('/Delete Test View Model/', $result);
$this->assertPattern('/Edit Test View Model/', $result);
$this->assertPattern('/List Test View Models/', $result);
$this->assertPattern('/New Test View Model/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'id\'\]/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'name\'\]/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'body\'\]/', $result);
}
/**
* test getContent() using an admin_prefixed action.
*
* @return void
**/
function testGetContentWithAdminAction() {
$_back = Configure::read('Routing.admin');
Configure::write('Routing.admin', 'admin');
$vars = array(
'modelClass' => 'TestViewModel',
'schema' => array(),
'primaryKey' => 'id',
'displayField' => 'name',
'singularVar' => 'testViewModel',
'pluralVar' => 'testViewModels',
'singularHumanName' => 'Test View Model',
'pluralHumanName' => 'Test View Models',
'fields' => array('id', 'name', 'body'),
'associations' => array()
);
$result = $this->Task->getContent('admin_view', $vars);
$this->assertPattern('/Delete Test View Model/', $result);
$this->assertPattern('/Edit Test View Model/', $result);
$this->assertPattern('/List Test View Models/', $result);
$this->assertPattern('/New Test View Model/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'id\'\]/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'name\'\]/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'body\'\]/', $result);
Configure::write('Routing.admin', $_back);
}
/**
* test Bake method
*
* @return void
**/
function testBake() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expectAt(0, 'createFile', array(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PatternExpectation('/View Task Articles/')
));
$this->Task->bake('view', true);
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'edit.ctp', '*'));
$this->Task->bake('edit', true);
$this->Task->expectAt(2, 'createFile', array(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PatternExpectation('/\$viewTaskComment\[\'Article\'\]\[\'title\'\]/')
));
$this->Task->bake('index', true);
}
/**
* test bake() with a -plugin param
*
* @return void
**/
function testBakeWithPlugin() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->plugin = 'TestTest';
$path = APP . 'plugins' . DS . 'test_test' . DS . 'views' . DS . 'view_task_comments' . DS . 'view.ctp';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->bake('view', true);
}
/**
* test bake actions baking multiple actions.
*
* @return void
**/
function testBakeActions() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expectAt(0, 'createFile', array(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PatternExpectation('/ViewTaskComments/')
));
$this->Task->expectAt(1, 'createFile', array(
TMP . 'view_task_comments' . DS . 'edit.ctp',
new PatternExpectation('/Edit ViewTaskComment/')
));
$this->Task->expectAt(2, 'createFile', array(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->bakeActions(array('view', 'edit', 'index'), array());
}
/**
* test baking a customAction (non crud)
*
* @return void
**/
function testCustomAction() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->params['app'] = APP;
$this->Task->setReturnValueAt(0, 'in', '');
$this->Task->setReturnValueAt(1, 'in', 'my_action');
$this->Task->setReturnValueAt(2, 'in', 'y');
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'my_action.ctp', '*'));
$this->Task->customAction();
}
/**
* Test all()
*
* @return void
**/
function testExecuteIntoAll() {
$this->Task->args[0] = 'all';
$this->Task->Controller->setReturnValue('listAll', array('view_task_comments'));
$this->Task->Controller->expectOnce('listAll');
$this->Task->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'index.ctp', '*'));
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'view.ctp', '*'));
$this->Task->expectAt(2, 'createFile', array(TMP . 'view_task_comments' . DS . 'add.ctp', '*'));
$this->Task->expectAt(3, 'createFile', array(TMP . 'view_task_comments' . DS . 'edit.ctp', '*'));
$this->Task->execute();
}
/**
* test `cake bake view $controller view`
*
* @return void
**/
function testExecuteWithActionParam() {
$this->Task->args[0] = 'ViewTaskComments';
$this->Task->args[1] = 'view';
$this->Task->expectCallCount('createFile', 1);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'view.ctp', '*'));
$this->Task->execute();
}
/**
* test `cake bake view $controller`
* Ensure that views are only baked for actions that exist in the controller.
*
* @return void
**/
function testExecuteWithController() {
$this->Task->args[0] = 'ViewTaskComments';
$this->Task->expectCallCount('createFile', 2);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'index.ctp', '*'));
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'add.ctp', '*'));
$this->Task->execute();
}
/**
* test `cake bake view $controller -admin`
* Which only bakes admin methods, not non-admin methods.
*
* @return void
**/
function testExecuteWithControllerAndAdminFlag() {
$_back = Configure::read('Routing.admin');
Configure::write('Routing.admin', 'admin');
$this->Task->args[0] = 'ViewTaskArticles';
$this->Task->params['admin'] = 1;
$this->Task->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_articles' . DS . 'admin_index.ctp', '*'));
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_articles' . DS . 'admin_add.ctp', '*'));
$this->Task->expectAt(2, 'createFile', array(TMP . 'view_task_articles' . DS . 'admin_view.ctp', '*'));
$this->Task->expectAt(3, 'createFile', array(TMP . 'view_task_articles' . DS . 'admin_edit.ctp', '*'));
$this->Task->execute();
Configure::write('Routing.admin', $_back);
}
/**
* test execute into interactive.
*
* @return void
**/
function testExecuteInteractive() {
$this->Task->connection = 'test_suite';
$this->Task->args = array();
$this->Task->params = array();
$this->Task->Controller->setReturnValue('getName', 'ViewTaskComments');
$this->Task->setReturnValue('in', 'y');
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', 'n');
$this->Task->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->expectAt(1, 'createFile', array(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->expectAt(2, 'createFile', array(
TMP . 'view_task_comments' . DS . 'add.ctp',
new PatternExpectation('/Add ViewTaskComment/')
));
$this->Task->expectAt(3, 'createFile', array(
TMP . 'view_task_comments' . DS . 'edit.ctp',
new PatternExpectation('/Edit ViewTaskComment/')
));
$this->Task->execute();
}
/**
* test execute into interactive() with admin methods.
*
* @return void
**/
function testExecuteInteractiveWithAdmin() {
Configure::write('Routing.admin', 'admin');
$this->Task->connection = 'test_suite';
$this->Task->args = array();
$this->Task->Controller->setReturnValue('getName', 'ViewTaskComments');
$this->Task->Project->setReturnValue('getAdmin', 'admin_');
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->setReturnValueAt(2, 'in', 'y');
$this->Task->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(
TMP . 'view_task_comments' . DS . 'admin_index.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->expectAt(1, 'createFile', array(
TMP . 'view_task_comments' . DS . 'admin_view.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->expectAt(2, 'createFile', array(
TMP . 'view_task_comments' . DS . 'admin_add.ctp',
new PatternExpectation('/Add ViewTaskComment/')
));
$this->Task->expectAt(3, 'createFile', array(
TMP . 'view_task_comments' . DS . 'admin_edit.ctp',
new PatternExpectation('/Edit ViewTaskComment/')
));
$this->Task->execute();
}
}
?>

View file

@ -144,6 +144,18 @@ class CakeSocketTest extends CakeTestCase {
$this->Socket = new CakeSocket(array('timeout' => 5)); $this->Socket = new CakeSocket(array('timeout' => 5));
$this->Socket->connect(); $this->Socket->connect();
$this->assertEqual($this->Socket->read(26), null); $this->assertEqual($this->Socket->read(26), null);
$config = array('host' => 'www.cakephp.org', 'timeout' => 1);
$this->Socket = new CakeSocket($config);
$this->assertTrue($this->Socket->connect());
$this->assertFalse($this->Socket->read(1024 * 1024));
$this->assertEqual($this->Socket->lastError(), '2: ' . __('Connection timed out', true));
$config = array('host' => 'www.cakephp.org', 'timeout' => 30);
$this->Socket = new CakeSocket($config);
$this->assertTrue($this->Socket->connect());
$this->assertEqual($this->Socket->read(26), null);
$this->assertEqual($this->Socket->lastError(), null);
} }
/** /**
* testLastError method * testLastError method

View file

@ -228,6 +228,7 @@ class CakeTestCaseTest extends CakeTestCase {
$this->Case->before('start'); $this->Case->before('start');
$this->expectError(); $this->expectError();
$this->Case->loadFixtures('Wrong!'); $this->Case->loadFixtures('Wrong!');
$this->Case->end();
} }
/** /**
* testGetTests Method * testGetTests Method
@ -268,6 +269,10 @@ class CakeTestCaseTest extends CakeTestCase {
$result = $this->Case->testAction('/tests_apps/set_action', array('return' => 'vars')); $result = $this->Case->testAction('/tests_apps/set_action', array('return' => 'vars'));
$this->assertEqual($result, array('var' => 'string')); $this->assertEqual($result, array('var' => 'string'));
$db =& ConnectionManager::getDataSource('test_suite');
$fixture =& new PostFixture();
$fixture->create($db);
$result = $this->Case->testAction('/tests_apps_posts/add', array('return' => 'vars')); $result = $this->Case->testAction('/tests_apps_posts/add', array('return' => 'vars'));
$this->assertTrue(array_key_exists('posts', $result)); $this->assertTrue(array_key_exists('posts', $result));
$this->assertEqual(count($result['posts']), 1); $this->assertEqual(count($result['posts']), 1);
@ -309,7 +314,7 @@ class CakeTestCaseTest extends CakeTestCase {
) )
)); ));
$this->assertEqual(array_keys($result['data']), array('name', 'pork')); $this->assertEqual(array_keys($result['data']), array('name', 'pork'));
$fixture->drop($db);
$db =& ConnectionManager::getDataSource('test_suite'); $db =& ConnectionManager::getDataSource('test_suite');
$_backPrefix = $db->config['prefix']; $_backPrefix = $db->config['prefix'];
@ -319,11 +324,11 @@ class CakeTestCaseTest extends CakeTestCase {
$config['prefix'] = 'cake_testcase_test_'; $config['prefix'] = 'cake_testcase_test_';
ConnectionManager::create('cake_test_case', $config); ConnectionManager::create('cake_test_case', $config);
$db =& ConnectionManager::getDataSource('cake_test_case'); $db2 =& ConnectionManager::getDataSource('cake_test_case');
$fixture =& new PostFixture($db); $fixture =& new PostFixture($db2);
$fixture->create($db); $fixture->create($db2);
$fixture->insert($db); $fixture->insert($db2);
$result = $this->Case->testAction('/tests_apps_posts/fixtured', array( $result = $this->Case->testAction('/tests_apps_posts/fixtured', array(
'return' => 'vars', 'return' => 'vars',
@ -332,15 +337,12 @@ class CakeTestCaseTest extends CakeTestCase {
)); ));
$this->assertTrue(isset($result['posts'])); $this->assertTrue(isset($result['posts']));
$this->assertEqual(count($result['posts']), 3); $this->assertEqual(count($result['posts']), 3);
$tables = $db->listSources(true); $tables = $db2->listSources();
$this->assertFalse(in_array('cake_testaction_test_suite_posts', $tables)); $this->assertFalse(in_array('cake_testaction_test_suite_posts', $tables));
$fixture->drop($db); $fixture->drop($db2);
$db =& ConnectionManager::getDataSource('test_suite'); $db =& ConnectionManager::getDataSource('test_suite');
$db->config['prefix'] = $_backPrefix;
$fixture->drop($db);
//test that drop tables behaves as exepected with testAction //test that drop tables behaves as exepected with testAction
$db =& ConnectionManager::getDataSource('test_suite'); $db =& ConnectionManager::getDataSource('test_suite');

View file

@ -114,6 +114,23 @@ class ConfigureTest extends CakeTestCase {
Configure::write('SomeName.someKey', null); Configure::write('SomeName.someKey', null);
$result = Configure::read('SomeName.someKey'); $result = Configure::read('SomeName.someKey');
$this->assertEqual($result, null); $this->assertEqual($result, null);
$expected = array('One' => array('Two' => array('Three' => array('Four' => array('Five' => 'cool')))));
Configure::write('Key', $expected);
$result = Configure::read('Key');
$this->assertEqual($expected, $result);
$result = Configure::read('Key.One');
$this->assertEqual($expected['One'], $result);
$result = Configure::read('Key.One.Two');
$this->assertEqual($expected['One']['Two'], $result);
$result = Configure::read('Key.One.Two.Three.Four.Five');
$this->assertEqual('cool', $result);
} }
/** /**
* testSetErrorReporting Level * testSetErrorReporting Level

View file

@ -337,7 +337,8 @@ MSGBLOC;
// TODO: better test for format of message sent? // TODO: better test for format of message sent?
$this->Controller->EmailTest->sendAs = 'both'; $this->Controller->EmailTest->sendAs = 'both';
$expect = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="alt-"' . "\n", $message); $expect = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="alt-"', $message);
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect)); $this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
} }
@ -412,10 +413,11 @@ HTMLBLOC;
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect)); $this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
$this->Controller->EmailTest->sendAs = 'both'; $this->Controller->EmailTest->sendAs = 'both';
$expect = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="alt-"' . "\n", $header); $expect = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="alt-"', $header);
$expect .= '--alt-' . "\n" . 'Content-Type: text/plain; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 7bit' . "\n\n" . $text . "\n\n"; $expect .= '--alt-' . "\n" . 'Content-Type: text/plain; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 7bit' . "\n\n" . $text . "\n\n";
$expect .= '--alt-' . "\n" . 'Content-Type: text/html; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 7bit' . "\n\n" . $html . "\n\n"; $expect .= '--alt-' . "\n" . 'Content-Type: text/html; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 7bit' . "\n\n" . $html . "\n\n";
$expect = '<pre>' . $expect . '--alt---' . "\n\n" . '</pre>'; $expect = '<pre>' . $expect . '--alt---' . "\n\n" . '</pre>';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect)); $this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
@ -556,6 +558,66 @@ TEXTBLOC;
preg_match('/Subject: (.*)Header:/s', $this->Controller->Session->read('Message.email.message'), $matches); preg_match('/Subject: (.*)Header:/s', $this->Controller->Session->read('Message.email.message'), $matches);
$this->assertEqual(trim($matches[1]), $subject); $this->assertEqual(trim($matches[1]), $subject);
} }
/**
* undocumented function
*
* @return void
* @access public
*/
function testSendAsIsNotIgnoredIfAttachmentsPresent() {
$this->Controller->EmailTest->reset();
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Attachment Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'debug';
$this->Controller->EmailTest->attachments = array(__FILE__);
$body = '<p>This is the body of the message</p>';
$this->Controller->EmailTest->sendAs = 'html';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = $this->Controller->Session->read('Message.email.message');
$this->assertNoPattern('/text\/plain/', $msg);
$this->assertPattern('/text\/html/', $msg);
$this->Controller->EmailTest->sendAs = 'text';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = $this->Controller->Session->read('Message.email.message');
$this->assertPattern('/text\/plain/', $msg);
$this->assertNoPattern('/text\/html/', $msg);
$this->Controller->EmailTest->sendAs = 'both';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = $this->Controller->Session->read('Message.email.message');
$this->assertNoPattern('/text\/plain/', $msg);
$this->assertNoPattern('/text\/html/', $msg);
$this->assertPattern('/multipart\/alternative/', $msg);
}
/**
* undocumented function
*
* @return void
* @access public
*/
function testNoDoubleNewlinesInHeaders() {
$this->Controller->EmailTest->reset();
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Attachment Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'debug';
$body = '<p>This is the body of the message</p>';
$this->Controller->EmailTest->sendAs = 'both';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = $this->Controller->Session->read('Message.email.message');
$this->assertNoPattern('/\n\nContent-Transfer-Encoding/', $msg);
$this->assertPattern('/\nContent-Transfer-Encoding/', $msg);
}
/** /**
* testReset method * testReset method
* *
@ -574,6 +636,7 @@ TEXTBLOC;
$this->Controller->EmailTest->additionalParams = 'X-additional-header'; $this->Controller->EmailTest->additionalParams = 'X-additional-header';
$this->Controller->EmailTest->delivery = 'smtp'; $this->Controller->EmailTest->delivery = 'smtp';
$this->Controller->EmailTest->smtpOptions['host'] = 'blah'; $this->Controller->EmailTest->smtpOptions['host'] = 'blah';
$this->Controller->EmailTest->attachments = array('attachment1', 'attachment2');
$this->assertFalse($this->Controller->EmailTest->send('Should not work')); $this->assertFalse($this->Controller->EmailTest->send('Should not work'));
@ -592,6 +655,7 @@ TEXTBLOC;
$this->assertNull($this->Controller->EmailTest->getBoundary()); $this->assertNull($this->Controller->EmailTest->getBoundary());
$this->assertIdentical($this->Controller->EmailTest->getMessage(), array()); $this->assertIdentical($this->Controller->EmailTest->getMessage(), array());
$this->assertNull($this->Controller->EmailTest->smtpError); $this->assertNull($this->Controller->EmailTest->smtpError);
$this->assertIdentical($this->Controller->EmailTest->attachments, array());
} }
/** /**
* osFix method * osFix method

View file

@ -35,6 +35,13 @@ Mock::generatePartial('RequestHandlerComponent', 'NoStopRequestHandler', array('
* @subpackage cake.tests.cases.libs.controller.components * @subpackage cake.tests.cases.libs.controller.components
*/ */
class RequestHandlerTestController extends Controller { class RequestHandlerTestController extends Controller {
/**
* name property
*
* @var string
* @access public
**/
var $name = 'RequestHandlerTest';
/** /**
* uses property * uses property
* *
@ -124,21 +131,32 @@ class RequestHandlerComponentTest extends CakeTestCase {
*/ */
var $RequestHandler; var $RequestHandler;
/** /**
* setUp method * startTest method
* *
* @access public * @access public
* @return void * @return void
*/ */
function setUp() { function startTest() {
$this->_init(); $this->_init();
} }
/** /**
* tearDown method * init method
*
* @access protected
* @return void
*/
function _init() {
$this->Controller = new RequestHandlerTestController(array('components' => array('RequestHandler')));
$this->Controller->constructClasses();
$this->RequestHandler =& $this->Controller->RequestHandler;
}
/**
* endTest method
* *
* @access public * @access public
* @return void * @return void
*/ */
function tearDown() { function endTest() {
unset($this->RequestHandler); unset($this->RequestHandler);
unset($this->Controller); unset($this->Controller);
if (!headers_sent()) { if (!headers_sent()) {
@ -242,6 +260,24 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->RequestHandler->renderAs($this->Controller, 'xml'); $this->RequestHandler->renderAs($this->Controller, 'xml');
$this->assertTrue(in_array('Xml', $this->Controller->helpers)); $this->assertTrue(in_array('Xml', $this->Controller->helpers));
} }
/**
* test that calling renderAs() more than once continues to work.
*
* @link #6466
* @return void
**/
function testRenderAsCalledTwice() {
$this->RequestHandler->renderAs($this->Controller, 'xml');
$this->assertEqual($this->Controller->viewPath, 'request_handler_test/xml');
$this->assertEqual($this->Controller->layoutPath, 'xml');
$this->assertTrue(in_array('Xml', $this->Controller->helpers));
$this->RequestHandler->renderAs($this->Controller, 'js');
$this->assertEqual($this->Controller->viewPath, 'request_handler_test/js');
$this->assertEqual($this->Controller->layoutPath, 'js');
$this->assertTrue(in_array('Js', $this->Controller->helpers));
}
/** /**
* testRequestClientTypes method * testRequestClientTypes method
* *
@ -500,16 +536,5 @@ class RequestHandlerComponentTest extends CakeTestCase {
unset($_SERVER['HTTP_X_REQUESTED_WITH']); unset($_SERVER['HTTP_X_REQUESTED_WITH']);
} }
/**
* init method
*
* @access protected
* @return void
*/
function _init() {
$this->Controller = new RequestHandlerTestController(array('components' => array('RequestHandler')));
$this->Controller->constructClasses();
$this->RequestHandler =& $this->Controller->RequestHandler;
}
} }
?> ?>

View file

@ -235,6 +235,11 @@ class ScaffoldViewTest extends CakeTestCase {
*/ */
function setUp() { function setUp() {
$this->Controller =& new ScaffoldMockController(); $this->Controller =& new ScaffoldMockController();
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
} }
/** /**
* tearDown method * tearDown method
@ -244,6 +249,8 @@ class ScaffoldViewTest extends CakeTestCase {
*/ */
function tearDown() { function tearDown() {
unset($this->Controller); unset($this->Controller);
App::build();
} }
/** /**
* testGetViewFilename method * testGetViewFilename method
@ -293,13 +300,6 @@ class ScaffoldViewTest extends CakeTestCase {
$expected = 'cake' . DS . 'libs' . DS . 'view' . DS . 'errors' . DS . 'scaffold_error.ctp'; $expected = 'cake' . DS . 'libs' . DS . 'view' . DS . 'errors' . DS . 'scaffold_error.ctp';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$_back = array(
'viewPaths' => Configure::read('viewPaths'),
'pluginPaths' => Configure::read('pluginPaths'),
);
Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS));
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
$Controller =& new ScaffoldMockController(); $Controller =& new ScaffoldMockController();
$Controller->scaffold = 'admin'; $Controller->scaffold = 'admin';
$Controller->viewPath = 'posts'; $Controller->viewPath = 'posts';
@ -329,8 +329,6 @@ class ScaffoldViewTest extends CakeTestCase {
. DS .'test_plugin' . DS . 'views' . DS . 'tests' . DS . 'scaffold.edit.ctp'; . DS .'test_plugin' . DS . 'views' . DS . 'tests' . DS . 'scaffold.edit.ctp';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
Configure::write('viewPaths', $_back['viewPaths']);
Configure::write('pluginPaths', $_back['pluginPaths']);
Configure::write('Routing.admin', $_admin); Configure::write('Routing.admin', $_admin);
} }
/** /**

View file

@ -39,9 +39,9 @@ class I18nTest extends CakeTestCase {
* @return void * @return void
*/ */
function setUp() { function setUp() {
$this->_localePaths = App::path('locales');
App::build(array( App::build(array(
'locales' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'locale') 'locales' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'locale'),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins')
)); ));
} }
/** /**
@ -2390,8 +2390,6 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('23 = 0 or > 1 (from plugin)', $plurals)); $this->assertTrue(in_array('23 = 0 or > 1 (from plugin)', $plurals));
$this->assertTrue(in_array('24 = 0 or > 1 (from plugin)', $plurals)); $this->assertTrue(in_array('24 = 0 or > 1 (from plugin)', $plurals));
$this->assertTrue(in_array('25 = 0 or > 1 (from plugin)', $plurals)); $this->assertTrue(in_array('25 = 0 or > 1 (from plugin)', $plurals));
App::build();
} }
/** /**
* testPoMultipleLineTranslation method * testPoMultipleLineTranslation method
@ -2487,6 +2485,12 @@ class I18nTest extends CakeTestCase {
$expected = 'this is a "quoted string" (translated)'; $expected = 'this is a "quoted string" (translated)';
$this->assertEqual(__('this is a "quoted string"', true), $expected); $this->assertEqual(__('this is a "quoted string"', true), $expected);
} }
/**
* testFloatValue method
*
* @access public
* @return void
*/
function testFloatValue() { function testFloatValue() {
Configure::write('Config.language', 'rule_9_po'); Configure::write('Config.language', 'rule_9_po');
@ -2502,6 +2506,70 @@ class I18nTest extends CakeTestCase {
$expected = "%d everything else (translated)"; $expected = "%d everything else (translated)";
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
} }
/**
* testCategory method
*
* @access public
* @return void
*/
function testCategory() {
Configure::write('Config.language', 'po');
$category = $this->__category();
$this->assertEqual('Monetary Po (translated)', $category);
}
/**
* testPluginCategory method
*
* @access public
* @return void
*/
function testPluginCategory() {
Configure::write('Config.language', 'po');
$singular = $this->__domainCategorySingular();
$this->assertEqual('Monetary Plural Rule 1 (from plugin)', $singular);
$plurals = $this->__domainCategoryPlural();
$this->assertTrue(in_array('Monetary 0 = 0 or > 1 (from plugin)', $plurals));
$this->assertTrue(in_array('Monetary 1 = 1 (from plugin)', $plurals));
}
/**
* testCategoryThenSingular method
*
* @access public
* @return void
*/
function testCategoryThenSingular() {
Configure::write('Config.language', 'po');
$category = $this->__category();
$this->assertEqual('Monetary Po (translated)', $category);
$singular = $this->__singular();
$this->assertEqual('Po (translated)', $singular);
}
/**
* Singular method
*
* @access private
* @return void
*/
function __domainCategorySingular($domain = 'test_plugin', $category = LC_MONETARY) {
$singular = __dc($domain, 'Plural Rule 1', $category, true);
return $singular;
}
/**
* Plural method
*
* @access private
* @return void
*/
function __domainCategoryPlural($domain = 'test_plugin', $category = LC_MONETARY) {
$plurals = array();
for ($number = 0; $number <= 25; $number++) {
$plurals[] = sprintf(__dcn($domain, '%d = 1', '%d = 0 or > 1', (float)$number, $category, true), (float)$number);
}
return $plurals;
}
/** /**
* Singular method * Singular method
* *
@ -2525,6 +2593,16 @@ class I18nTest extends CakeTestCase {
} }
return $plurals; return $plurals;
} }
/**
* category method
*
* @access private
* @return void
*/
function __category($category = LC_MONETARY) {
$singular = __c('Plural Rule 1', $category, true);
return $singular;
}
/** /**
* Singular method * Singular method
* *

View file

@ -2133,7 +2133,7 @@ class DboSourceTest extends CakeTestCase {
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->testDb->conditions(array('score' => array(2=>1, 2, 10))); $result = $this->testDb->conditions(array('score' => array(2=>1, 2, 10)));
$expected = " WHERE `score` IN (1, 2, 10)"; $expected = " WHERE score IN (1, 2, 10)";
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->testDb->conditions("Aro.rght = Aro.lft + 1.1"); $result = $this->testDb->conditions("Aro.rght = Aro.lft + 1.1");
@ -2385,7 +2385,7 @@ class DboSourceTest extends CakeTestCase {
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->testDb->conditions(array('score' => array(1, 2, 10))); $result = $this->testDb->conditions(array('score' => array(1, 2, 10)));
$expected = " WHERE `score` IN (1, 2, 10)"; $expected = " WHERE score IN (1, 2, 10)";
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->testDb->conditions(array('score' => array())); $result = $this->testDb->conditions(array('score' => array()));
@ -2476,7 +2476,7 @@ class DboSourceTest extends CakeTestCase {
'NOT' => array('Course.id' => null, 'Course.vet' => 'N', 'level_of_education_id' => array(912,999)), 'NOT' => array('Course.id' => null, 'Course.vet' => 'N', 'level_of_education_id' => array(912,999)),
'Enrollment.yearcompleted >' => '0') 'Enrollment.yearcompleted >' => '0')
); );
$this->assertPattern('/^\s*WHERE\s+\(NOT\s+\(`Course`\.`id` IS NULL\)\s+AND NOT\s+\(`Course`\.`vet`\s+=\s+\'N\'\)\s+AND NOT\s+\(`level_of_education_id` IN \(912, 999\)\)\)\s+AND\s+`Enrollment`\.`yearcompleted`\s+>\s+\'0\'\s*$/', $result); $this->assertPattern('/^\s*WHERE\s+\(NOT\s+\(`Course`\.`id` IS NULL\)\s+AND NOT\s+\(`Course`\.`vet`\s+=\s+\'N\'\)\s+AND NOT\s+\(level_of_education_id IN \(912, 999\)\)\)\s+AND\s+`Enrollment`\.`yearcompleted`\s+>\s+\'0\'\s*$/', $result);
$result = $this->testDb->conditions(array('id <>' => '8')); $result = $this->testDb->conditions(array('id <>' => '8'));
$this->assertPattern('/^\s*WHERE\s+`id`\s+<>\s+\'8\'\s*$/', $result); $this->assertPattern('/^\s*WHERE\s+`id`\s+<>\s+\'8\'\s*$/', $result);
@ -2495,16 +2495,24 @@ class DboSourceTest extends CakeTestCase {
"Listing.description LIKE" => "%term_2%" "Listing.description LIKE" => "%term_2%"
); );
$result = $this->testDb->conditions($conditions); $result = $this->testDb->conditions($conditions);
$expected = " WHERE NOT (`Listing`.`expiration` BETWEEN '1' AND '100') AND ((`Listing`.`title` LIKE '%term%') OR (`Listing`.`description` LIKE '%term%')) AND ((`Listing`.`title` LIKE '%term_2%') OR (`Listing`.`description` LIKE '%term_2%'))"; $expected = " WHERE NOT (`Listing`.`expiration` BETWEEN '1' AND '100') AND" .
" ((`Listing`.`title` LIKE '%term%') OR (`Listing`.`description` LIKE '%term%')) AND" .
" ((`Listing`.`title` LIKE '%term_2%') OR (`Listing`.`description` LIKE '%term_2%'))";
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->testDb->conditions(array('MD5(CONCAT(Reg.email,Reg.id))' => 'blah')); $result = $this->testDb->conditions(array('MD5(CONCAT(Reg.email,Reg.id))' => 'blah'));
$expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) = 'blah'"; $expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) = 'blah'";
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->testDb->conditions(array(
'MD5(CONCAT(Reg.email,Reg.id))' => array('blah', 'blahblah')
));
$expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) IN ('blah', 'blahblah')";
$this->assertEqual($result, $expected);
$conditions = array('id' => array(2, 5, 6, 9, 12, 45, 78, 43, 76)); $conditions = array('id' => array(2, 5, 6, 9, 12, 45, 78, 43, 76));
$result = $this->testDb->conditions($conditions); $result = $this->testDb->conditions($conditions);
$expected = " WHERE `id` IN (2, 5, 6, 9, 12, 45, 78, 43, 76)"; $expected = " WHERE id IN (2, 5, 6, 9, 12, 45, 78, 43, 76)";
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$conditions = array('title' => 'user(s)'); $conditions = array('title' => 'user(s)');

File diff suppressed because it is too large Load diff

View file

@ -333,6 +333,58 @@ class Test2Behavior extends TestBehavior{
*/ */
class Test3Behavior extends TestBehavior{ class Test3Behavior extends TestBehavior{
} }
/**
* Test4Behavior class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class Test4Behavior extends ModelBehavior{
function setup(&$model, $config = null) {
$model->bindModel(
array('hasMany' => array('Comment'))
);
}
}
/**
* Test5Behavior class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class Test5Behavior extends ModelBehavior{
function setup(&$model, $config = null) {
$model->bindModel(
array('belongsTo' => array('User'))
);
}
}
/**
* Test6Behavior class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class Test6Behavior extends ModelBehavior{
function setup(&$model, $config = null) {
$model->bindModel(
array('hasAndBelongsToMany' => array('Tag'))
);
}
}
/**
* Test7Behavior class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class Test7Behavior extends ModelBehavior{
function setup(&$model, $config = null) {
$model->bindModel(
array('hasOne' => array('Attachment'))
);
}
}
/** /**
* BehaviorTest class * BehaviorTest class
* *
@ -346,7 +398,10 @@ class BehaviorTest extends CakeTestCase {
* @var array * @var array
* @access public * @access public
*/ */
var $fixtures = array('core.apple', 'core.sample'); var $fixtures = array(
'core.apple', 'core.sample', 'core.article', 'core.user', 'core.comment',
'core.attachment', 'core.tag', 'core.articles_tag'
);
/** /**
* tearDown method * tearDown method
* *
@ -944,6 +999,53 @@ class BehaviorTest extends CakeTestCase {
$expected = array('TestBehavior', 'Test2Behavior'); $expected = array('TestBehavior', 'Test2Behavior');
$this->assertIdentical($Apple->beforeTestResult, $expected); $this->assertIdentical($Apple->beforeTestResult, $expected);
} }
/**
* undocumented function
*
* @return void
* @access public
*/
function testBindModelCallsInBehaviors() {
$this->loadFixtures('Article', 'Comment');
// hasMany
$Article = new Article();
$Article->unbindModel(array('hasMany' => array('Comment')));
$result = $Article->find('first');
$this->assertFalse(array_key_exists('Comment', $result));
$Article->Behaviors->attach('Test4');
$result = $Article->find('first');
$this->assertTrue(array_key_exists('Comment', $result));
// belongsTo
$Article->unbindModel(array('belongsTo' => array('User')));
$result = $Article->find('first');
$this->assertFalse(array_key_exists('User', $result));
$Article->Behaviors->attach('Test5');
$result = $Article->find('first');
$this->assertTrue(array_key_exists('User', $result));
// hasAndBelongsToMany
$Article->unbindModel(array('hasAndBelongsToMany' => array('Tag')));
$result = $Article->find('first');
$this->assertFalse(array_key_exists('Tag', $result));
$Article->Behaviors->attach('Test6');
$result = $Article->find('first');
$this->assertTrue(array_key_exists('Comment', $result));
// hasOne
$Comment = new Comment();
$Comment->unbindModel(array('hasOne' => array('Attachment')));
$result = $Comment->find('first');
$this->assertFalse(array_key_exists('Attachment', $result));
$Comment->Behaviors->attach('Test7');
$result = $Comment->find('first');
$this->assertTrue(array_key_exists('Attachment', $result));
}
/** /**
* Test attach and detaching * Test attach and detaching
* *

View file

@ -0,0 +1,571 @@
<?php
/* SVN FILE: $Id: model.test.php 8225 2009-07-08 03:25:30Z mark_story $ */
/**
* ModelDeleteTest file
*
* Long description for file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.cases.libs.model
* @since CakePHP(tm) v 1.2.0.4206
* @version $Revision: 8225 $
* @modifiedby $LastChangedBy: mark_story $
* @lastmodified $Date: 2009-07-07 23:25:30 -0400 (Tue, 07 Jul 2009) $
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
require_once dirname(__FILE__) . DS . 'model.test.php';
require_once dirname(__FILE__) . DS . 'model_delete.test.php';
/**
* ModelDeleteTest
*
* @package cake
* @subpackage cake.tests.cases.libs.model.operations
*/
class ModelDeleteTest extends BaseModelTest {
/**
* testDeleteHabtmReferenceWithConditions method
*
* @access public
* @return void
*/
function testDeleteHabtmReferenceWithConditions() {
$this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio');
$Portfolio =& new Portfolio();
$Portfolio->hasAndBelongsToMany['Item']['conditions'] = array('ItemsPortfolio.item_id >' => 1);
$result = $Portfolio->find('first', array(
'conditions' => array('Portfolio.id' => 1)
));
$expected = array(
array(
'id' => 3,
'syfile_id' => 3,
'published' => 0,
'name' => 'Item 3',
'ItemsPortfolio' => array(
'id' => 3,
'item_id' => 3,
'portfolio_id' => 1
)),
array(
'id' => 4,
'syfile_id' => 4,
'published' => 0,
'name' => 'Item 4',
'ItemsPortfolio' => array(
'id' => 4,
'item_id' => 4,
'portfolio_id' => 1
)),
array(
'id' => 5,
'syfile_id' => 5,
'published' => 0,
'name' => 'Item 5',
'ItemsPortfolio' => array(
'id' => 5,
'item_id' => 5,
'portfolio_id' => 1
)));
$this->assertEqual($result['Item'], $expected);
$result = $Portfolio->ItemsPortfolio->find('all', array(
'conditions' => array('ItemsPortfolio.portfolio_id' => 1)
));
$expected = array(
array(
'ItemsPortfolio' => array(
'id' => 1,
'item_id' => 1,
'portfolio_id' => 1
)),
array(
'ItemsPortfolio' => array(
'id' => 3,
'item_id' => 3,
'portfolio_id' => 1
)),
array(
'ItemsPortfolio' => array(
'id' => 4,
'item_id' => 4,
'portfolio_id' => 1
)),
array(
'ItemsPortfolio' => array(
'id' => 5,
'item_id' => 5,
'portfolio_id' => 1
)));
$this->assertEqual($result, $expected);
$Portfolio->delete(1);
$result = $Portfolio->find('first', array(
'conditions' => array('Portfolio.id' => 1)
));
$this->assertFalse($result);
$result = $Portfolio->ItemsPortfolio->find('all', array(
'conditions' => array('ItemsPortfolio.portfolio_id' => 1)
));
$this->assertFalse($result);
}
/**
* testDeleteArticleBLinks method
*
* @access public
* @return void
*/
function testDeleteArticleBLinks() {
$this->loadFixtures('Article', 'ArticlesTag', 'Tag');
$TestModel =& new ArticleB();
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
array('ArticlesTag' => array('article_id' => '1', 'tag_id' => '1')),
array('ArticlesTag' => array('article_id' => '1', 'tag_id' => '2')),
array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '1')),
array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '3'))
);
$this->assertEqual($result, $expected);
$TestModel->delete(1);
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '1')),
array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '3'))
);
$this->assertEqual($result, $expected);
}
/**
* testDeleteDependentWithConditions method
*
* @access public
* @return void
*/
function testDeleteDependentWithConditions() {
$this->loadFixtures('Cd','Book','OverallFavorite');
$Cd =& new Cd();
$OverallFavorite =& new OverallFavorite();
$Cd->del(1);
$result = $OverallFavorite->find('all', array(
'fields' => array('model_type', 'model_id', 'priority')
));
$expected = array(
array(
'OverallFavorite' => array(
'model_type' => 'Book',
'model_id' => 1,
'priority' => 2
)));
$this->assertTrue(is_array($result));
$this->assertEqual($result, $expected);
}
/**
* testDel method
*
* @access public
* @return void
*/
function testDel() {
$this->loadFixtures('Article');
$TestModel =& new Article();
$result = $TestModel->del(2);
$this->assertTrue($result);
$result = $TestModel->read(null, 2);
$this->assertFalse($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'title')
));
$expected = array(
array('Article' => array(
'id' => 1,
'title' => 'First Article'
)),
array('Article' => array(
'id' => 3,
'title' => 'Third Article'
)));
$this->assertEqual($result, $expected);
$result = $TestModel->del(3);
$this->assertTrue($result);
$result = $TestModel->read(null, 3);
$this->assertFalse($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'title')
));
$expected = array(
array('Article' => array(
'id' => 1,
'title' => 'First Article'
)));
$this->assertEqual($result, $expected);
// make sure deleting a non-existent record doesn't break save()
// ticket #6293
$this->loadFixtures('Uuid');
$Uuid =& new Uuid();
$data = array(
'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3',
'52C8865C-10EE-4302-AE6C-6E7D8E12E2C8',
'8208C7FE-E89C-47C5-B378-DED6C271F9B8');
foreach ($data as $id) {
$Uuid->save(array('id' => $id));
}
$Uuid->del('52C8865C-10EE-4302-AE6C-6E7D8E12E2C8');
$Uuid->del('52C8865C-10EE-4302-AE6C-6E7D8E12E2C8');
foreach ($data as $id) {
$Uuid->save(array('id' => $id));
}
$result = $Uuid->find('all', array(
'conditions' => array('id' => $data),
'fields' => array('id'),
'order' => 'id'));
$expected = array(
array('Uuid' => array(
'id' => '52C8865C-10EE-4302-AE6C-6E7D8E12E2C8')),
array('Uuid' => array(
'id' => '8208C7FE-E89C-47C5-B378-DED6C271F9B8')),
array('Uuid' => array(
'id' => 'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3')));
$this->assertEqual($result, $expected);
}
/**
* testDeleteAll method
*
* @access public
* @return void
*/
function testDeleteAll() {
$this->loadFixtures('Article');
$TestModel =& new Article();
$data = array('Article' => array(
'user_id' => 2,
'id' => 4,
'title' => 'Fourth Article',
'published' => 'N'
));
$result = $TestModel->set($data) && $TestModel->save();
$this->assertTrue($result);
$data = array('Article' => array(
'user_id' => 2,
'id' => 5,
'title' => 'Fifth Article',
'published' => 'Y'
));
$result = $TestModel->set($data) && $TestModel->save();
$this->assertTrue($result);
$data = array('Article' => array(
'user_id' => 1,
'id' => 6,
'title' => 'Sixth Article',
'published' => 'N'
));
$result = $TestModel->set($data) && $TestModel->save();
$this->assertTrue($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'user_id', 'title', 'published')
));
$expected = array(
array('Article' => array(
'id' => 1,
'user_id' => 1,
'title' => 'First Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 2,
'user_id' => 3,
'title' => 'Second Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 3,
'user_id' => 1,
'title' => 'Third Article',
'published' => 'Y')),
array('Article' => array(
'id' => 4,
'user_id' => 2,
'title' => 'Fourth Article',
'published' => 'N'
)),
array('Article' => array(
'id' => 5,
'user_id' => 2,
'title' => 'Fifth Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 6,
'user_id' => 1,
'title' => 'Sixth Article',
'published' => 'N'
)));
$this->assertEqual($result, $expected);
$result = $TestModel->deleteAll(array('Article.published' => 'N'));
$this->assertTrue($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'user_id', 'title', 'published')
));
$expected = array(
array('Article' => array(
'id' => 1,
'user_id' => 1,
'title' => 'First Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 2,
'user_id' => 3,
'title' => 'Second Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 3,
'user_id' => 1,
'title' => 'Third Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 5,
'user_id' => 2,
'title' => 'Fifth Article',
'published' => 'Y'
)));
$this->assertEqual($result, $expected);
$data = array('Article.user_id' => array(2, 3));
$result = $TestModel->deleteAll($data, true, true);
$this->assertTrue($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'user_id', 'title', 'published')
));
$expected = array(
array('Article' => array(
'id' => 1,
'user_id' => 1,
'title' => 'First Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 3,
'user_id' => 1,
'title' => 'Third Article',
'published' => 'Y'
)));
$this->assertEqual($result, $expected);
$result = $TestModel->deleteAll(array('Article.user_id' => 999));
$this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s');
}
/**
* testRecursiveDel method
*
* @access public
* @return void
*/
function testRecursiveDel() {
$this->loadFixtures('Article', 'Comment', 'Attachment');
$TestModel =& new Article();
$result = $TestModel->del(2);
$this->assertTrue($result);
$TestModel->recursive = 2;
$result = $TestModel->read(null, 2);
$this->assertFalse($result);
$result = $TestModel->Comment->read(null, 5);
$this->assertFalse($result);
$result = $TestModel->Comment->read(null, 6);
$this->assertFalse($result);
$result = $TestModel->Comment->Attachment->read(null, 1);
$this->assertFalse($result);
$result = $TestModel->find('count');
$this->assertEqual($result, 2);
$result = $TestModel->Comment->find('count');
$this->assertEqual($result, 4);
$result = $TestModel->Comment->Attachment->find('count');
$this->assertEqual($result, 0);
}
/**
* testDependentExclusiveDelete method
*
* @access public
* @return void
*/
function testDependentExclusiveDelete() {
$this->loadFixtures('Article', 'Comment');
$TestModel =& new Article10();
$result = $TestModel->find('all');
$this->assertEqual(count($result[0]['Comment']), 4);
$this->assertEqual(count($result[1]['Comment']), 2);
$this->assertEqual($TestModel->Comment->find('count'), 6);
$TestModel->delete(1);
$this->assertEqual($TestModel->Comment->find('count'), 2);
}
/**
* testDeleteLinks method
*
* @access public
* @return void
*/
function testDeleteLinks() {
$this->loadFixtures('Article', 'ArticlesTag', 'Tag');
$TestModel =& new Article();
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
array('ArticlesTag' => array(
'article_id' => '1',
'tag_id' => '1'
)),
array('ArticlesTag' => array(
'article_id' => '1',
'tag_id' => '2'
)),
array('ArticlesTag' => array(
'article_id' => '2',
'tag_id' => '1'
)),
array('ArticlesTag' => array(
'article_id' => '2',
'tag_id' => '3'
)));
$this->assertEqual($result, $expected);
$TestModel->delete(1);
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
array('ArticlesTag' => array(
'article_id' => '2',
'tag_id' => '1'
)),
array('ArticlesTag' => array(
'article_id' => '2',
'tag_id' => '3'
)));
$this->assertEqual($result, $expected);
$result = $TestModel->deleteAll(array('Article.user_id' => 999));
$this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s');
}
/**
* testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable method
*
* @access public
* @return void
*/
function testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable() {
$this->loadFixtures('Apple', 'Device', 'ThePaperMonkies');
$ThePaper =& new ThePaper();
$ThePaper->id = 1;
$ThePaper->save(array('Monkey' => array(2, 3)));
$result = $ThePaper->findById(1);
$expected = array(
array(
'id' => '2',
'device_type_id' => '1',
'name' => 'Device 2',
'typ' => '1'
),
array(
'id' => '3',
'device_type_id' => '1',
'name' => 'Device 3',
'typ' => '2'
));
$this->assertEqual($result['Monkey'], $expected);
$ThePaper =& new ThePaper();
$ThePaper->id = 2;
$ThePaper->save(array('Monkey' => array(2, 3)));
$result = $ThePaper->findById(2);
$expected = array(
array(
'id' => '2',
'device_type_id' => '1',
'name' => 'Device 2',
'typ' => '1'
),
array(
'id' => '3',
'device_type_id' => '1',
'name' => 'Device 3',
'typ' => '2'
));
$this->assertEqual($result['Monkey'], $expected);
$ThePaper->delete(1);
$result = $ThePaper->findById(2);
$expected = array(
array(
'id' => '2',
'device_type_id' => '1',
'name' => 'Device 2',
'typ' => '1'
),
array(
'id' => '3',
'device_type_id' => '1',
'name' => 'Device 3',
'typ' => '2'
));
$this->assertEqual($result['Monkey'], $expected);
}
}
?>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,126 @@
<?php
/* SVN FILE: $Id: model.test.php 8225 2009-07-08 03:25:30Z mark_story $ */
/**
* ModelValidationTest file
*
* Long description for file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.cases.libs.model
* @since CakePHP(tm) v 1.2.0.4206
* @version $Revision: 8225 $
* @modifiedby $LastChangedBy: mark_story $
* @lastmodified $Date: 2009-07-07 23:25:30 -0400 (Tue, 07 Jul 2009) $
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
require_once dirname(__FILE__) . DS . 'model.test.php';
require_once dirname(__FILE__) . DS . 'model_validation.test.php';
/**
* ModelValidationTest
*
* @package cake
* @subpackage cake.tests.cases.libs.model.operations
*/
class ModelValidationTest extends BaseModelTest {
/**
* Tests validation parameter order in custom validation methods
*
* @access public
* @return void
*/
function testValidationParams() {
$TestModel =& new ValidationTest1();
$TestModel->validate['title'] = array(
'rule' => 'customValidatorWithParams',
'required' => true
);
$TestModel->create(array('title' => 'foo'));
$TestModel->invalidFields();
$expected = array(
'data' => array(
'title' => 'foo'
),
'validator' => array(
'rule' => 'customValidatorWithParams',
'on' => null,
'last' => false,
'allowEmpty' => false,
'required' => true
),
'or' => true,
'ignore_on_same' => 'id'
);
$this->assertEqual($TestModel->validatorParams, $expected);
$TestModel->validate['title'] = array(
'rule' => 'customValidatorWithMessage',
'required' => true
);
$expected = array(
'title' => 'This field will *never* validate! Muhahaha!'
);
$this->assertEqual($TestModel->invalidFields(), $expected);
}
/**
* Tests validation parameter fieldList in invalidFields
*
* @access public
* @return void
*/
function testInvalidFieldsWithFieldListParams() {
$TestModel =& new ValidationTest1();
$TestModel->validate = $validate = array(
'title' => array(
'rule' => 'customValidator',
'required' => true
),
'name' => array(
'rule' => 'allowEmpty',
'required' => true
));
$TestModel->invalidFields(array('fieldList' => array('title')));
$expected = array(
'title' => 'This field cannot be left blank'
);
$this->assertEqual($TestModel->validationErrors, $expected);
$TestModel->validationErrors = array();
$TestModel->invalidFields(array('fieldList' => array('name')));
$expected = array(
'name' => 'This field cannot be left blank'
);
$this->assertEqual($TestModel->validationErrors, $expected);
$TestModel->validationErrors = array();
$TestModel->invalidFields(array('fieldList' => array('name', 'title')));
$expected = array(
'name' => 'This field cannot be left blank',
'title' => 'This field cannot be left blank'
);
$this->assertEqual($TestModel->validationErrors, $expected);
$TestModel->validationErrors = array();
$TestModel->whitelist = array('name');
$TestModel->invalidFields();
$expected = array('name' => 'This field cannot be left blank');
$this->assertEqual($TestModel->validationErrors, $expected);
$TestModel->validationErrors = array();
$this->assertEqual($TestModel->validate, $validate);
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -299,7 +299,7 @@ class RouterTest extends CakeTestCase {
$result = Router::normalize('/recipe/recipes/add'); $result = Router::normalize('/recipe/recipes/add');
$this->assertEqual($result, '/recipe/recipes/add'); $this->assertEqual($result, '/recipe/recipes/add');
Router::setRequestInfo(array(array(), array('base' => 'us'))); Router::setRequestInfo(array(array(), array('base' => '/us')));
$result = Router::normalize('/us/users/logout/'); $result = Router::normalize('/us/users/logout/');
$this->assertEqual($result, '/users/logout'); $this->assertEqual($result, '/users/logout');
@ -309,6 +309,22 @@ class RouterTest extends CakeTestCase {
$result = Router::normalize('/cake_12/users/logout/'); $result = Router::normalize('/cake_12/users/logout/');
$this->assertEqual($result, '/users/logout'); $this->assertEqual($result, '/users/logout');
Router::reload();
$_back = Configure::read('App.baseUrl');
Configure::write('App.baseUrl', '/');
Router::setRequestInfo(array(array(), array('base' => '/')));
$result = Router::normalize('users/login');
$this->assertEqual($result, '/users/login');
Configure::write('App.baseUrl', $_back);
Router::reload();
Router::setRequestInfo(array(array(), array('base' => 'beer')));
$result = Router::normalize('beer/admin/beers_tags/add');
$this->assertEqual($result, '/admin/beers_tags/add');
$result = Router::normalize('/admin/beers_tags/add');
$this->assertEqual($result, '/admin/beers_tags/add');
} }
/** /**
* testUrlGeneration method * testUrlGeneration method
@ -1036,6 +1052,28 @@ class RouterTest extends CakeTestCase {
$result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => 'var=test&var2=test2')); $result = Router::url(array('controller' => 'posts', 'action' => 'index', '0', '?' => 'var=test&var2=test2'));
$expected = '/beheer/posts/index/0?var=test&var2=test2'; $expected = '/beheer/posts/index/0?var=test&var2=test2';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
Configure::write('Routing.admin', 'admin');
$paths = Configure::read('pluginPaths');
Configure::write('pluginPaths', array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS
));
Configure::write('__objects.plugin', array('test_plugin'));
Router::reload();
Router::setRequestInfo(array(
array('admin' => true, 'controller' => 'controller', 'action' => 'action',
'form' => array(), 'url' => array(), 'plugin' => null),
array('base' => '/', 'here' => '/', 'webroot' => '/base/', 'passedArgs' => array(),
'argSeparator' => ':', 'namedArgs' => array())
));
Router::parse('/');
$result = Router::url(array('plugin' => 'test_plugin', 'controller' => 'test_plugin', 'action' => 'index'));
$expected = '/admin/test_plugin';
$this->assertEqual($result, $expected);
Configure::write('pluginPaths', $paths);
} }
/** /**
* testExtensionParsingSetting method * testExtensionParsingSetting method
@ -1617,5 +1655,20 @@ class RouterTest extends CakeTestCase {
$expected = '/test/test_another_action/locale:badness'; $expected = '/test/test_another_action/locale:badness';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
} }
/**
* testStripPlugin
*
* @return void
* @access public
*/
function testStripPlugin() {
$pluginName = 'forums';
$url = 'example.com/' . $pluginName . '/';
$expected = 'example.com';
$this->assertEqual(Router::stripPlugin($url, $pluginName), $expected);
$this->assertEqual(Router::stripPlugin($url), $url);
$this->assertEqual(Router::stripPlugin($url, null), $url);
}
} }
?> ?>

View file

@ -73,10 +73,31 @@ class HtmlHelperTest extends CakeTestCase {
/** /**
* html property * html property
* *
* @var mixed null * @var object
* @access public * @access public
*/ */
var $html = null; var $Html = null;
/**
* Backup of app encoding configuration setting
*
* @var string
* @access protected
*/
var $_appEncoding;
/**
* Backup of asset configuration settings
*
* @var string
* @access protected
*/
var $_asset;
/**
* Backup of debug configuration setting
*
* @var integer
* @access protected
*/
var $_debug;
/** /**
* setUp method * setUp method
* *
@ -88,6 +109,8 @@ class HtmlHelperTest extends CakeTestCase {
$view =& new View(new TheHtmlTestController()); $view =& new View(new TheHtmlTestController());
ClassRegistry::addObject('view', $view); ClassRegistry::addObject('view', $view);
$this->_appEncoding = Configure::read('App.encoding'); $this->_appEncoding = Configure::read('App.encoding');
$this->_asset = Configure::read('Asset');
$this->_debug = Configure::read('debug');
} }
/** /**
* tearDown method * tearDown method
@ -97,6 +120,8 @@ class HtmlHelperTest extends CakeTestCase {
*/ */
function tearDown() { function tearDown() {
Configure::write('App.encoding', $this->_appEncoding); Configure::write('App.encoding', $this->_appEncoding);
Configure::write('Asset', $this->_asset);
Configure::write('debug', $this->_debug);
ClassRegistry::flush(); ClassRegistry::flush();
} }
/** /**
@ -269,14 +294,34 @@ class HtmlHelperTest extends CakeTestCase {
$result = $this->Html->image('cake.icon.gif'); $result = $this->Html->image('cake.icon.gif');
$this->assertTags($result, array('img' => array('src' => 'preg:/img\/cake\.icon\.gif\?\d+/', 'alt' => ''))); $this->assertTags($result, array('img' => array('src' => 'preg:/img\/cake\.icon\.gif\?\d+/', 'alt' => '')));
$back = Configure::read('debug');
Configure::write('debug', 0); Configure::write('debug', 0);
Configure::write('Asset.timestamp', 'force'); Configure::write('Asset.timestamp', 'force');
$result = $this->Html->image('cake.icon.gif'); $result = $this->Html->image('cake.icon.gif');
$this->assertTags($result, array('img' => array('src' => 'preg:/img\/cake\.icon\.gif\?\d+/', 'alt' => ''))); $this->assertTags($result, array('img' => array('src' => 'preg:/img\/cake\.icon\.gif\?\d+/', 'alt' => '')));
}
/**
* Tests creation of an image tag using a theme and asset timestamping
*
* @access public
* @return void
* @link https://trac.cakephp.org/ticket/6490
*/
function testImageTagWithTheme() {
$file = WWW_ROOT . 'themed' . DS . 'default' . DS . 'img' . DS . 'cake.power.gif';
$message = "File '{$file}' not present. %s";
$this->skipUnless(file_exists($file), $message);
Configure::write('debug', $back); Configure::write('Asset.timestamp', true);
Configure::write('debug', 1);
$this->Html->themeWeb = 'themed/default/';
$result = $this->Html->image('cake.power.gif');
$this->assertTags($result, array(
'img' => array(
'src' => 'preg:/themed\/default\/img\/cake\.power\.gif\?\d+/',
'alt' => ''
)));
} }
/** /**
* testStyle method * testStyle method
@ -346,7 +391,6 @@ class HtmlHelperTest extends CakeTestCase {
$expected['link']['href'] = 'preg:/.*css\/cake\.generic\.css\?[0-9]+/'; $expected['link']['href'] = 'preg:/.*css\/cake\.generic\.css\?[0-9]+/';
$this->assertTags($result, $expected); $this->assertTags($result, $expected);
$debug = Configure::read('debug');
Configure::write('debug', 0); Configure::write('debug', 0);
$result = $this->Html->css('cake.generic'); $result = $this->Html->css('cake.generic');
@ -372,8 +416,6 @@ class HtmlHelperTest extends CakeTestCase {
$expected['link']['href'] = 'preg:/\/testing\/longer\/css\/cake\.generic\.css\?/'; $expected['link']['href'] = 'preg:/\/testing\/longer\/css\/cake\.generic\.css\?/';
$this->assertTags($result, $expected); $this->assertTags($result, $expected);
$this->Html->webroot = $webroot; $this->Html->webroot = $webroot;
Configure::write('debug', $debug);
} }
/** /**
* test timestamp enforcement for script tags. * test timestamp enforcement for script tags.
@ -1043,4 +1085,4 @@ class HtmlHelperTest extends CakeTestCase {
unset($this->Html); unset($this->Html);
} }
} }
?> ?>

View file

@ -95,13 +95,25 @@ class TestJavascriptObject {
* @since CakePHP Test Suite v 1.0.0.0 * @since CakePHP Test Suite v 1.0.0.0
*/ */
class JavascriptTest extends CakeTestCase { class JavascriptTest 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
* *
* @access public * @access public
* @return void * @return void
*/ */
function setUp() { function startTest() {
$this->Javascript =& new JavascriptHelper(); $this->Javascript =& new JavascriptHelper();
$this->Javascript->Html =& new HtmlHelper(); $this->Javascript->Html =& new HtmlHelper();
$this->Javascript->Form =& new FormHelper(); $this->Javascript->Form =& new FormHelper();
@ -114,7 +126,7 @@ class JavascriptTest extends CakeTestCase {
* @access public * @access public
* @return void * @return void
*/ */
function tearDown() { function endTest() {
unset($this->Javascript->Html); unset($this->Javascript->Html);
unset($this->Javascript->Form); unset($this->Javascript->Form);
unset($this->Javascript); unset($this->Javascript);
@ -356,11 +368,14 @@ class JavascriptTest extends CakeTestCase {
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8)); $object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8));
$result = $this->Javascript->object($object, array('block' => true)); $result = $this->Javascript->object($object, array('block' => true));
$expected = '{"title":"New thing","indexes":[5,6,7,8]}'; $expected = array(
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*' . str_replace('/', '\\/', preg_quote($expected)) . '\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+<\/script>$/s', $result); $this->cDataStart,
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); '{"title":"New thing","indexes":[5,6,7,8]}',
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); $this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8), 'object' => array('inner' => array('value' => 1))); $object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8), 'object' => array('inner' => array('value' => 1)));
$result = $this->Javascript->object($object); $result = $this->Javascript->object($object);
@ -402,7 +417,6 @@ class JavascriptTest extends CakeTestCase {
$this->Javascript->useNative = $oldNative; $this->Javascript->useNative = $oldNative;
} }
/** /**
* testScriptBlock method * testScriptBlock method
* *
@ -410,68 +424,101 @@ class JavascriptTest extends CakeTestCase {
* @return void * @return void
*/ */
function testScriptBlock() { function testScriptBlock() {
ob_flush(); $result = $this->Javascript->codeBlock('something');
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'something',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', array('allowCache' => true, 'safe' => false)); $result = $this->Javascript->codeBlock('something', array('allowCache' => true, 'safe' => false));
$this->assertPattern('/^<script[^<>]+>something<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">something<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); 'something',
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); '/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', array('allowCache' => false, 'safe' => false)); $result = $this->Javascript->codeBlock('something', array('allowCache' => false, 'safe' => false));
$this->assertPattern('/^<script[^<>]+>something<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">something<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); 'something',
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); '/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', true); $result = $this->Javascript->codeBlock('something', true);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*something\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*something\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); 'something',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', false); $result = $this->Javascript->codeBlock('something', false);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*something\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*something\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); 'something',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', array('safe' => false)); $result = $this->Javascript->codeBlock('something', array('safe' => false));
$this->assertPattern('/^<script[^<>]+>something<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">something<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); 'something',
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); '/script'
);
$result = $this->Javascript->blockEnd(); $this->assertTags($result, $expected);
$this->assertPattern('/^<\/script>$/', $result);
$result = $this->Javascript->codeBlock('something', array('safe' => true)); $result = $this->Javascript->codeBlock('something', array('safe' => true));
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*something\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*something\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); 'something',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock(null, array('safe' => true, 'allowCache' => false)); $result = $this->Javascript->codeBlock(null, array('safe' => true, 'allowCache' => false));
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*$/', $result); $this->assertNull($result);
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); echo 'this is some javascript';
$result = $this->Javascript->blockEnd(); $result = $this->Javascript->blockEnd();
$this->assertPattern('/^\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
'script' => array('type' => 'text/javascript'),
$result = $this->Javascript->codeBlock('something'); $this->cDataStart,
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*something\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); 'this is some javascript',
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+<\/script>$/s', $result); $this->cDataEnd,
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); '/script'
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); );
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock(); $result = $this->Javascript->codeBlock();
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*$/', $result); $this->assertNull($result);
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); echo "alert('hey');";
$result = $this->Javascript->blockEnd(); $result = $this->Javascript->blockEnd();
$this->assertPattern('/^\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"alert('hey');",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$this->Javascript->cacheEvents(false, true); $this->Javascript->cacheEvents(false, true);
$this->assertFalse($this->Javascript->inBlock); $this->assertFalse($this->Javascript->inBlock);
$result = $this->Javascript->codeBlock(); $result = $this->Javascript->codeBlock();
$this->assertIdentical($result, null); $this->assertIdentical($result, null);
$this->assertTrue($this->Javascript->inBlock); $this->assertTrue($this->Javascript->inBlock);
@ -491,11 +538,16 @@ class JavascriptTest extends CakeTestCase {
* @return void * @return void
*/ */
function testOutOfLineScriptWriting() { function testOutOfLineScriptWriting() {
echo $this->Javascript->codeBlock('$(document).ready(function() { /* ... */ });', array('inline' => false)); echo $this->Javascript->codeBlock('$(document).ready(function() { });', array('inline' => false));
$this->Javascript->codeBlock(null, array('inline' => false)); $this->Javascript->codeBlock(null, array('inline' => false));
echo '$(function(){ /* ... */ });'; echo '$(function(){ });';
$this->Javascript->blockEnd(); $this->Javascript->blockEnd();
$script = $this->View->scripts();
$this->assertEqual(count($script), 2);
$this->assertPattern('/' . preg_quote('$(document).ready(function() { });', '/') . '/', $script[0]);
$this->assertPattern('/' . preg_quote('$(function(){ });', '/') . '/', $script[1]);
} }
/** /**
* testEvent method * testEvent method
@ -505,52 +557,78 @@ class JavascriptTest extends CakeTestCase {
*/ */
function testEvent() { function testEvent() {
$result = $this->Javascript->event('myId', 'click', 'something();'); $result = $this->Javascript->event('myId', 'click', 'something();');
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*.+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '.+<\/script>$/s', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); "Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('myId', 'click', 'something();', array('safe' => false)); $result = $this->Javascript->event('myId', 'click', 'something();', array('safe' => false));
$this->assertPattern('/^<script[^<>]+>[^<>]+<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); "Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); '/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('myId', 'click'); $result = $this->Javascript->event('myId', 'click');
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*.+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { }, false);')) . '.+<\/script>$/s', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); "Event.observe($('myId'), 'click', function(event) { }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('myId', 'click', 'something();', false); $result = $this->Javascript->event('myId', 'click', 'something();', false);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*.+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '.+<\/script>$/s', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); "Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('myId', 'click', 'something();', array('useCapture' => true)); $result = $this->Javascript->event('myId', 'click', 'something();', array('useCapture' => true));
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*.+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, true);')) . '.+<\/script>$/s', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); "Event.observe($('myId'), 'click', function(event) { something(); }, true);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('document', 'load'); $result = $this->Javascript->event('document', 'load');
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*.+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+' . str_replace('/', '\\/', preg_quote('Event.observe(document, \'load\', function(event) { }, false);')) . '.+<\/script>$/s', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); "Event.observe(document, 'load', function(event) { }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('$(\'myId\')', 'click', 'something();', array('safe' => false)); $result = $this->Javascript->event('$(\'myId\')', 'click', 'something();', array('safe' => false));
$this->assertPattern('/^<script[^<>]+>[^<>]+<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); "Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); '/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('\'document\'', 'load', 'something();', array('safe' => false)); $result = $this->Javascript->event('\'document\'', 'load', 'something();', array('safe' => false));
$this->assertPattern('/^<script[^<>]+>[^<>]+<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">' . str_replace('/', '\\/', preg_quote('Event.observe(\'document\', \'load\', function(event) { something(); }, false);')) . '<\/script>$/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); "Event.observe('document', 'load', function(event) { something(); }, false);",
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); '/script'
);
$this->assertTags($result, $expected);
$this->Javascript->cacheEvents(); $this->Javascript->cacheEvents();
$result = $this->Javascript->event('myId', 'click', 'something();'); $result = $this->Javascript->event('myId', 'click', 'something();');
@ -577,10 +655,14 @@ class JavascriptTest extends CakeTestCase {
$this->assertNull($result); $this->assertNull($result);
$result = $this->Javascript->writeEvents(); $result = $this->Javascript->writeEvents();
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*.+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '.+<\/script>$/s', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); "Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->getCache(); $result = $this->Javascript->getCache();
$this->assertTrue(empty($result)); $this->assertTrue(empty($result));
@ -595,10 +677,15 @@ class JavascriptTest extends CakeTestCase {
$this->assertNull($result); $this->assertNull($result);
$this->assertEqual(count($resultScripts), 1); $this->assertEqual(count($resultScripts), 1);
$result = current($resultScripts); $result = current($resultScripts);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*.+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '.+<\/script>$/s', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); 'script' => array('type' => 'text/javascript'),
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); $this->cDataStart,
"Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->getCache(); $result = $this->Javascript->getCache();
$this->assertTrue(empty($result)); $this->assertTrue(empty($result));
@ -698,7 +785,7 @@ class JavascriptTest extends CakeTestCase {
$data['mystring'] = "a \"double-quoted\" string"; $data['mystring'] = "a \"double-quoted\" string";
$this->assertEqual(json_encode($data), $this->Javascript->object($data)); $this->assertEqual(json_encode($data), $this->Javascript->object($data));
$data['mystring'] = 'a \\"double-quoted\\" string'; $data['mystring'] = 'a \\"double-quoted\\" string';
$this->assertEqual(json_encode($data), $this->Javascript->object($data)); $this->assertEqual(json_encode($data), $this->Javascript->object($data));
} }
@ -739,11 +826,15 @@ class JavascriptTest extends CakeTestCase {
ob_start(); ob_start();
$this->Javascript->afterRender(); $this->Javascript->afterRender();
$result = ob_get_clean(); $result = ob_get_clean();
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*.+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result); $expected = array(
$this->assertPattern('/^<script[^<>]+type="text\/javascript">.+' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '.+<\/script>$/s', $result); 'script' => array('type' => 'text/javascript'),
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>/', $result); $this->cDataStart,
$this->assertNoPattern('/^<script[^type]=[^<>]*>/', $result); "Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->getCache(); $result = $this->Javascript->getCache();
$this->assertTrue(empty($result)); $this->assertTrue(empty($result));

View file

@ -164,6 +164,16 @@ class JqueryEngineHelperTestCase extends CakeTestCase {
)); ));
$expected = '$.ajax({success:function (msg, status) {$("#updated").html(msg);}, type:"post", url:"\\/people\\/edit\\/1"});'; $expected = '$.ajax({success:function (msg, status) {$("#updated").html(msg);}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->Jquery->request('/people/edit/1', array(
'update' => '#updated',
'success' => 'doFoo',
'method' => 'post',
'dataExpression' => true,
'data' => '$("#someId").serialize()'
));
$expected = '$.ajax({data:$("#someId").serialize(), success:function (msg, status) {$("#updated").html(msg);}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEqual($result, $expected);
} }
/** /**
* test sortable list generation * test sortable list generation

View file

@ -116,9 +116,11 @@ class PaginatorHelperTest extends CakeTestCase {
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$this->Paginator->params['paging']['Article']['prevPage'] = false; $this->Paginator->params['paging']['Article']['prevPage'] = false;
$result = $this->Paginator->prev('prev', array('update'=> 'theList', 'indicator'=> 'loading', 'url'=> array('controller' => 'posts')), null, array('class' => 'disabled', 'tag' => 'span')); $result = $this->Paginator->prev('prev', array('update' => 'theList', 'indicator' => 'loading', 'url' => array('controller' => 'posts')), null, array('class' => 'disabled', 'tag' => 'span'));
$expected = '<span class="disabled">prev</span>'; $expected = array(
$this->assertEqual($result, $expected); 'span' => array('class' => 'disabled'), 'prev', '/span'
);
$this->assertTags($result, $expected);
} }
/** /**
* testSortLinks method * testSortLinks method
@ -135,24 +137,60 @@ class PaginatorHelperTest extends CakeTestCase {
)); ));
$this->Paginator->options(array('url' => array('param'))); $this->Paginator->options(array('url' => array('param')));
$result = $this->Paginator->sort('title'); $result = $this->Paginator->sort('title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc">Title<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->sort('date'); $result = $this->Paginator->sort('date');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:date\/direction:desc">Date<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:date/direction:desc'),
'Date',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(array('modulus'=> '2', 'url'=> array('controller'=>'projects', 'action'=>'sort'),'update'=>'list')); $result = $this->Paginator->numbers(array('modulus'=> '2', 'url'=> array('controller'=>'projects', 'action'=>'sort'),'update'=>'list'));
$this->assertPattern('/\/projects\/sort\/page:2/', $result); $this->assertPattern('/\/projects\/sort\/page:2/', $result);
$this->assertPattern('/<script type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*Event.observe/', $result); $this->assertPattern('/<script type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*Event.observe/', $result);
$result = $this->Paginator->sort('TestTitle', 'title'); $result = $this->Paginator->sort('TestTitle', 'title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc">TestTitle<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:asc'),
'TestTitle',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->sort(array('asc' => 'ascending', 'desc' => 'descending'), 'title'); $result = $this->Paginator->sort(array('asc' => 'ascending', 'desc' => 'descending'), 'title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc">ascending<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:asc'),
'ascending',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['sort'] = 'title'; $this->Paginator->params['paging']['Article']['options']['sort'] = 'title';
$result = $this->Paginator->sort(array('asc' => 'ascending', 'desc' => 'descending'), 'title'); $result = $this->Paginator->sort(array('asc' => 'ascending', 'desc' => 'descending'), 'title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc">descending<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:desc'),
'descending',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc">Title<\/a>$/', $result);
} }
/** /**
* testSortLinksUsingDotNotation method * testSortLinksUsingDotNotation method
@ -170,16 +208,30 @@ class PaginatorHelperTest extends CakeTestCase {
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc'); $this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$result = $this->Paginator->sort('Title','Article.title'); $result = $this->Paginator->sort('Title','Article.title');
$this->assertPattern('/\/accounts\/index\/page:1\/sort:Article.title\/direction:asc">Title<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:Article.title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc'); $this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$result = $this->Paginator->sort('Title','Article.title'); $result = $this->Paginator->sort('Title','Article.title');
$this->assertPattern('/\/accounts\/index\/page:1\/sort:Article.title\/direction:desc">Title<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:Article.title/direction:desc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Account.title' => 'asc'); $this->Paginator->params['paging']['Article']['options']['order'] = array('Account.title' => 'asc');
$result = $this->Paginator->sort('title'); $result = $this->Paginator->sort('title');
$this->assertPattern('/\/accounts\/index\/page:1\/sort:title\/direction:asc">Title<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
} }
/** /**
* testSortKey method * testSortKey method
@ -188,7 +240,6 @@ class PaginatorHelperTest extends CakeTestCase {
* @return void * @return void
*/ */
function testSortKey() { function testSortKey() {
$result = $this->Paginator->sortKey(null, array( $result = $this->Paginator->sortKey(null, array(
'order' => array('Article.title' => 'desc' 'order' => array('Article.title' => 'desc'
))); )));
@ -200,69 +251,69 @@ class PaginatorHelperTest extends CakeTestCase {
* @access public * @access public
* @return void * @return void
*/ */
function testSortDir() { function testSortDir() {
$result = $this->Paginator->sortDir(); $result = $this->Paginator->sortDir();
$expected = 'asc'; $expected = 'asc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc'); $this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$result = $this->Paginator->sortDir(); $result = $this->Paginator->sortDir();
$expected = 'desc'; $expected = 'desc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']); unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc'); $this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$result = $this->Paginator->sortDir(); $result = $this->Paginator->sortDir();
$expected = 'asc'; $expected = 'asc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']); unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('title' => 'desc'); $this->Paginator->params['paging']['Article']['options']['order'] = array('title' => 'desc');
$result = $this->Paginator->sortDir(); $result = $this->Paginator->sortDir();
$expected = 'desc'; $expected = 'desc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']); unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('title' => 'asc'); $this->Paginator->params['paging']['Article']['options']['order'] = array('title' => 'asc');
$result = $this->Paginator->sortDir(); $result = $this->Paginator->sortDir();
$expected = 'asc'; $expected = 'asc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']); unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['direction'] = 'asc'; $this->Paginator->params['paging']['Article']['options']['direction'] = 'asc';
$result = $this->Paginator->sortDir(); $result = $this->Paginator->sortDir();
$expected = 'asc'; $expected = 'asc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
unset($this->paginator->params['paging']['article']['options']); unset($this->paginator->params['paging']['article']['options']);
$this->Paginator->params['paging']['Article']['options']['direction'] = 'desc'; $this->Paginator->params['paging']['Article']['options']['direction'] = 'desc';
$result = $this->Paginator->sortDir(); $result = $this->Paginator->sortDir();
$expected = 'desc'; $expected = 'desc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']); unset($this->Paginator->params['paging']['Article']['options']);
$result = $this->Paginator->sortDir('Article', array('direction' => 'asc')); $result = $this->Paginator->sortDir('Article', array('direction' => 'asc'));
$expected = 'asc'; $expected = 'asc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->Paginator->sortDir('Article', array('direction' => 'desc')); $result = $this->Paginator->sortDir('Article', array('direction' => 'desc'));
$expected = 'desc'; $expected = 'desc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->Paginator->sortDir('Article', array('direction' => 'asc')); $result = $this->Paginator->sortDir('Article', array('direction' => 'asc'));
$expected = 'asc'; $expected = 'asc';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
} }
/** /**
* testSortAdminLinks method * testSortAdminLinks method
* *
@ -280,8 +331,12 @@ class PaginatorHelperTest extends CakeTestCase {
Router::parse('/admin/users'); Router::parse('/admin/users');
$this->Paginator->params['paging']['Article']['page'] = 1; $this->Paginator->params['paging']['Article']['page'] = 1;
$result = $this->Paginator->next('Next'); $result = $this->Paginator->next('Next');
$this->assertPattern('/^<a[^<>]+>Next<\/a>$/', $result); $expected = array(
$this->assertPattern('/href="\/admin\/users\/index\/page:2"/', $result); 'a' => array('href' => '/admin/users/index/page:2'),
'Next',
'/a'
);
$this->assertTags($result, $expected);
Router::reload(); Router::reload();
Router::setRequestInfo(array( Router::setRequestInfo(array(
@ -291,12 +346,21 @@ class PaginatorHelperTest extends CakeTestCase {
Router::parse('/'); Router::parse('/');
$this->Paginator->options(array('url' => array('param'))); $this->Paginator->options(array('url' => array('param')));
$result = $this->Paginator->sort('title'); $result = $this->Paginator->sort('title');
$this->assertPattern('/\/admin\/test\/index\/param\/page:1\/sort:title\/direction:asc"\s*>Title<\/a>$/', $result); $expected = array(
'a' => array('href' => '/admin/test/index/param/page:1/sort:title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('param'))); $this->Paginator->options(array('url' => array('param')));
$result = $this->Paginator->sort('Title', 'Article.title'); $result = $this->Paginator->sort('Title', 'Article.title');
$this->assertPattern('/\/admin\/test\/index\/param\/page:1\/sort:Article.title\/direction:asc"\s*>Title<\/a>$/', $result); $expected = array(
'a' => array('href' => '/admin/test/index/param/page:1/sort:Article.title/direction:asc'),
'Title',
'/a'
);
$this->assertTags($result, $expected);
} }
/** /**
* testUrlGeneration method * testUrlGeneration method
@ -306,8 +370,12 @@ class PaginatorHelperTest extends CakeTestCase {
*/ */
function testUrlGeneration() { function testUrlGeneration() {
$result = $this->Paginator->sort('controller'); $result = $this->Paginator->sort('controller');
$this->assertPattern('/\/page:1\//', $result); $expected = array(
$this->assertPattern('/\/sort:controller\//', $result); 'a' => array('href' => '/index/page:1/sort:controller/direction:asc'),
'Controller',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->url(); $result = $this->Paginator->url();
$this->assertEqual($result, '/index/page:1'); $this->assertEqual($result, '/index/page:1');
@ -351,16 +419,28 @@ class PaginatorHelperTest extends CakeTestCase {
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$result = $this->Paginator->sort('name', null, array('url' => $options)); $result = $this->Paginator->sort('name', null, array('url' => $options));
$expected = '<a href="/members/posts/index/page:2/sort:name/direction:asc">Name</a>'; $expected = array(
$this->assertEqual($result, $expected); 'a' => array('href' => '/members/posts/index/page:2/sort:name/direction:asc'),
'Name',
'/a'
);
$this->assertTags($result, $expected, true);
$result = $this->Paginator->next('next', array('url' => $options)); $result = $this->Paginator->next('next', array('url' => $options));
$expected = '<a href="/members/posts/index/page:3">next</a>'; $expected = array(
$this->assertEqual($result, $expected); 'a' => array('href' => '/members/posts/index/page:3'),
'next',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('prev', array('url' => $options)); $result = $this->Paginator->prev('prev', array('url' => $options));
$expected = '<a href="/members/posts/index/page:1">prev</a>'; $expected = array(
$this->assertEqual($result, $expected); 'a' => array('href' => '/members/posts/index/page:1'),
'prev',
'/a'
);
$this->assertTags($result, $expected);
$options = array('members' => true, 'controller' => 'posts', 'order' => array('name' => 'desc')); $options = array('members' => true, 'controller' => 'posts', 'order' => array('name' => 'desc'));
$result = $this->Paginator->url($options); $result = $this->Paginator->url($options);
@ -432,28 +512,54 @@ class PaginatorHelperTest extends CakeTestCase {
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array())) 'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
); );
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled')); $result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
$expected = '<div class="disabled">&lt;&lt; Previous</div>'; $expected = array(
$this->assertEqual($result, $expected); 'div' => array('class' => 'disabled'),
'&lt;&lt; Previous',
'/div'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled', 'tag' => 'span')); $result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled', 'tag' => 'span'));
$expected = '<span class="disabled">&lt;&lt; Previous</span>'; $expected = array(
$this->assertEqual($result, $expected); 'span' => array('class' => 'disabled'),
'&lt;&lt; Previous',
'/span'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 2; $this->Paginator->params['paging']['Client']['page'] = 2;
$this->Paginator->params['paging']['Client']['prevPage'] = true; $this->Paginator->params['paging']['Client']['prevPage'] = true;
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled')); $result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
$this->assertPattern('/^<a[^<>]+>&lt;&lt; Previous<\/a>$/', $result); $expected = array(
$this->assertPattern('/href="\/index\/page:1"/', $result); 'a' => array('href' => '/index/page:1'),
'&lt;&lt; Previous',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->next('Next'); $result = $this->Paginator->next('Next');
$this->assertPattern('/^<a[^<>]+>Next<\/a>$/', $result); $expected = array(
$this->assertPattern('/href="\/index\/page:3"/', $result); 'a' => array('href' => '/index/page:3'),
'Next',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', array('escape' => true)); $result = $this->Paginator->prev('<< Previous', array('escape' => true));
$this->assertPattern('/^<a[^<>]+>&lt;&lt; Previous<\/a>$/', $result); $expected = array(
'a' => array('href' => '/index/page:1'),
'&lt;&lt; Previous',
'/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', array('escape' => false)); $result = $this->Paginator->prev('<< Previous', array('escape' => false));
$this->assertPattern('/^<a[^<>]+><< Previous<\/a>$/', $result); $expected = array(
'a' => array('href' => '/index/page:1'),
'preg:/<< Previous/',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array( $this->Paginator->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 1, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5, 'page' => 1, 'current' => 1, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
@ -462,13 +568,28 @@ class PaginatorHelperTest extends CakeTestCase {
); );
$result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>'); $result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>');
$this->assertPattern('/^<div>&lt;strong&gt;Disabled&lt;\/strong&gt;<\/div>$/', $result); $expected = array(
'<div',
'&lt;strong&gt;Disabled&lt;/strong&gt;',
'/div'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>', array('escape' => true)); $result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>', array('escape' => true));
$this->assertPattern('/^<div>&lt;strong&gt;Disabled&lt;\/strong&gt;<\/div>$/', $result); $expected = array(
'<div',
'&lt;strong&gt;Disabled&lt;/strong&gt;',
'/div'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>', array('escape' => false)); $result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>', array('escape' => false));
$this->assertPattern('/^<div><strong>Disabled<\/strong><\/div>$/', $result); $expected = array(
'<div',
'<strong', 'Disabled', '/strong',
'/div'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array( $this->Paginator->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5, 'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
@ -479,10 +600,20 @@ class PaginatorHelperTest extends CakeTestCase {
$this->Paginator->params['paging']['Client']['page'] = 2; $this->Paginator->params['paging']['Client']['page'] = 2;
$this->Paginator->params['paging']['Client']['prevPage'] = true; $this->Paginator->params['paging']['Client']['prevPage'] = true;
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled')); $result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
$this->assertPattern('/\/sort:Client.name\/direction:DESC"/', $result); $expected = array(
'a' => array('href' => '/index/page:1/limit:3/sort:Client.name/direction:DESC'),
'&lt;&lt; Previous',
'/a'
);
$this->assertTags($result, $expected, true);
$result = $this->Paginator->next('Next'); $result = $this->Paginator->next('Next');
$this->assertPattern('/\/sort:Client.name\/direction:DESC"/', $result); $expected = array(
'a' => array('href' => '/index/page:3/limit:3/sort:Client.name/direction:DESC'),
'Next',
'/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array( $this->Paginator->params['paging'] = array('Client' => array(
'page' => 2, 'current' => 1, 'count' => 13, 'prevPage' => true, 'nextPage' => false, 'pageCount' => 2, 'page' => 2, 'current' => 1, 'count' => 13, 'prevPage' => true, 'nextPage' => false, 'pageCount' => 2,
@ -520,11 +651,16 @@ class PaginatorHelperTest extends CakeTestCase {
) )
); );
$result = $this->Paginator->next('Next', array('model' => 'Client')); $result = $this->Paginator->next('Next', array('model' => 'Client'));
$this->assertPattern('/^<a[^<>]+>Next<\/a>$/', $result); $expected = array(
$this->assertPattern('/href="\/index\/page:2"/', $result); // These is passed. 'a' => array('href' => '/index/page:2'), 'Next', '/a'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->next('Next', array('model' => 'Server'), 'No Next', array('model' => 'Server')); $result = $this->Paginator->next('Next', array('model' => 'Server'), 'No Next', array('model' => 'Server'));
$this->assertPattern('/^<div>No Next<\/div>$/', $result); $expected = array(
'<div', 'No Next', '/div'
);
$this->assertTags($result, $expected);
} }
/** /**
* testGenericLinks method * testGenericLinks method
@ -534,24 +670,30 @@ class PaginatorHelperTest extends CakeTestCase {
*/ */
function testGenericLinks() { function testGenericLinks() {
$result = $this->Paginator->link('Sort by title on page 5', array('sort' => 'title', 'page' => 5, 'direction' => 'desc')); $result = $this->Paginator->link('Sort by title on page 5', array('sort' => 'title', 'page' => 5, 'direction' => 'desc'));
$this->assertPattern('/^<a href=".+"[^<>]*>Sort by title on page 5<\/a>$/', $result); $expected = array(
$this->assertPattern('/\/page:5/', $result); 'a' => array('href' => '/index/page:5/sort:title/direction:desc'),
$this->assertPattern('/\/sort:title/', $result); 'Sort by title on page 5',
$this->assertPattern('/\/direction:desc/', $result); '/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['page'] = 2; $this->Paginator->params['paging']['Article']['options']['page'] = 2;
$result = $this->Paginator->link('Sort by title', array('sort' => 'title', 'direction' => 'desc')); $result = $this->Paginator->link('Sort by title', array('sort' => 'title', 'direction' => 'desc'));
$this->assertPattern('/^<a href=".+"[^<>]*>Sort by title<\/a>$/', $result); $expected = array(
$this->assertPattern('/\/page:2/', $result); 'a' => array('href' => '/index/page:2/sort:title/direction:desc'),
$this->assertPattern('/\/sort:title/', $result); 'Sort by title',
$this->assertPattern('/\/direction:desc/', $result); '/a'
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['page'] = 4; $this->Paginator->params['paging']['Article']['options']['page'] = 4;
$result = $this->Paginator->link('Sort by title on page 4', array('sort' => 'Article.title', 'direction' => 'desc')); $result = $this->Paginator->link('Sort by title on page 4', array('sort' => 'Article.title', 'direction' => 'desc'));
$this->assertPattern('/^<a href=".+"[^<>]*>Sort by title on page 4<\/a>$/', $result); $expected = array(
$this->assertPattern('/\/page:4/', $result); 'a' => array('href' => '/index/page:4/sort:Article.title/direction:desc'),
$this->assertPattern('/\/sort:Article.title/', $result); 'Sort by title on page 4',
$this->assertPattern('/\/direction:desc/', $result); '/a'
);
$this->assertTags($result, $expected);
} }
/** /**
* Tests generation of generic links with preset options * Tests generation of generic links with preset options
@ -725,6 +867,66 @@ class PaginatorHelperTest extends CakeTestCase {
$result = $this->Paginator->numbers(); $result = $this->Paginator->numbers();
$expected = '<span><a href="/index/page:1/sort:Client.name/direction:DESC">1</a></span> | <span class="current">2</span> | <span><a href="/index/page:3/sort:Client.name/direction:DESC">3</a></span> | <span><a href="/index/page:4/sort:Client.name/direction:DESC">4</a></span>'; $expected = '<span><a href="/index/page:1/sort:Client.name/direction:DESC">1</a></span> | <span class="current">2</span> | <span><a href="/index/page:3/sort:Client.name/direction:DESC">3</a></span> | <span><a href="/index/page:4/sort:Client.name/direction:DESC">4</a></span>';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 4895, 'current' => 10, 'count' => 48962, 'prevPage' => 1, 'nextPage' => 1, 'pageCount' => 4897,
'defaults' => array('limit' => 10),
'options' => array('page' => 4894, 'limit' => 10, 'order' => 'Client.name DESC', 'conditions' => array()))
);
$result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4894')), '4894', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '4895', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
'page' => 3, 'current' => 10, 'count' => 48962, 'prevPage' => 1, 'nextPage' => 1, 'pageCount' => 4897,
'defaults' => array('limit' => 10),
'options' => array('page' => 4894, 'limit' => 10, 'order' => 'Client.name DESC', 'conditions' => array()))
);
$result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' | ',
array('span' => array('class' => 'current')), '3', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' | ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/span',
' - ',
array('span' => array('class' => 'current')), '3', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/span',
'...',
array('span' => array()), array('a' => array('href' => '/index/page:4896')), '4896', '/a', '/span',
' - ',
array('span' => array()), array('a' => array('href' => '/index/page:4897')), '4897', '/a', '/span',
);
$this->assertTags($result, $expected);
} }
/** /**
* testFirstAndLast method * testFirstAndLast method
@ -750,28 +952,71 @@ class PaginatorHelperTest extends CakeTestCase {
); );
$result = $this->Paginator->first(); $result = $this->Paginator->first();
$expected = '<span><a href="/index/page:1">&lt;&lt; first</a></span>'; $expected = array(
$this->assertEqual($result, $expected); '<span',
'a' => array('href' => '/index/page:1'),
'&lt;&lt; first',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->first('<<', array('tag' => 'li')); $result = $this->Paginator->first('<<', array('tag' => 'li'));
$expected = '<li><a href="/index/page:1">&lt;&lt;</a></li>'; $expected = array(
$this->assertEqual($result, $expected); '<li',
'a' => array('href' => '/index/page:1'),
'&lt;&lt;',
'/a',
'/li'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(); $result = $this->Paginator->last();
$expected = '<span><a href="/index/page:15">last &gt;&gt;</a></span>'; $expected = array(
$this->assertEqual($result, $expected); '<span',
'a' => array('href' => '/index/page:15'),
'last &gt;&gt;',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(1); $result = $this->Paginator->last(1);
$expected = '...<span><a href="/index/page:15">15</a></span>'; $expected = array(
$this->assertEqual($result, $expected); '...',
'<span',
'a' => array('href' => '/index/page:15'),
'15',
'/a',
'/span'
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(2); $result = $this->Paginator->last(2);
$expected = '...<span><a href="/index/page:14">14</a></span> | <span><a href="/index/page:15">15</a></span>'; $expected = array(
$this->assertEqual($result, $expected); '...',
'<span',
array('a' => array('href' => '/index/page:14')), '14', '/a',
'/span',
' | ',
'<span',
array('a' => array('href' => '/index/page:15')), '15', '/a',
'/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(2, array('tag' => 'li')); $result = $this->Paginator->last(2, array('tag' => 'li'));
$expected = '...<li><a href="/index/page:14">14</a></li> | <li><a href="/index/page:15">15</a></li>'; $expected = array(
$this->assertEqual($result, $expected); '...',
'<li',
array('a' => array('href' => '/index/page:14')), '14', '/a',
'/li',
' | ',
'<li',
array('a' => array('href' => '/index/page:15')), '15', '/a',
'/li',
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array( $this->Paginator->params['paging'] = array('Client' => array(
'page' => 15, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15, 'page' => 15, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
@ -789,20 +1034,42 @@ class PaginatorHelperTest extends CakeTestCase {
); );
$result = $this->Paginator->first(); $result = $this->Paginator->first();
$expected = '<span><a href="/index/page:1/sort:Client.name/direction:DESC">&lt;&lt; first</a></span>'; $expected = array(
$this->assertEqual($result, $expected); '<span',
array('a' => array('href' => '/index/page:1/sort:Client.name/direction:DESC')), '&lt;&lt; first', '/a',
'/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(); $result = $this->Paginator->last();
$expected = '<span><a href="/index/page:15/sort:Client.name/direction:DESC">last &gt;&gt;</a></span>'; $expected = array(
$this->assertEqual($result, $expected); '<span',
array('a' => array('href' => '/index/page:15/sort:Client.name/direction:DESC')), 'last &gt;&gt;', '/a',
'/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(1); $result = $this->Paginator->last(1);
$expected = '...<span><a href="/index/page:15/sort:Client.name/direction:DESC">15</a></span>'; $expected = array(
$this->assertEqual($result, $expected); '...',
'<span',
array('a' => array('href' => '/index/page:15/sort:Client.name/direction:DESC')), '15', '/a',
'/span',
);
$this->assertTags($result, $expected);
$result = $this->Paginator->last(2); $result = $this->Paginator->last(2);
$expected = '...<span><a href="/index/page:14/sort:Client.name/direction:DESC">14</a></span> | <span><a href="/index/page:15/sort:Client.name/direction:DESC">15</a></span>'; $expected = array(
$this->assertEqual($result, $expected); '...',
'<span',
array('a' => array('href' => '/index/page:14/sort:Client.name/direction:DESC')), '14', '/a',
'/span',
' | ',
'<span',
array('a' => array('href' => '/index/page:15/sort:Client.name/direction:DESC')), '15', '/a',
'/span',
);
$this->assertTags($result, $expected);
} }
/** /**
* testCounter method * testCounter method
@ -862,7 +1129,6 @@ class PaginatorHelperTest extends CakeTestCase {
$result = $this->Paginator->counter(array('format' => 'range')); $result = $this->Paginator->counter(array('format' => 'range'));
$expected = '1 - 3 of 13'; $expected = '1 - 3 of 13';
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
} }
/** /**
* testHasPage method * testHasPage method
@ -900,23 +1166,37 @@ class PaginatorHelperTest extends CakeTestCase {
)); ));
$result = $this->Paginator->link('Page 3', array('page' => 3)); $result = $this->Paginator->link('Page 3', array('page' => 3));
$this->assertPattern('/["\']\/my_plugin\/magazines\/index\/page:3["\']/', $result); $expected = array(
'a' => array('href' => '/my_plugin/magazines/index/page:3'), 'Page 3', '/a'
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('action' => 'another_index'))); $this->Paginator->options(array('url' => array('action' => 'another_index')));
$result = $this->Paginator->link('Page 3', array('page' => 3)); $result = $this->Paginator->link('Page 3', array('page' => 3));
$this->assertPattern('/["\']\/my_plugin\/magazines\/another_index\/page:3["\']/', $result); $expected = array(
'a' => array('href' => '/my_plugin/magazines/another_index/page:3'), 'Page 3', '/a'
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('controller' => 'issues'))); $this->Paginator->options(array('url' => array('controller' => 'issues')));
$result = $this->Paginator->link('Page 3', array('page' => 3)); $result = $this->Paginator->link('Page 3', array('page' => 3));
$this->assertPattern('/["\']\/my_plugin\/issues\/index\/page:3["\']/', $result); $expected = array(
'a' => array('href' => '/my_plugin/issues/index/page:3'), 'Page 3', '/a'
);
$this->assertTags($result, $expected);
$this->Paginator->options(array('url' => array('plugin' => null))); $this->Paginator->options(array('url' => array('plugin' => null)));
$result = $this->Paginator->link('Page 3', array('page' => 3)); $result = $this->Paginator->link('Page 3', array('page' => 3));
$this->assertPattern('/["\']\/magazines\/index\/page:3["\']/', $result); $expected = array(
'a' => array('/magazines/index/page:3'), 'Page 3', '/a'
);
$this->Paginator->options(array('url' => array('plugin' => null, 'controller' => 'issues'))); $this->Paginator->options(array('url' => array('plugin' => null, 'controller' => 'issues')));
$result = $this->Paginator->link('Page 3', array('page' => 3)); $result = $this->Paginator->link('Page 3', array('page' => 3));
$this->assertPattern('/["\']\/issues\/index\/page:3["\']/', $result); $expected = array(
'a' => array('href' => '/issues/index/page:3'), 'Page 3', '/a'
);
$this->assertTags($result, $expected);
} }
/** /**
@ -944,7 +1224,12 @@ class PaginatorHelperTest extends CakeTestCase {
$this->Paginator->options($test); $this->Paginator->options($test);
$result = $this->Paginator->next('Next'); $result = $this->Paginator->next('Next');
$this->assertPattern('/\/accounts\/index\/page:2\/sort:Article.title\/direction:asc">Next<\/a>$/', $result); $expected = array(
'a' => array('href' => '/officespace/accounts/index/page:2/sort:Article.title/direction:asc'),
'Next',
'/a'
);
$this->assertTags($result, $expected);
} }
} }
?> ?>

View file

@ -140,10 +140,20 @@ class TextHelperTest extends CakeTestCase {
$text1 = '<p>strongbow isn&rsquo;t real cider</p>'; $text1 = '<p>strongbow isn&rsquo;t real cider</p>';
$text2 = '<p>strongbow <strong>isn&rsquo;t</strong> real cider</p>'; $text2 = '<p>strongbow <strong>isn&rsquo;t</strong> real cider</p>';
$text3 = '<img src="what-a-strong-mouse.png" alt="What a strong mouse!" />'; $text3 = '<img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$text4 = 'What a strong mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$expected = '<p><b>strong</b>bow isn&rsquo;t real cider</p>';
$this->assertEqual($this->Text->highlight($text1, 'strong', '<b>\1</b>', true), $expected);
$expected = '<p><b>strong</b>bow <strong>isn&rsquo;t</strong> real cider</p>';
$this->assertEqual($this->Text->highlight($text2, 'strong', '<b>\1</b>', true), $expected);
$this->assertEqual($this->Text->highlight($text1, 'strong', '<b>\1</b>', true), '<p><b>strong</b>bow isn&rsquo;t real cider</p>');
$this->assertEqual($this->Text->highlight($text2, 'strong', '<b>\1</b>', true), '<p><b>strong</b>bow <strong>isn&rsquo;t</strong> real cider</p>');
$this->assertEqual($this->Text->highlight($text3, 'strong', '<b>\1</b>', true), $text3); $this->assertEqual($this->Text->highlight($text3, 'strong', '<b>\1</b>', true), $text3);
$this->assertEqual($this->Text->highlight($text3, array('strong', 'what'), '<b>\1</b>', true), $text3);
$expected = '<b>What</b> a <b>strong</b> mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$this->assertEqual($this->Text->highlight($text4, array('strong', 'what'), '<b>\1</b>', true), $expected);
} }
/** /**
* testStripLinks method * testStripLinks method
@ -277,22 +287,32 @@ class TextHelperTest extends CakeTestCase {
$expected = '...with test text...'; $expected = '...with test text...';
$result = $this->Text->excerpt($text, 'test', 9, '...'); $result = $this->Text->excerpt($text, 'test', 9, '...');
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$expected = 'This is a...'; $expected = 'This is a...';
$result = $this->Text->excerpt($text, 'not_found', 9, '...'); $result = $this->Text->excerpt($text, 'not_found', 9, '...');
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$expected = 'This is a phras...'; $expected = 'This is a phras...';
$result = $this->Text->excerpt($text, null, 9, '...'); $result = $this->Text->excerpt($text, null, 9, '...');
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$expected = $text; $expected = $text;
$result = $this->Text->excerpt($text, null, 200, '...'); $result = $this->Text->excerpt($text, null, 200, '...');
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$expected = '...phrase...'; $expected = '...phrase...';
$result = $this->Text->excerpt($text, 'phrase', 2, '...'); $result = $this->Text->excerpt($text, 'phrase', 2, '...');
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$phrase = 'This is a phrase with test';
$expected = $text;
$result = $this->Text->excerpt($text, $phrase, strlen($phrase) + 3, '...');
$this->assertEqual($expected, $result);
$phrase = 'This is a phrase with text';
$expected = $text;
$result = $this->Text->excerpt($text, $phrase, 10, '...');
$this->assertEqual($expected, $result);
} }
/** /**
* testExcerptCaseInsensitivity method * testExcerptCaseInsensitivity method

View file

@ -276,6 +276,23 @@ class TimeHelperTest extends CakeTestCase {
$fourHours = $this->Time->timeAgoInWords(strtotime('-5 days, -2 hours'), array('userOffset' => -4)); $fourHours = $this->Time->timeAgoInWords(strtotime('-5 days, -2 hours'), array('userOffset' => -4));
$result = $this->Time->timeAgoInWords(strtotime('-5 days, -2 hours'), array('userOffset' => 4)); $result = $this->Time->timeAgoInWords(strtotime('-5 days, -2 hours'), array('userOffset' => 4));
$this->assertEqual($fourHours, $result); $this->assertEqual($fourHours, $result);
$result = $this->Time->timeAgoInWords(strtotime('-2 hours'));
$expected = '2 hours ago';
$this->assertEqual($expected, $result);
$result = $this->Time->timeAgoInWords(strtotime('-12 minutes'));
$expected = '12 minutes ago';
$this->assertEqual($expected, $result);
$result = $this->Time->timeAgoInWords(strtotime('-12 seconds'));
$expected = '12 seconds ago';
$this->assertEqual($expected, $result);
$time = strtotime('-3 years -12 months');
$result = $this->Time->timeAgoInWords($time);
$expected = 'on ' . date('j/n/y', $time);
$this->assertEqual($expected, $result);
} }
/** /**
* testRelative method * testRelative method

View file

@ -159,6 +159,18 @@ class ThemeViewTest extends CakeTestCase {
unset($this->PostsController); unset($this->PostsController);
unset($this->Controller); unset($this->Controller);
} }
/**
* startTest
*
* @access public
* @return void
*/
function startTest() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
}
/** /**
* endTest * endTest
* *
@ -182,11 +194,6 @@ class ThemeViewTest extends CakeTestCase {
$this->Controller->theme = 'test_plugin_theme'; $this->Controller->theme = 'test_plugin_theme';
$ThemeView = new TestThemeView($this->Controller); $ThemeView = new TestThemeView($this->Controller);
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS .'test_plugin' . DS . 'views' . DS . 'themed' . DS . 'test_plugin_theme' . DS .'tests' . DS .'index.ctp'; $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS .'test_plugin' . DS . 'views' . DS . 'themed' . DS . 'test_plugin_theme' . DS .'tests' . DS .'index.ctp';
$result = $ThemeView->getViewFileName('index'); $result = $ThemeView->getViewFileName('index');
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
@ -210,12 +217,6 @@ class ThemeViewTest extends CakeTestCase {
$ThemeView = new TestThemeView($this->Controller); $ThemeView = new TestThemeView($this->Controller);
$ThemeView->theme = 'test_theme'; $ThemeView->theme = 'test_theme';
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS .'pages' . DS .'home.ctp'; $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS .'pages' . DS .'home.ctp';
$result = $ThemeView->getViewFileName('home'); $result = $ThemeView->getViewFileName('home');
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);

View file

@ -0,0 +1,58 @@
<?php
/**
* Bake Group test file
*
* Run all the test cases related to bake.
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.groups
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
/**
* BakeGroupTest class
*
* This test group will run all bake tests
*
* @package cake
* @subpackage cake.tests.groups
*/
class BakeGroupTest extends GroupTest {
/**
* label property
*
* @var string 'All core cache engines'
* @access public
*/
var $label = 'All Tasks related to bake.';
/**
* BakeGroupTest method
*
* @access public
* @return void
*/
function BakeGroupTest() {
$path = CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'tasks' . DS;
TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'bake');
TestManager::addTestFile($this, $path . 'controller');
TestManager::addTestFile($this, $path . 'model');
TestManager::addTestFile($this, $path . 'view');
TestManager::addTestFile($this, $path . 'fixture');
TestManager::addTestFile($this, $path . 'test');
TestManager::addTestFile($this, $path . 'db_config');
TestManager::addTestFile($this, $path . 'plugin');
TestManager::addTestFile($this, $path . 'project');
}
}
?>

View file

@ -0,0 +1,56 @@
<?php
/* SVN FILE: $Id$ */
/**
* DatabaseGroupTest file
*
* Long description for file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.groups
* @since CakePHP(tm) v 1.2.0.5517
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
/**
* DatabaseGroupTest class
*
* This test group will run all behavior, schema and datasource tests excluding database
* driver-specific tests
*
* @package cake
* @subpackage cake.tests.groups
*/
class DatabaseGroupTest extends GroupTest {
/**
* label property
*
* @var string 'All model tests'
* @access public
*/
var $label = 'Datasources, Schema and DbAcl tests';
/**
* ModelGroupTest method
*
* @access public
* @return void
*/
function DatabaseGroupTest() {
TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'db_acl');
TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'schema');
TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'datasources' . DS . 'dbo_source');
}
}
?>

View file

@ -37,10 +37,10 @@ class ModelGroupTest extends GroupTest {
/** /**
* label property * label property
* *
* @var string 'All model tests' * @var string
* @access public * @access public
*/ */
var $label = 'Model, all Behaviors and Datasources'; var $label = 'Model & Behavior tests';
/** /**
* ModelGroupTest method * ModelGroupTest method
* *
@ -49,9 +49,6 @@ class ModelGroupTest extends GroupTest {
*/ */
function ModelGroupTest() { function ModelGroupTest() {
TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'model'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'model');
TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'db_acl');
TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'schema');
TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'datasources' . DS . 'dbo_source');
TestManager::addTestCasesFromDirectory($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'behaviors'); TestManager::addTestCasesFromDirectory($this, CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'behaviors');
} }
} }

View file

@ -425,10 +425,11 @@ class CakeTestCase extends UnitTestCase {
return; return;
} }
foreach ($this->_fixtures as $fixture) { foreach ($this->_fixtures as $fixture) {
if (in_array($fixture->table, $sources)) { $table = $this->db->config['prefix'] . $fixture->table;
if (in_array($table, $sources)) {
$fixture->drop($this->db); $fixture->drop($this->db);
$fixture->create($this->db); $fixture->create($this->db);
} elseif (!in_array($fixture->table, $sources)) { } elseif (!in_array($table, $sources)) {
$fixture->create($this->db); $fixture->create($this->db);
} }
} }
@ -726,7 +727,7 @@ class CakeTestCase extends UnitTestCase {
if (strpos($fixture, 'core.') === 0) { if (strpos($fixture, 'core.') === 0) {
$fixture = substr($fixture, strlen('core.')); $fixture = substr($fixture, strlen('core.'));
foreach (Configure::corePaths('cake') as $key => $path) { foreach (App::core('cake') as $key => $path) {
$fixturePaths[] = $path . 'tests' . DS . 'fixtures'; $fixturePaths[] = $path . 'tests' . DS . 'fixtures';
} }
} elseif (strpos($fixture, 'app.') === 0) { } elseif (strpos($fixture, 'app.') === 0) {

View file

@ -31,6 +31,12 @@
* @subpackage cake.cake.tests.lib * @subpackage cake.cake.tests.lib
*/ */
class CakeTestFixture extends Object { class CakeTestFixture extends Object {
/**
* Name of the object
*
* @var string
**/
var $name = null;
/** /**
* Cake's DBO driver (e.g: DboMysql). * Cake's DBO driver (e.g: DboMysql).
* *
@ -43,7 +49,6 @@ class CakeTestFixture extends Object {
* @access public * @access public
*/ */
var $table = null; var $table = null;
/** /**
* Instantiate the fixture. * Instantiate the fixture.
* *
@ -185,4 +190,4 @@ class CakeTestFixture extends Object {
return $return; return $return;
} }
} }
?> ?>

View file

@ -129,4 +129,5 @@
<h1>CakePHP: the rapid development php framework</h1> <h1>CakePHP: the rapid development php framework</h1>
</div> </div>
<div id="content"> <div id="content">
<h2>CakePHP Test Suite v 1.3.0.0</h2>
<h2>CakePHP Test Suite v 1.3.0.0</h2>

View file

@ -33,7 +33,8 @@ class TestsAppsPostsController extends AppController {
$data = array( $data = array(
'Post' => array( 'Post' => array(
'title' => 'Test article', 'title' => 'Test article',
'body' => 'Body of article.' 'body' => 'Body of article.',
'author_id' => 1
) )
); );
$this->Post->save($data); $this->Post->save($data);

View file

@ -0,0 +1,18 @@
msgid ""
msgstr ""
"Project-Id-Version: CakePHP Testsuite\n"
"POT-Creation-Date: 2008-05-15 02:51-0700\n"
"PO-Revision-Date: \n"
"Last-Translator: CakePHP I18N & I10N Team <i10n.cakephp@gmail.com>\n"
"Language-Team: CakePHP I18N & I10N Team <i10n.cakephp@gmail.com>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n"
"X-Poedit-Language: Three Forms of Plurals\n"
"X-Poedit-SourceCharset: utf-8\n"
msgid ""
msgstr "header"
msgid "Plural Rule 1"
msgstr "Monetary Po (translated)"

View file

@ -0,0 +1,22 @@
msgid ""
msgstr ""
"Project-Id-Version: CakePHP Testsuite\n"
"POT-Creation-Date: 2008-05-15 02:51-0700\n"
"PO-Revision-Date: \n"
"Last-Translator: CakePHP I18N & I10N Team <i10n.cakephp@gmail.com>\n"
"Language-Team: CakePHP I18N & I10N Team <i10n.cakephp@gmail.com>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Poedit-Language: Two Forms of Plurals\n"
"X-Poedit-SourceCharset: utf-8\n"
msgid "Plural Rule 1"
msgstr "Monetary Plural Rule 1 (from plugin)"
msgid "%d = 1"
msgid_plural "%d = 0 or > 1"
msgstr[0] "Monetary %d = 1 (from plugin)"
msgstr[1] "Monetary %d = 0 or > 1 (from plugin)"

View file

@ -0,0 +1,2 @@
I got rendered
<?php echo $test; ?>