Merge branch '1.2'

This commit is contained in:
gwoo 2009-08-03 13:24:49 -07:00
commit b3b7eb0f94
125 changed files with 17075 additions and 7470 deletions

View file

@ -362,8 +362,8 @@ if (!function_exists('array_combine')) {
*/
function env($key) {
if ($key == 'HTTPS') {
if (isset($_SERVER) && !empty($_SERVER)) {
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on');
if (isset($_SERVER['HTTPS'])) {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
}
return (strpos(env('SCRIPT_URI'), 'https://') === 0);
}
@ -624,9 +624,9 @@ if (!function_exists('file_put_contents')) {
}
if ($return === false) {
echo I18n::translate($singular, $plural, null, 5, $count);
echo I18n::translate($singular, $plural, null, 6, $count);
} 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) {
echo I18n::translate($singular, $plural, $domain, 5, $count);
echo I18n::translate($singular, $plural, $domain, 6, $count);
} 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.
*
* Note that the category must be specified with a numeric value, instead of the constant name. The values are:
* LC_CTYPE 0
* LC_NUMERIC 1
* LC_TIME 2
* LC_COLLATE 3
* LC_MONETARY 4
* LC_MESSAGES 5
* LC_ALL 6
* LC_ALL 0
* LC_COLLATE 1
* LC_CTYPE 2
* LC_MONETARY 3
* LC_NUMERIC 4
* LC_TIME 5
* LC_MESSAGES 6
*
* @param string $domain Domain
* @param string $singular Singular string to translate
@ -810,7 +810,7 @@ if (!function_exists('file_put_contents')) {
foreach ($args[0] as $valueKey => $valueData) {
for ($i = 1; $i < $argc; $i++) {
if (isset($args[$i][$valueKey])) {
if (array_key_exists($valueKey, $args[$i])) {
continue 2;
}
}
@ -830,7 +830,7 @@ if (!function_exists('file_put_contents')) {
function array_intersect_key($arr1, $arr2) {
$res = array();
foreach ($arr1 as $key => $value) {
if (isset($arr2[$key])) {
if (array_key_exists($key, $arr2)) {
$res[$key] = $arr1[$key];
}
}

View file

@ -446,13 +446,15 @@ class ShellDispatcher {
*/
function parseParams($params) {
$this->__parseParams($params);
$defaults = array('app' => 'app', 'root' => dirname(dirname(dirname(__FILE__))), 'working' => null, 'webroot' => 'webroot');
$params = array_merge($defaults, array_intersect_key($this->params, $defaults));
$isWin = array_filter(array_map('strpos', $params, array('\\')));
$isWin = false;
foreach ($defaults as $default => $value) {
if (strpos($params[$default], '\\') !== false) {
$isWin = true;
break;
}
}
$params = str_replace('\\', '/', $params);
if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) {
@ -464,7 +466,7 @@ class ShellDispatcher {
}
}
if ($params['app'][0] == '/' || preg_match('/([a-zA-Z])(:)/i', $params['app'], $matches)) {
if ($params['app'][0] == '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
$params['root'] = dirname($params['app']);
} elseif (strpos($params['app'], '/')) {
$params['root'] .= '/' . dirname($params['app']);

View file

@ -66,7 +66,7 @@ class ApiShell extends Shell {
return $this->help();
}
$type = low($this->args[0]);
$type = strtolower($this->args[0]);
if (isset($this->paths[$type])) {
$path = $this->paths[$type];
@ -196,15 +196,15 @@ class ApiShell extends Shell {
$contents = $File->read();
if (preg_match_all('%(/\\*\\*[\\s\\S]*?\\*/)(\\s+function\\s+\\w+)(\\(.+\\))%', $contents, $result, PREG_PATTERN_ORDER)) {
if (preg_match_all('%(/\\*\\*[\\s\\S]*?\\*/)(\\s+function\\s+\\w+)(\\(.*\\))%', $contents, $result, PREG_PATTERN_ORDER)) {
foreach ($result[2] as $key => $method) {
$method = str_replace('function ', '', trim($method));
if (strpos($method, '__') === false && $method[0] != '_') {
$parsed[$method] = array(
'comment' => r(array('/*', '*/', '*'), '', trim($result[1][$key])),
'comment' => str_replace(array('/*', '*/', '*'), '', trim($result[1][$key])),
'method' => $method,
'parameters' => trim($result[3][$key]),
'parameters' => trim($result[3][$key])
);
}
}

View file

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

View file

@ -199,7 +199,7 @@ class SchemaShell extends Shell {
}
}
$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);
if ($write) {
if (strpos($write, '.sql') === false) {

View file

@ -149,10 +149,10 @@ class Shell extends Object {
ClassRegistry::map($this->name, $this->alias);
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();
}
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();
}
}
@ -297,7 +297,7 @@ class Shell extends Object {
}
if (!isset($this->{$taskName})) {
$this->err("Task '".$taskName."' could not be loaded");
$this->err("Task '" . $taskName . "' could not be loaded");
$this->_stop();
}
}
@ -329,7 +329,7 @@ class Shell extends Object {
}
}
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);
}
}
@ -427,10 +427,10 @@ class Shell extends Object {
$this->out("\n" . sprintf(__("Creating file %s", true), $path));
if (is_file($path) && $this->interactive === true) {
$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");
exit;
} elseif (low($key) != 'y') {
} elseif (strtolower($key) != 'y') {
$this->out(__("Skip", true) ." {$path}\n");
return false;
}
@ -472,7 +472,7 @@ class Shell extends Object {
return true;
}
$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) {
$this->out("\nYou can download SimpleTest from http://simpletest.org", true);
@ -488,8 +488,8 @@ class Shell extends Object {
*/
function shortPath($file) {
$shortPath = str_replace(ROOT, null, $file);
$shortPath = str_replace('..'.DS, '', $shortPath);
return r(DS.DS, DS, $shortPath);
$shortPath = str_replace('..' . DS, '', $shortPath);
return str_replace(DS . DS, DS, $shortPath);
}
/**
* Checks for Configure::read('Routing.admin') and forces user to input it if not enabled
@ -528,7 +528,7 @@ class Shell extends Object {
* @access protected
*/
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

View file

@ -120,7 +120,7 @@ class ControllerTask extends Shell {
$this->out("Baking {$controllerName}Controller");
$this->hr();
$controllerFile = low(Inflector::underscore($controllerName));
$controllerFile = strtolower(Inflector::underscore($controllerName));
$question[] = __("Would you like to build your controller interactively?", true);
if (file_exists($this->path . $controllerFile .'_controller.php')) {
@ -128,29 +128,29 @@ class ControllerTask extends Shell {
}
$doItInteractive = $this->in(join("\n", $question), array('y','n'), 'y');
if (low($doItInteractive) == 'y' || low($doItInteractive) == 'yes') {
if (strtolower($doItInteractive) == 'y' || strtolower($doItInteractive) == 'yes') {
$this->interactive = true;
$wannaUseScaffold = $this->in(__("Would you like to use scaffolding?", true), array('y','n'), 'n');
if (low($wannaUseScaffold) == 'n' || low($wannaUseScaffold) == 'no') {
if (strtolower($wannaUseScaffold) == 'n' || strtolower($wannaUseScaffold) == 'no') {
$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') {
if (strtolower($wannaDoScaffolding) == 'y' || strtolower($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') {
if (strtolower($wannaDoHelpers) == 'y' || strtolower($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') {
if (strtolower($wannaDoComponents) == 'y' || strtolower($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);
@ -163,20 +163,20 @@ class ControllerTask extends Shell {
} else {
$wannaDoScaffolding = $this->in(__("Would you like to include some basic class methods (index(), add(), view(), edit())?", true), array('y','n'), 'y');
if (low($wannaDoScaffolding) == 'y' || low($wannaDoScaffolding) == 'yes') {
if (strtolower($wannaDoScaffolding) == 'y' || strtolower($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')) {
if ((strtolower($wannaDoAdmin) == 'y' || strtolower($wannaDoAdmin) == 'yes')) {
$admin = $this->getAdmin();
}
if (low($wannaDoScaffolding) == 'y' || low($wannaDoScaffolding) == 'yes') {
$actions = $this->bakeActions($controllerName, null, in_array(low($wannaUseSession), array('y', 'yes')));
if (strtolower($wannaDoScaffolding) == 'y' || strtolower($wannaDoScaffolding) == 'yes') {
$actions = $this->bakeActions($controllerName, null, in_array(strtolower($wannaUseSession), array('y', 'yes')));
if ($admin) {
$actions .= $this->bakeActions($controllerName, $admin, in_array(low($wannaUseSession), array('y', 'yes')));
$actions .= $this->bakeActions($controllerName, $admin, in_array(strtolower($wannaUseSession), array('y', 'yes')));
}
}
@ -187,7 +187,7 @@ class ControllerTask extends Shell {
$this->hr();
$this->out("Controller Name: $controllerName");
if (low($wannaUseScaffold) == 'y' || low($wannaUseScaffold) == 'yes') {
if (strtolower($wannaUseScaffold) == 'y' || strtolower($wannaUseScaffold) == 'yes') {
$this->out(" var \$scaffold;");
$actions = 'scaffold';
}
@ -218,7 +218,7 @@ class ControllerTask extends Shell {
$this->hr();
$looksGood = $this->in(__('Look okay?', true), array('y','n'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
if (strtolower($looksGood) == 'y' || strtolower($looksGood) == 'yes') {
$baked = $this->bake($controllerName, $actions, $helpers, $components, $uses);
if ($baked && $this->_checkUnitTest()) {
$this->bakeTest($controllerName);
@ -243,8 +243,11 @@ class ControllerTask extends Shell {
* @access private
*/
function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
$currentModelName = $this->_modelName($controllerName);
if (!App::import('Model', $currentModelName)) {
$currentModelName = $modelImport = $this->_modelName($controllerName);
if ($this->plugin) {
$modelImport = $this->plugin . '.' . $modelImport;
}
if (!App::import('Model', $modelImport)) {
$this->err(__('You must have a model for this class to build scaffold methods. Please try again.', true));
exit;
}
@ -270,7 +273,7 @@ class ControllerTask extends Shell {
$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\t\$this->set('" . $singularName . "', \$this->{$currentModelName}->read(null, \$id));\n";
$actions .= "\t}\n";
$actions .= "\n";
@ -281,7 +284,7 @@ class ControllerTask extends Shell {
$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->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";
@ -310,7 +313,7 @@ class ControllerTask extends Shell {
}
}
if (!empty($compact)) {
$actions .= "\t\t\$this->set(compact(".join(', ', $compact)."));\n";
$actions .= "\t\t\$this->set(compact(" . join(', ', $compact) . "));\n";
}
$actions .= "\t}\n";
$actions .= "\n";
@ -329,10 +332,10 @@ class ControllerTask extends Shell {
$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->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\t\$this->flash(__('The " . $singularHumanName . " has been saved.', true), array('action'=>'index'));\n";
}
$actions .= "\t\t\t} else {\n";
if ($wannaUseSession) {
@ -362,7 +365,7 @@ class ControllerTask extends Shell {
}
}
if (!empty($compact)) {
$actions .= "\t\t\$this->set(compact(".join(',', $compact)."));\n";
$actions .= "\t\t\$this->set(compact(" . join(',', $compact) . "));\n";
}
$actions .= "\t}\n";
$actions .= "\n";
@ -405,7 +408,7 @@ class ControllerTask extends Shell {
$out .= "class $controllerName" . "Controller extends {$this->plugin}AppController {\n\n";
$out .= "\tvar \$name = '$controllerName';\n";
if (low($actions) == 'scaffold') {
if (strtolower($actions) == 'scaffold') {
$out .= "\tvar \$scaffold;\n";
} else {
if (count($uses)) {
@ -481,7 +484,7 @@ class ControllerTask extends Shell {
$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}?>";
$content = "<?php \n/* SVN FILE: $header$ */\n/* " . $className . "Controller Test cases generated on: " . date('Y-m-d H:i:s') . " : ". time() . "*/\n{$out}?>";
return $this->createFile($path . $filename, $content);
}
/**

View file

@ -240,7 +240,7 @@ class DbConfigTask extends Shell {
$this->hr();
$looksGood = $this->in('Look okay?', array('y', 'n'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
if (strtolower($looksGood) == 'y' || strtolower($looksGood) == 'yes') {
return $config;
}
return false;

View file

@ -112,11 +112,11 @@ class ModelTask extends Shell {
$tableIsGood = $this->in(__('Do you want to use this table?', true), array('y','n'), 'y');
}
if (low($tableIsGood) == 'n' || low($tableIsGood) == 'no') {
if (strtolower($tableIsGood) == 'n' || strtolower($tableIsGood) == 'no') {
$useTable = $this->in(__('What is the name of the table (enter "null" to use NO table)?', true));
}
while ($tableIsGood == false && low($useTable) != 'null') {
while ($tableIsGood == false && strtolower($useTable) != 'null') {
if (is_array($this->__tables) && !in_array($useTable, $this->__tables)) {
$fullTableName = $db->fullTableName($useTable, false);
$this->out($fullTableName . ' does not exist.');
@ -144,12 +144,12 @@ class ModelTask extends Shell {
}
}
if (array_search($useTable, $this->__tables) !== false && (low($wannaDoValidation) == 'y' || low($wannaDoValidation) == 'yes')) {
if (array_search($useTable, $this->__tables) !== false && (strtolower($wannaDoValidation) == 'y' || strtolower($wannaDoValidation) == 'yes')) {
$validate = $this->doValidation($tempModel);
}
$wannaDoAssoc = $this->in(__('Would you like to define model associations (hasMany, hasOne, belongsTo, etc.)?', true), array('y','n'), 'y');
if ((low($wannaDoAssoc) == 'y' || low($wannaDoAssoc) == 'yes')) {
if ((strtolower($wannaDoAssoc) == 'y' || strtolower($wannaDoAssoc) == 'yes')) {
$associations = $this->doAssociations($tempModel);
}
@ -201,7 +201,7 @@ class ModelTask extends Shell {
$this->hr();
$looksGood = $this->in(__('Look okay?', true), array('y','n'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
if (strtolower($looksGood) == 'y' || strtolower($looksGood) == 'yes') {
if ($this->bake($currentModelName, $associations, $validate, $primaryKey, $useTable, $useDbConfig)) {
if ($this->_checkUnitTest()) {
$this->bakeTest($currentModelName, $useTable, $associations);
@ -401,7 +401,7 @@ class ModelTask extends Shell {
$prompt = "{$model->name} {$type} {$associations[$type][$i]['alias']}";
$response = $this->in("{$prompt}?", array('y','n'), 'y');
if ('n' == low($response) || 'no' == low($response)) {
if ('n' == strtolower($response) || 'no' == strtolower($response)) {
unset($associations[$type][$i]);
} else {
if ($model->name === $associations[$type][$i]['alias']) {
@ -414,7 +414,7 @@ class ModelTask extends Shell {
$alternateAlias = $this->in(sprintf(__('This is a self join. Use %s as the alias', true), $alias), array('y', 'n'), 'y');
if ('n' == low($alternateAlias) || 'no' == low($alternateAlias)) {
if ('n' == strtolower($alternateAlias) || 'no' == strtolower($alternateAlias)) {
$associations[$type][$i]['alias'] = $this->in(__('Specify an alternate alias.', true));
} else {
$associations[$type][$i]['alias'] = $alias;
@ -429,7 +429,7 @@ class ModelTask extends Shell {
$wannaDoMoreAssoc = $this->in(__('Would you like to define some additional model associations?', true), array('y','n'), 'n');
while ((low($wannaDoMoreAssoc) == 'y' || low($wannaDoMoreAssoc) == 'yes')) {
while ((strtolower($wannaDoMoreAssoc) == 'y' || strtolower($wannaDoMoreAssoc) == 'yes')) {
$assocs = array(1 => 'belongsTo', 2 => 'hasOne', 3 => 'hasMany', 4 => 'hasAndBelongsToMany');
$bad = true;
while ($bad) {
@ -733,7 +733,7 @@ class ModelTask extends Shell {
$this->out("\nBaking unit test for $className...");
$header = '$Id';
$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $className ." Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
$content = "<?php \n/* SVN FILE: $header$ */\n/* " . $className . " Test cases generated on: " . date('Y-m-d H:i:s') . " : " . time() . "*/\n{$out}?>";
return $this->createFile($path . $filename, $content);
}
return false;
@ -905,7 +905,7 @@ class ModelTask extends Shell {
$col = "\t\t'indexes' => array(";
$props = array();
foreach ((array)$value as $key => $index) {
$props[] = "'{$key}' => array(".join(', ', $schema->__values($index)).")";
$props[] = "'{$key}' => array(" . join(', ', $schema->__values($index)) . ")";
}
$col .= join(', ', $props);
}
@ -925,9 +925,9 @@ class ModelTask extends Shell {
$pluginPath = 'plugins' . DS . Inflector::underscore($this->plugin) . DS;
$path = APP . $pluginPath . 'tests' . DS . 'fixtures' . DS;
}
$filename = Inflector::underscore($model).'_fixture.php';
$filename = Inflector::underscore($model) . '_fixture.php';
$header = '$Id';
$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $model ." Fixture generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
$content = "<?php \n/* SVN FILE: $header$ */\n/* " . $model . " Fixture generated on: " . date('Y-m-d H:i:s') . " : " . time() . "*/\n{$out}?>";
$this->out("\nBaking test fixture for $model...");
if ($this->createFile($path . $filename, $content)) {
return str_replace("\t\t", "\t\t\t", $records);

View file

@ -136,7 +136,7 @@ class PluginTask extends Shell {
$looksGood = $this->in('Look okay?', array('y', 'n', 'q'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
if (strtolower($looksGood) == 'y' || strtolower($looksGood) == 'yes') {
$verbose = $this->in(__('Do you want verbose output?', true), array('y', 'n'), 'n');
$Folder = new Folder($this->path . $pluginPath);
@ -146,7 +146,7 @@ class PluginTask extends Shell {
$Folder->create($this->path . $pluginPath . DS . $directory);
}
if (low($verbose) == 'y' || low($verbose) == 'yes') {
if (strtolower($verbose) == 'y' || strtolower($verbose) == 'yes') {
foreach ($Folder->messages() as $message) {
$this->out($message);
}

View file

@ -144,7 +144,7 @@ class ProjectTask extends Shell {
$looksGood = $this->in('Look okay?', array('y', 'n', 'q'), 'y');
if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
if (strtolower($looksGood) == 'y' || strtolower($looksGood) == 'yes') {
$verbose = $this->in(__('Do you want verbose output?', true), array('y', 'n'), 'n');
$Folder = new Folder($skel);
@ -153,18 +153,18 @@ class ProjectTask extends Shell {
$this->out(sprintf(__("Created: %s in %s", true), $app, $path));
$this->hr();
} else {
$this->err(" '".$app."' could not be created properly");
$this->err(" '" . $app . "' could not be created properly");
return false;
}
if (low($verbose) == 'y' || low($verbose) == 'yes') {
if (strtolower($verbose) == 'y' || strtolower($verbose) == 'yes') {
foreach ($Folder->messages() as $message) {
$this->out($message);
}
}
return true;
} elseif (low($looksGood) == 'q' || low($looksGood) == 'quit') {
} elseif (strtolower($looksGood) == 'q' || strtolower($looksGood) == 'quit') {
$this->out('Bake Aborted.');
} else {
$this->execute(false);
@ -219,7 +219,7 @@ class ProjectTask extends Shell {
$File =& new File($path . 'webroot' . DS . 'index.php');
$contents = $File->read();
if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) {
$result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '".CAKE_CORE_INCLUDE_PATH."');", $contents);
$result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '" . CAKE_CORE_INCLUDE_PATH . "');", $contents);
if (!$File->write($result)) {
return false;
}
@ -230,7 +230,7 @@ class ProjectTask extends Shell {
$File =& new File($path . 'webroot' . DS . 'test.php');
$contents = $File->read();
if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) {
$result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '".CAKE_CORE_INCLUDE_PATH."');", $contents);
$result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '" . CAKE_CORE_INCLUDE_PATH . "');", $contents);
if (!$File->write($result)) {
return false;
}

View file

@ -181,7 +181,7 @@ class TestTask extends Shell {
}
$header = '$Id';
$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $name ." Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
$content = "<?php \n/* SVN FILE: $header$ */\n/* " . $name . " Test cases generated on: " . date('Y-m-d H:i:s') . " : ". time() . "*/\n{$out}?>";
return $this->createFile($this->filePath . Inflector::underscore($name) . '.test.php', $content);
}
/**

View file

@ -161,25 +161,25 @@ class ViewTask extends Shell {
$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');
if (low($interactive) == 'y' || low($interactive) == 'yes') {
if (strtolower($interactive) == 'y' || strtolower($interactive) == 'yes') {
$this->interactive = true;
$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') {
if (strtolower($wannaDoScaffold) == 'y' || strtolower($wannaDoScaffold) == 'yes') {
$wannaDoAdmin = $this->in("Would you like to create the views for admin routing?", array('y','n'), 'y');
}
$admin = false;
if ((low($wannaDoAdmin) == 'y' || low($wannaDoAdmin) == 'yes')) {
if ((strtolower($wannaDoAdmin) == 'y' || strtolower($wannaDoAdmin) == 'yes')) {
$admin = $this->getAdmin();
}
if (low($wannaDoScaffold) == 'y' || low($wannaDoScaffold) == 'yes') {
if (strtolower($wannaDoScaffold) == 'y' || strtolower($wannaDoScaffold) == 'yes') {
$actions = $this->scaffoldActions;
if ($admin) {
foreach ($actions as $action) {
@ -213,7 +213,7 @@ class ViewTask extends Shell {
$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') {
if (strtolower($looksGood) == 'y' || strtolower($looksGood) == 'yes') {
$this->bake($action);
$this->_stop();
} else {

View file

@ -25,7 +25,7 @@
<div class="<?php echo $pluralVar;?> form">
<?php echo "<?php echo \$form->create('{$modelClass}');?>\n";?>
<fieldset>
<legend><?php echo "<?php __('".Inflector::humanize($action)." {$singularHumanName}');?>";?></legend>
<legend><?php echo "<?php __('" . Inflector::humanize($action) . " {$singularHumanName}');?>";?></legend>
<?php
echo "\t<?php\n";
foreach ($fields as $field) {
@ -58,8 +58,8 @@
foreach ($associations as $type => $data) {
foreach ($data as $alias => $details) {
if ($details['controller'] != $this->name && !in_array($details['controller'], $done)) {
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('List " . Inflector::humanize($details['controller']) . "', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New " . Inflector::humanize(Inflector::underscore($alias)) . "', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}

View file

@ -1,5 +1,5 @@
<?php
$output = "<h2>Sweet, \"".Inflector::humanize($app)."\" got Baked by CakePHP!</h2>\n";
$output = "<h2>Sweet, \"" . Inflector::humanize($app) . "\" got Baked by CakePHP!</h2>\n";
$output .="
<?php
if (Configure::read() > 0):

View file

@ -88,8 +88,8 @@ echo "<?php endforeach; ?>\n";
foreach ($associations as $type => $data) {
foreach ($data as $alias => $details) {
if ($details['controller'] != $this->name && !in_array($details['controller'], $done)) {
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('List " . Inflector::humanize($details['controller']) . "', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New " . Inflector::humanize(Inflector::underscore($alias)) . "', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}

View file

@ -32,14 +32,14 @@ foreach ($fields as $field) {
foreach ($associations['belongsTo'] as $alias => $details) {
if ($field === $details['foreignKey']) {
$isKey = true;
echo "\t\t<dt<?php if (\$i % 2 == 0) echo \$class;?>><?php __('".Inflector::humanize(Inflector::underscore($alias))."'); ?></dt>\n";
echo "\t\t<dt<?php if (\$i % 2 == 0) echo \$class;?>><?php __('" . Inflector::humanize(Inflector::underscore($alias)) . "'); ?></dt>\n";
echo "\t\t<dd<?php if (\$i++ % 2 == 0) echo \$class;?>>\n\t\t\t<?php echo \$html->link(\${$singularVar}['{$alias}']['{$details['displayField']}'], array('controller' => '{$details['controller']}', 'action' => 'view', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?>\n\t\t\t&nbsp;\n\t\t</dd>\n";
break;
}
}
}
if ($isKey !== true) {
echo "\t\t<dt<?php if (\$i % 2 == 0) echo \$class;?>><?php __('".Inflector::humanize($field)."'); ?></dt>\n";
echo "\t\t<dt<?php if (\$i % 2 == 0) echo \$class;?>><?php __('" . Inflector::humanize($field) . "'); ?></dt>\n";
echo "\t\t<dd<?php if (\$i++ % 2 == 0) echo \$class;?>>\n\t\t\t<?php echo \${$singularVar}['{$modelClass}']['{$field}']; ?>\n\t\t\t&nbsp;\n\t\t</dd>\n";
}
}
@ -58,8 +58,8 @@ foreach ($fields as $field) {
foreach ($associations as $type => $data) {
foreach ($data as $alias => $details) {
if ($details['controller'] != $this->name && !in_array($details['controller'], $done)) {
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('List " . Inflector::humanize($details['controller']) . "', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New " . Inflector::humanize(Inflector::underscore($alias)) . "', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}
@ -71,12 +71,12 @@ foreach ($fields as $field) {
if (!empty($associations['hasOne'])) :
foreach ($associations['hasOne'] as $alias => $details): ?>
<div class="related">
<h3><?php echo "<?php __('Related ".Inflector::humanize($details['controller'])."');?>";?></h3>
<h3><?php echo "<?php __('Related " . Inflector::humanize($details['controller']) . "');?>";?></h3>
<?php echo "<?php if (!empty(\${$singularVar}['{$alias}'])):?>\n";?>
<dl><?php echo "\t<?php \$i = 0; \$class = ' class=\"altrow\"';?>\n";?>
<?php
foreach ($details['fields'] as $field) {
echo "\t\t<dt<?php if (\$i % 2 == 0) echo \$class;?>><?php __('".Inflector::humanize($field)."');?></dt>\n";
echo "\t\t<dt<?php if (\$i % 2 == 0) echo \$class;?>><?php __('" . Inflector::humanize($field) . "');?></dt>\n";
echo "\t\t<dd<?php if (\$i++ % 2 == 0) echo \$class;?>>\n\t<?php echo \${$singularVar}['{$alias}']['{$field}'];?>\n&nbsp;</dd>\n";
}
?>
@ -84,7 +84,7 @@ if (!empty($associations['hasOne'])) :
<?php echo "<?php endif; ?>\n";?>
<div class="actions">
<ul>
<li><?php echo "<?php echo \$html->link(__('Edit ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'edit', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?></li>\n";?>
<li><?php echo "<?php echo \$html->link(__('Edit " . Inflector::humanize(Inflector::underscore($alias)) . "', true), array('controller' => '{$details['controller']}', 'action' => 'edit', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?></li>\n";?>
</ul>
</div>
</div>
@ -110,7 +110,7 @@ foreach ($relations as $alias => $details):
<tr>
<?php
foreach ($details['fields'] as $field) {
echo "\t\t<th><?php __('".Inflector::humanize($field)."'); ?></th>\n";
echo "\t\t<th><?php __('" . Inflector::humanize($field) . "'); ?></th>\n";
}
?>
<th class="actions"><?php echo "<?php __('Actions');?>";?></th>
@ -143,7 +143,7 @@ echo "\t<?php endforeach; ?>\n";
<?php echo "<?php endif; ?>\n\n";?>
<div class="actions">
<ul>
<li><?php echo "<?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'add'));?>";?> </li>
<li><?php echo "<?php echo \$html->link(__('New " . Inflector::humanize(Inflector::underscore($alias)) . "', true), array('controller' => '{$details['controller']}', 'action' => 'add'));?>";?> </li>
</ul>
</div>
</div>

View file

@ -515,10 +515,10 @@ class Dispatcher extends Object {
parse_str($uri[1], $_GET);
}
$uri = $uri[0];
} elseif (empty($uri) && is_string(env('QUERY_STRING'))) {
} else {
$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);
}
if (empty($uri) || $uri == '/' || $uri == '//') {

View file

@ -168,7 +168,6 @@ class FileEngine extends CacheEngine {
if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
$this->__File->close();
$this->__File->delete();
return false;
}
$data = $this->__File->read(true);

View file

@ -263,6 +263,9 @@ class AuthComponent extends Object {
*/
function startup(&$controller) {
$methods = array_flip($controller->methods);
$action = strtolower($controller->params['action']);
$allowedActions = array_map('strtolower', $this->allowedActions);
$isErrorOrTests = (
strtolower($controller->name) == 'cakeerror' ||
(strtolower($controller->name) == 'tests' && Configure::read() > 0)
@ -273,7 +276,7 @@ class AuthComponent extends Object {
$isMissingAction = (
$controller->scaffold === false &&
!isset($methods[strtolower($controller->params['action'])])
!isset($methods[$action])
);
if ($isMissingAction) {
@ -295,7 +298,7 @@ class AuthComponent extends Object {
$isAllowed = (
$this->allowedActions == array('*') ||
in_array($controller->params['action'], $this->allowedActions)
in_array($action, $allowedActions)
);
if ($loginAction != $url && $isAllowed) {

View file

@ -203,10 +203,10 @@ class CookieComponent extends Object {
if (count($name) > 1) {
$this->__values[$name[0]][$name[1]] = $value;
$this->__write("[".$name[0]."][".$name[1]."]", $value);
$this->__write("[" . $name[0] . "][" . $name[1] . "]", $value);
} else {
$this->__values[$name[0]] = $value;
$this->__write("[".$name[0]."]", $value);
$this->__write("[" . $name[0] . "]", $value);
}
} else {
foreach ($key as $names => $value) {
@ -214,10 +214,10 @@ class CookieComponent extends Object {
if (count($name) > 1) {
$this->__values[$name[0]][$name[1]] = $value;
$this->__write("[".$name[0]."][".$name[1]."]", $value);
$this->__write("[" . $name[0] . "][" . $name[1] . "]", $value);
} else {
$this->__values[$name[0]] = $value;
$this->__write("[".$name[0]."]", $value);
$this->__write("[" . $name[0] . "]", $value);
}
}
}
@ -278,17 +278,17 @@ class CookieComponent extends Object {
$name = $this->__cookieVarNames($key);
if (count($name) > 1) {
if (isset($this->__values[$name[0]])) {
$this->__delete("[".$name[0]."][".$name[1]."]");
$this->__delete("[" . $name[0] . "][" . $name[1] . "]");
unset($this->__values[$name[0]][$name[1]]);
}
} else {
if (isset($this->__values[$name[0]])) {
if (is_array($this->__values[$name[0]])) {
foreach ($this->__values[$name[0]] as $key => $value) {
$this->__delete("[".$name[0]."][".$key."]");
$this->__delete("[" . $name[0] . "][" . $key . "]");
}
}
$this->__delete("[".$name[0]."]");
$this->__delete("[" . $name[0] . "]");
unset($this->__values[$name[0]]);
}
}

View file

@ -346,6 +346,7 @@ class EmailComponent extends Object{
$this->subject = null;
$this->additionalParams = null;
$this->smtpError = null;
$this->attachments = array();
$this->__header = array();
$this->__boundary = null;
$this->__message = array();
@ -490,7 +491,6 @@ class EmailComponent extends Object{
$this->__header[] = 'Content-Type: text/html; charset=' . $this->charset;
} elseif ($this->sendAs === 'both') {
$this->__header[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->__boundary . '"';
$this->__header[] = '';
}
$this->__header[] = 'Content-Transfer-Encoding: 7bit';
@ -503,12 +503,16 @@ class EmailComponent extends Object{
*/
function __formatMessage($message) {
if (!empty($this->attachments)) {
$prefix = array(
'--' . $this->__boundary,
'Content-Type: text/plain; charset=' . $this->charset,
'Content-Transfer-Encoding: 7bit',
''
);
$prefix = array('--' . $this->__boundary);
if ($this->sendAs === 'text') {
$prefix[] = 'Content-Type: text/plain; charset=' . $this->charset;
} 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);
}
return $message;
@ -632,7 +636,9 @@ class EmailComponent extends Object{
* @access private
*/
function __strip($value, $message = false) {
$search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:|charset\=|mime-version\:|multipart/mixed|(?:to|b?cc)\:.*';
$search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:';
$search .= '|charset\=|mime-version\:|multipart/mixed|(?:[^a-z]to|b?cc)\:.*';
if ($message !== true) {
$search .= '|\r|\n';
}
@ -674,8 +680,8 @@ class EmailComponent extends Object{
return false;
}
if (isset($this->smtpOptions['host'])) {
$host = $this->smtpOptions['host'];
if (isset($this->smtpOptions['client'])) {
$host = $this->smtpOptions['client'];
} else {
$host = env('HTTP_HOST');
}

View file

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

View file

@ -323,7 +323,7 @@ class SecurityComponent extends Object {
if (strtolower($options['type']) == 'digest') {
$out[] = 'qop="auth"';
$out[] = 'nonce="' . uniqid() . '"';
$out[] = 'nonce="' . uniqid("") . '"';
$out[] = 'opaque="' . md5($options['realm']).'"';
}

View file

@ -393,7 +393,9 @@ class Controller extends Object {
if ($var === 'components') {
$normal = Set::normalize($this->{$var});
$app = Set::normalize($appVars[$var]);
if ($app !== $normal) {
$this->{$var} = Set::merge($app, $normal);
}
} else {
$this->{$var} = Set::merge($this->{$var}, array_diff($appVars[$var], $this->{$var}));
}
@ -415,7 +417,9 @@ class Controller extends Object {
if ($var === 'components') {
$normal = Set::normalize($this->{$var});
$app = Set::normalize($appVars[$var]);
$this->{$var} = Set::merge($normal, array_diff_assoc($app, $normal));
if ($app !== $normal) {
$this->{$var} = Set::merge($app, $normal);
}
} else {
$this->{$var} = Set::merge($this->{$var}, array_diff($appVars[$var], $this->{$var}));
}
@ -943,17 +947,17 @@ class Controller extends Object {
}
if ($assoc && isset($this->{$object}->{$assoc})) {
$object = $this->{$object}->{$assoc};
$object =& $this->{$object}->{$assoc};
} elseif ($assoc && isset($this->{$this->modelClass}) && isset($this->{$this->modelClass}->{$assoc})) {
$object = $this->{$this->modelClass}->{$assoc};
$object =& $this->{$this->modelClass}->{$assoc};
} elseif (isset($this->{$object})) {
$object = $this->{$object};
$object =& $this->{$object};
} elseif (isset($this->{$this->modelClass}) && isset($this->{$this->modelClass}->{$object})) {
$object = $this->{$this->modelClass}->{$object};
$object =& $this->{$this->modelClass}->{$object};
}
} elseif (empty($object) || $object === null) {
if (isset($this->{$this->modelClass})) {
$object = $this->{$this->modelClass};
$object =& $this->{$this->modelClass};
} else {
$className = null;
$name = $this->uses[0];
@ -961,9 +965,9 @@ class Controller extends Object {
list($name, $className) = explode('.', $this->uses[0]);
}
if ($className) {
$object = $this->{$className};
$object =& $this->{$className};
} else {
$object = $this->{$name};
$object =& $this->{$name};
}
}
}

View file

@ -378,7 +378,7 @@ class Scaffold extends Object {
* @access private
*/
function __scaffold($params) {
$db = &ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
$db =& ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
$admin = Configure::read('Routing.admin');
if (isset($db)) {

View file

@ -366,12 +366,13 @@ class File extends Object {
function md5($maxsize = 5) {
if ($maxsize === true) {
return md5_file($this->path);
} else {
}
$size = $this->size();
if ($size && $size < ($maxsize * 1024) * 1024) {
return md5_file($this->path);
}
}
return false;
}
/**

View file

@ -202,10 +202,10 @@ class HttpSocket extends CakeSocket {
}
if (isset($this->request['auth']['user']) && isset($this->request['auth']['pass'])) {
$this->request['header']['Authorization'] = $this->request['auth']['method'] ." ". base64_encode($this->request['auth']['user'] .":".$this->request['auth']['pass']);
$this->request['header']['Authorization'] = $this->request['auth']['method'] . " " . base64_encode($this->request['auth']['user'] . ":" . $this->request['auth']['pass']);
}
if (isset($this->request['uri']['user']) && isset($this->request['uri']['pass'])) {
$this->request['header']['Authorization'] = $this->request['auth']['method'] ." ". base64_encode($this->request['uri']['user'] .":".$this->request['uri']['pass']);
$this->request['header']['Authorization'] = $this->request['auth']['method'] . " " . base64_encode($this->request['uri']['user'] . ":" . $this->request['uri']['pass']);
}
if (is_array($this->request['body'])) {
@ -220,7 +220,10 @@ class HttpSocket extends CakeSocket {
$this->request['header']['Content-Length'] = strlen($this->request['body']);
}
$connectionType = @$this->request['header']['Connection'];
$connectionType = null;
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'])) {
@ -395,7 +398,11 @@ class HttpSocket extends CakeSocket {
}
$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'];
if (!empty($decoded['header'])) {
@ -805,7 +812,7 @@ class HttpSocket extends CakeSocket {
return false;
}
preg_match_all("/(.+):(.+)(?:(?<![\t ])".$this->lineBreak."|\$)/Uis", $header, $matches, PREG_SET_ORDER);
preg_match_all("/(.+):(.+)(?:(?<![\t ])" . $this->lineBreak . "|\$)/Uis", $header, $matches, PREG_SET_ORDER);
$header = array();
foreach ($matches as $match) {
@ -845,9 +852,16 @@ class HttpSocket extends CakeSocket {
$cookies = array();
foreach ((array)$header['Set-Cookie'] as $cookie) {
$parts = preg_split('/(?<![^;]");[ \t]*/', $cookie);
if (strpos($cookie, '";"') !== false) {
$cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
$parts = str_replace("{__cookie_replace__}", '";"', preg_split('/\;/', $cookie));
} else {
$parts = preg_split('/\;[ \t]*/', $cookie);
}
list($name, $value) = explode('=', array_shift($parts), 2);
$cookies[$name] = compact('value');
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
list($key, $value) = explode('=', $part);

View file

@ -62,7 +62,7 @@ class I18n extends Object {
* Current language used for translations
*
* @var string
* @access private;
* @access private
*/
var $__lang = null;
/**
@ -94,7 +94,9 @@ class I18n extends Object {
* @var array
* @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
*
@ -111,7 +113,7 @@ class I18n extends Object {
}
/**
* 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 $plural Plural string (if any)
@ -121,7 +123,7 @@ class I18n extends Object {
* @return string translated strings.
* @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();
if (strpos($singular, "\r\n") !== false) {

View file

@ -150,8 +150,8 @@ class L10n extends Object {
/* Sami (Lappish) */ 'smi' => 'sz',
/* Serbian */ 'scc' => 'sr',
/* Serbian */ 'srp' => 'sr',
/* Slovack */ 'slo' => 'sk',
/* Slovack */ 'slk' => 'sk',
/* Slovak */ 'slo' => 'sk',
/* Slovak */ 'slk' => 'sk',
/* Slovenian */ 'slv' => 'sl',
/* Sorbian */ 'wen' => 'sb',
/* Spanish (Spain - Traditional) */ 'spa' => 'es',
@ -290,7 +290,7 @@ class L10n extends Object {
'ro-mo' => array('language' => 'Romanian (Moldavia)', 'locale' => 'ro_mo', 'localeFallback' => 'rum', 'charset' => 'utf-8'),
'ru-mo' => array('language' => 'Russian (Moldavia)', 'locale' => 'ru_mo', 'localeFallback' => 'rus', 'charset' => 'utf-8'),
'sb' => array('language' => 'Sorbian', 'locale' => 'wen', 'localeFallback' => 'wen', 'charset' => 'utf-8'),
'sk' => array('language' => 'Slovack', 'locale' => 'slo', 'localeFallback' => 'slo', 'charset' => 'utf-8'),
'sk' => array('language' => 'Slovak', 'locale' => 'slo', 'localeFallback' => 'slo', 'charset' => 'utf-8'),
'sl' => array('language' => 'Slovenian', 'locale' => 'slv', 'localeFallback' => 'slv', 'charset' => 'utf-8'),
'sq' => array('language' => 'Albanian', 'locale' => 'alb', 'localeFallback' => 'alb', 'charset' => 'utf-8'),
'sr' => array('language' => 'Serbian', 'locale' => 'scc', 'localeFallback' => 'scc', 'charset' => 'utf-8'),

View file

@ -313,7 +313,7 @@ class ContainableBehavior extends ModelBehavior {
$option = 'conditions';
$val = $Model->{$name}->alias.'.'.$key;
}
$children[$option] = isset($children[$option]) ? array_merge((array) $children[$option], (array) $val) : $val;
$children[$option] = is_array($val) ? $val : array($val);
$newChildren = null;
if (!empty($name) && !empty($children[$key])) {
$newChildren = $children[$key];

View file

@ -91,28 +91,28 @@ class DataSource extends Object {
* Enter description here...
*
* @var array
* @access private
* @access protected
*/
var $_result = null;
/**
* Queries count.
*
* @var int
* @access private
* @access protected
*/
var $_queriesCnt = 0;
/**
* Total duration of all queries.
*
* @var unknown_type
* @access private
* @access protected
*/
var $_queriesTime = null;
/**
* Log of queries executed by this DataSource
*
* @var unknown_type
* @access private
* @access protected
*/
var $_queriesLog = array();
/**
@ -121,21 +121,21 @@ class DataSource extends Object {
* >6000 queries on one system.
*
* @var int Maximum number of queries in the queries log.
* @access private
* @access protected
*/
var $_queriesLogMax = 200;
/**
* Caches serialzed results of executed queries
*
* @var array Maximum number of queries in the queries log.
* @access private
* @access protected
*/
var $_queryCache = array();
/**
* The default configuration of a specific DataSource
*
* @var array
* @access public
* @access protected
*/
var $_baseConfig = array();
/**

View file

@ -211,9 +211,10 @@ class DboMssql extends DboSource {
return $cache;
}
$fields = false;
$cols = $this->fetchAll("SELECT COLUMN_NAME as Field, DATA_TYPE as Type, COL_LENGTH('" . $this->fullTableName($model, false) . "', COLUMN_NAME) as Length, IS_NULLABLE As [Null], COLUMN_DEFAULT as [Default], COLUMNPROPERTY(OBJECT_ID('" . $this->fullTableName($model, false) . "'), COLUMN_NAME, 'IsIdentity') as [Key], NUMERIC_SCALE as Size FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $this->fullTableName($model, false) . "'", false);
$table = $this->fullTableName($model, false);
$cols = $this->fetchAll("SELECT COLUMN_NAME as Field, DATA_TYPE as Type, COL_LENGTH('" . $table . "', COLUMN_NAME) as Length, IS_NULLABLE As [Null], COLUMN_DEFAULT as [Default], COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key], NUMERIC_SCALE as Size FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'", false);
$fields = false;
foreach ($cols as $column) {
$field = $column[0]['Field'];
$fields[$field] = array(
@ -295,7 +296,8 @@ class DboMssql extends DboSource {
$fields = parent::fields($model, $alias, $fields, false);
$count = count($fields);
if ($count >= 1 && $fields[0] != '*' && strpos($fields[0], 'COUNT(*)') === false) {
if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) {
$result = array();
for ($i = 0; $i < $count; $i++) {
$prepend = '';
@ -306,6 +308,19 @@ class DboMssql extends DboSource {
$fieldAlias = count($this->__fieldMappings);
if (!preg_match('/\s+AS\s+/i', $fields[$i])) {
if (substr($fields[$i], -1) == '*') {
if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
$build = explode('.', $fields[$i]);
$AssociatedModel = $model->{$build[0]};
} else {
$AssociatedModel = $model;
}
$_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
$result = array_merge($result, $_fields);
continue;
}
if (strpos($fields[$i], '.') === false) {
$this->__fieldMappings[$alias . '__' . $fieldAlias] = $alias . '.' . $fields[$i];
$fieldName = $this->name($alias . '.' . $fields[$i]);
@ -321,11 +336,13 @@ class DboMssql extends DboSource {
}
$fields[$i] = "{$fieldName} AS {$fieldAlias}";
}
$fields[$i] = $prepend . $fields[$i];
}
$result[] = $prepend . $fields[$i];
}
return $result;
} else {
return $fields;
}
}
/**
* Generates and executes an SQL INSERT statement for given model, fields, and values.
* Removes Identity (primary key) column from update data before returning to parent, if
@ -373,6 +390,9 @@ class DboMssql extends DboSource {
if (isset($fields[$model->primaryKey])) {
unset($fields[$model->primaryKey]);
}
if (empty($fields)) {
return true;
}
return parent::update($model, array_keys($fields), array_values($fields), $conditions);
}
/**
@ -664,16 +684,10 @@ class DboMssql extends DboSource {
*/
function buildColumn($column) {
$result = preg_replace('/(int|integer)\([0-9]+\)/i', '$1', parent::buildColumn($column));
$null = (
(isset($column['null']) && $column['null'] == true) ||
(array_key_exists('default', $column) && $column['default'] === null) ||
(array_keys($column) == array('type', 'name'))
);
$primaryKey = (isset($column['key']) && $column['key'] == 'primary');
$stringKey = ($primaryKey && $column['type'] != 'integer');
if ($null && !$primaryKey) {
$result .= " NULL";
if (strpos($result, 'DEFAULT NULL') !== false) {
$result = str_replace('DEFAULT NULL', 'NULL', $result);
} else if (array_keys($column) == array('type', 'name')) {
$result .= ' NULL';
}
return $result;
}
@ -723,7 +737,6 @@ class DboMssql extends DboSource {
return $field;
}
}
return null;
}
}

View file

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

View file

@ -105,9 +105,8 @@ class DboMysqli extends DboMysqlBase {
function _execute($sql) {
if (preg_match('/^\s*call/i', $sql)) {
return $this->_executeProcedure($sql);
} else {
return mysqli_query($this->connection, $sql);
}
return mysqli_query($this->connection, $sql);
}
/**
* Executes given SQL statement (procedure call).
@ -140,7 +139,8 @@ class DboMysqli extends DboMysqlBase {
if (!$result) {
return array();
} else {
}
$tables = array();
while ($line = mysqli_fetch_array($result)) {
@ -149,7 +149,6 @@ class DboMysqli extends DboMysqlBase {
parent::listSources($tables);
return $tables;
}
}
/**
* Returns an array of the fields in given table name.
*
@ -201,18 +200,19 @@ class DboMysqli extends DboMysqlBase {
if ($parent != null) {
return $parent;
}
if ($data === null) {
if ($data === null || (is_array($data) && empty($data))) {
return 'NULL';
}
if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
return "''";
}
if (empty($column)) {
$column = $this->introspectType($data);
}
switch ($column) {
case 'boolean':
$data = $this->boolean((bool)$data);
return $this->boolean((bool)$data);
break;
case 'integer' :
case 'float' :
@ -232,20 +232,6 @@ class DboMysqli extends DboMysqlBase {
return $data;
}
/**
* Begin a transaction
*
* @param unknown_type $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions).
*/
function begin(&$model) {
if (parent::begin($model) && $this->execute('START TRANSACTION')) {
$this->_transactionStarted = true;
return true;
}
return false;
}
/**
* Returns a formatted error message from previous database operation.
*
@ -292,7 +278,6 @@ class DboMysqli extends DboMysqlBase {
if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
return $id[0]['insertID'];
}
return null;
}
/**
@ -403,9 +388,8 @@ class DboMysqli extends DboMysqlBase {
$i++;
}
return $resultRow;
} else {
return false;
}
return false;
}
/**
* Gets the database encoding

View file

@ -465,11 +465,12 @@ class DboOracle extends DboSource {
* @access public
*/
function describe(&$model) {
$table = $model->fullTableName($model, false);
if (!empty($model->sequence)) {
$this->_sequenceMap[$model->table] = $model->sequence;
$this->_sequenceMap[$table] = $model->sequence;
} elseif (!empty($model->table)) {
$this->_sequenceMap[$model->table] = $model->table . '_seq';
$this->_sequenceMap[$table] = $model->table . '_seq';
}
$cache = parent::describe($model);
@ -477,12 +478,14 @@ class DboOracle extends DboSource {
if ($cache != null) {
return $cache;
}
$sql = 'SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH FROM all_tab_columns WHERE table_name = \'';
$sql .= strtoupper($this->fullTableName($model)) . '\'';
if (!$this->execute($sql)) {
return false;
}
$fields = array();
for ($i = 0; $row = $this->fetchRow(); $i++) {
@ -952,11 +955,11 @@ class DboOracle extends DboSource {
if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
if (!isset($resultSet) || !is_array($resultSet)) {
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) {
e($this->error);
echo $this->error;
}
e('</div>');
echo '</div>';
}
return null;
}

View file

@ -275,6 +275,9 @@ class DboPostgres extends DboSource {
case 'inet':
case 'float':
case 'integer':
case 'date':
case 'datetime':
case 'timestamp':
if ($data === '') {
return $read ? 'NULL' : 'DEFAULT';
}

View file

@ -200,9 +200,8 @@ class DboSource extends DataSource {
if ($this->error) {
$this->showQuery($sql);
return false;
} else {
return $this->_result;
}
return $this->_result;
}
/**
* DataSource Query abstraction
@ -627,16 +626,22 @@ class DboSource extends DataSource {
$queryData['fields'] = $this->fields($model);
}
foreach ($model->__associations as $type) {
$_associations = $model->__associations;
if ($model->recursive == -1) {
$_associations = array();
} else if ($model->recursive == 0) {
unset($_associations[2], $_associations[3]);
}
foreach ($_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
if ($model->recursive > -1) {
$linkModel =& $model->{$assoc};
$external = isset($assocData['external']);
if ($model->useDbConfig == $linkModel->useDbConfig) {
if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
$linkedModels[] = $type . '/' . $assoc;
}
$linkedModels[$type . '/' . $assoc] = true;
}
}
}
@ -653,12 +658,12 @@ class DboSource extends DataSource {
$filtered = $this->__filterResults($resultSet, $model);
if ($model->recursive > 0) {
foreach ($model->__associations as $type) {
if ($model->recursive > -1) {
foreach ($_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
$linkModel =& $model->{$assoc};
if (!in_array($type . '/' . $assoc, $linkedModels)) {
if (empty($linkedModels[$type . '/' . $assoc])) {
if ($model->useDbConfig == $linkModel->useDbConfig) {
$db =& $this;
} else {
@ -737,11 +742,11 @@ class DboSource extends DataSource {
if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
if (!isset($resultSet) || !is_array($resultSet)) {
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) {
e($this->error);
echo $this->error;
}
e('</div>');
echo '</div>';
}
return null;
}
@ -852,11 +857,8 @@ class DboSource extends DataSource {
foreach ($fetch as $j => $data) {
if (
(isset($data[$with]) && $data[$with][$foreignKey] === $row[$model->alias][$model->primaryKey]) &&
(!in_array($data[$with][$joinKeys[1]], $uniqueIds))
(isset($data[$with]) && $data[$with][$foreignKey] === $row[$model->alias][$model->primaryKey])
) {
$uniqueIds[] = $data[$with][$joinKeys[1]];
if ($habtmFieldsCount <= 2) {
unset($data[$with]);
}
@ -1403,6 +1405,7 @@ class DboSource extends DataSource {
function _prepareUpdateFields(&$model, $fields, $quoteValues = true, $alias = false) {
$quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
$updates = array();
foreach ($fields as $field => $value) {
if ($alias && strpos($field, '.') === false) {
$quoted = $model->escapeField($field);
@ -1512,7 +1515,7 @@ class DboSource extends DataSource {
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 string $func Lowercase name of SQL function, i.e. 'count' or 'max'
@ -1840,9 +1843,9 @@ class DboSource extends DataSource {
if (array_keys($value) === array_values(array_keys($value))) {
$count = count($value);
if ($count === 1) {
$data = $this->name($key) . ' = (';
$data = $this->__quoteFields($key) . ' = (';
} else {
$data = $this->name($key) . ' IN (';
$data = $this->__quoteFields($key) . ' IN (';
}
if ($quoteValues || strpos($value[0], '-!') !== 0) {
if (is_object($model)) {
@ -1905,7 +1908,9 @@ class DboSource extends DataSource {
}
}
$type = (is_object($model) ? $model->getColumnType($key) : null);
$null = ($value === null || (is_array($value) && empty($value)));
if (strtolower($operator) === 'not') {
@ -1914,6 +1919,7 @@ class DboSource extends DataSource {
);
return $data[0];
}
$value = $this->value($value, $type);
if ($key !== '?') {
@ -1954,6 +1960,7 @@ class DboSource extends DataSource {
break;
}
}
return "{$key} {$operator} {$value}";
}
/**
@ -2381,11 +2388,12 @@ class DboSource extends DataSource {
if (!empty($value['unique'])) {
$out .= 'UNIQUE ';
}
$name = $this->startQuote . $name . $this->endQuote;
}
if (is_array($value['column'])) {
$out .= 'KEY '. $name .' (' . join(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
$out .= 'KEY ' . $name . ' (' . join(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
} else {
$out .= 'KEY '. $name .' (' . $this->name($value['column']) . ')';
$out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
}
$join[] = $out;
}

View file

@ -373,6 +373,10 @@ class Model extends Overloadable {
$this->useTable = $table;
}
if ($ds !== null) {
$this->useDbConfig = $ds;
}
if (is_subclass_of($this, 'AppModel')) {
$appVars = get_class_vars('AppModel');
$merge = array('_findMethods');
@ -823,8 +827,11 @@ class Model extends Overloadable {
$type = $this->getColumnType($field);
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');
$timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$format = $db->columns[$type]['format'];
@ -836,27 +843,42 @@ class Model extends Overloadable {
if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
$data['hour'] = '00';
}
if ($type == 'time') {
foreach ($timeFields as $key => $val) {
if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
$data[$val] = '00';
} elseif ($data[$val] === '') {
$data[$val] = '';
} else {
$data[$val] = sprintf('%02d', $data[$val]);
}
if (!empty($data[$val])) {
$date[$key] = $data[$val];
} else {
return null;
}
}
}
if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
foreach ($dateFields as $key => $val) {
if (in_array($val, array('hour', 'min', 'sec'))) {
if (!isset($data[$val]) || $data[$val] === '0' || empty($data[$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 (in_array($type, array('datetime', 'timestamp', 'date')) && !isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
return null;
} elseif (isset($data[$val]) && !empty($data[$val])) {
}
if (isset($data[$val]) && !empty($data[$val])) {
$date[$key] = $data[$val];
}
}
$date = str_replace(array_keys($date), array_values($date), $format);
if ($type == 'time' && $date == '00:00:00') {
return null;
}
if ($useNewDate && (!empty($date))) {
$date = str_replace(array_keys($date), array_values($date), $format);
if ($useNewDate && !empty($date)) {
return $date;
}
}
@ -1321,7 +1343,7 @@ class Model extends Overloadable {
unset($values);
} elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row;
} elseif (isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
} elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row[$join];
}
}
@ -1471,7 +1493,7 @@ class Model extends Overloadable {
if (Set::numeric(array_keys($data))) {
while ($validates) {
foreach ($data as $key => $record) {
if (!$currentValidates = $this->__save($this, $record, $options)) {
if (!$currentValidates = $this->__save($record, $options)) {
$validationErrors[$key] = $this->validationErrors;
}
@ -1524,7 +1546,7 @@ class Model extends Overloadable {
if (isset($associations[$association])) {
switch ($associations[$association]) {
case 'belongsTo':
if ($this->__save($this->{$association}, $values, $options)) {
if ($this->{$association}->__save($values, $options)) {
$data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
} else {
$validationErrors[$association] = $this->{$association}->validationErrors;
@ -1537,7 +1559,7 @@ class Model extends Overloadable {
}
}
}
if (!$this->__save($this, $data, $options)) {
if (!$this->__save($data, $options)) {
$validationErrors[$this->alias] = $this->validationErrors;
$validates = false;
}
@ -1555,7 +1577,7 @@ class Model extends Overloadable {
switch ($type) {
case 'hasOne':
$values[$this->{$type}[$association]['foreignKey']] = $this->id;
if (!$this->__save($this->{$association}, $values, $options)) {
if (!$this->{$association}->__save($values, $options)) {
$validationErrors[$association] = $this->{$association}->validationErrors;
$validates = false;
}
@ -1628,12 +1650,12 @@ class Model extends Overloadable {
* @access private
* @see Model::saveAll()
*/
function __save(&$model, $data, $options) {
function __save($data, $options) {
if ($options['validate'] === 'first' || $options['validate'] === 'only') {
if (!($model->create($data) && $model->validates($options))) {
if (!($this->create($data) && $this->validates($options))) {
return false;
}
} elseif (!($model->create(null) !== null && $model->save($data, $options))) {
} elseif (!($this->create(null) !== null && $this->save($data, $options))) {
return false;
}
return true;
@ -1807,7 +1829,7 @@ class Model extends Overloadable {
);
if (empty($ids)) {
return false;
return true;
}
if ($callbacks) {
@ -2466,8 +2488,8 @@ class Model extends Overloadable {
* rule (in case of multiple validation for field) that was broken.
*
* @param string $field The name of the field to invalidate
* @param mixed $value Name of validation rule that was not failed. If no validation key
* is provided, defaults to true.
* @param mixed $value Name of validation rule that was not failed, or validation message to
* be returned. If no validation key is provided, defaults to true.
* @access public
*/
function invalidate($field, $value = true) {

View file

@ -338,7 +338,7 @@ class CakeSchema extends Object {
$col = "\t\t'indexes' => array(";
$props = array();
foreach ((array)$value as $key => $index) {
$props[] = "'{$key}' => array(".join(', ', $this->__values($index)).")";
$props[] = "'{$key}' => array(" . join(', ', $this->__values($index)) . ")";
}
$col .= join(', ', $props);
}
@ -446,7 +446,7 @@ class CakeSchema extends Object {
if (is_array($values)) {
foreach ($values as $key => $val) {
if (is_array($val)) {
$vals[] = "'{$key}' => array('".join("', '", $val)."')";
$vals[] = "'{$key}' => array('" . join("', '", $val) . "')";
} else if (!is_numeric($key)) {
$val = var_export($val, true);
$vals[] = "'{$key}' => {$val}";

View file

@ -77,9 +77,10 @@ class Object {
/**
* Calls a controller's method from any location.
*
* @param string $url URL in the form of Cake URL ("/controller/method/parameter")
* @param mixed $url String or array-based url.
* @param array $extra if array includes the key "return" it sets the AutoRender to true.
* @return mixed Success (true/false) or contents if 'return' is set in $extra
* @return mixed Boolean true or false on success/failure, or contents
* of rendered action if 'return' is set in $extra.
* @access public
*/
function requestAction($url, $extra = array()) {

View file

@ -460,8 +460,6 @@ class Router extends Object {
if (isset($names[$key])) {
$out[$names[$key]] = $_this->stripEscape($found);
} elseif (isset($names[$key]) && empty($names[$key]) && empty($out[$names[$key]])) {
break;
} else {
$argOptions['context'] = array('action' => $out['action'], 'controller' => $out['controller']);
extract($_this->getArgs($found, $argOptions));
@ -535,10 +533,7 @@ class Router extends Object {
function compile($i) {
$route = $this->routes[$i];
if (!list($pattern, $names) = $this->writeRoute($route[0], $route[1], $route[2])) {
unset($this->routes[$i]);
return array();
}
list($pattern, $names) = $this->writeRoute($route[0], $route[1], $route[2]);
$this->routes[$i] = array(
$route[0], $pattern, $names,
array_merge(array('plugin' => null, 'controller' => null), (array)$route[1]),
@ -1082,7 +1077,7 @@ class Router extends Object {
if (isset($params[$key])) {
$string = $params[$key];
unset($params[$key]);
} else {
} elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
$key = $key . '/';
}
$out = str_replace(':' . $key, $string, $out);
@ -1200,7 +1195,7 @@ class Router extends Object {
$paths = Router::getPaths();
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;
@ -1245,7 +1240,7 @@ class Router extends Object {
* @access public
* @static
*/
function stripPlugin($base, $plugin) {
function stripPlugin($base, $plugin = null) {
if ($plugin != null) {
$base = preg_replace('/(?:' . $plugin . ')/', '', $base);
$base = str_replace('//', '', $base);
@ -1258,7 +1253,6 @@ class Router extends Object {
}
return $base;
}
/**
* Strip escape characters from parameter values.
*
@ -1274,9 +1268,9 @@ class Router extends Object {
return $param;
}
$return = preg_replace('/^(?:[\\t ]*(?:-!)+)/', '', $param);
return $return;
return preg_replace('/^(?:[\\t ]*(?:-!)+)/', '', $param);
}
foreach ($param as $key => $value) {
if (is_string($value)) {
$return[$key] = preg_replace('/^(?:[\\t ]*(?:-!)+)/', '', $value);
@ -1349,7 +1343,9 @@ class Router extends Object {
continue;
}
$param = $_this->stripEscape($param);
if ((!isset($options['named']) || !empty($options['named'])) && strpos($param, $_this->named['separator']) !== false) {
$separatorIsPresent = strpos($param, $_this->named['separator']) !== false;
if ((!isset($options['named']) || !empty($options['named'])) && $separatorIsPresent) {
list($key, $val) = explode($_this->named['separator'], $param, 2);
$hasRule = isset($rules[$key]);
$passIt = (!$hasRule && !$greedy) || ($hasRule && !Router::matchNamed($key, $val, $rules[$key], $context));

View file

@ -918,7 +918,7 @@ class Set extends Object {
* to null (useful for Set::merge). You can optionally group the values by what is obtained when
* following the path specified in $groupPath.
*
* @param array $data Array from where to extract keys and values
* @param mixed $data Array or object from where to extract keys and values
* @param mixed $path1 As an array, or as a dot-separated string.
* @param mixed $path2 As an array, or as a dot-separated string.
* @param string $groupPath As an array, or as a dot-separated string.

View file

@ -120,7 +120,11 @@ class CakeSocket extends Object {
$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)) {
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 {
return false;
}

View file

@ -25,11 +25,11 @@
<h2><?php echo sprintf(__('Missing Method in %s', true), $controller);?></h2>
<p class="error">
<strong><?php __('Error') ?>: </strong>
<?php echo sprintf(__('The action %1$s is not defined in controller %2$s', true), "<em>".$action."</em>", "<em>".$controller."</em>");?>
<?php echo sprintf(__('The action %1$s is not defined in controller %2$s', true), "<em>" . $action . "</em>", "<em>" . $controller . "</em>");?>
</p>
<p class="error">
<strong><?php __('Error') ?>: </strong>
<?php echo sprintf(__('Create %1$s%2$s in file: %3$s.', true), "<em>".$controller."::</em>", "<em>".$action."()</em>", APP_DIR.DS."controllers".DS.Inflector::underscore($controller).".php");?>
<?php echo sprintf(__('Create %1$s%2$s in file: %3$s.', true), "<em>" . $controller . "::</em>", "<em>" . $action . "()</em>", APP_DIR . DS . "controllers" . DS . Inflector::underscore($controller) . ".php");?>
</p>
<pre>
&lt;?php
@ -47,5 +47,5 @@ class <?php echo $controller;?> extends AppController {
</pre>
<p class="notice">
<strong><?php __('Notice') ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s.', true), APP_DIR.DS."views".DS."errors".DS."missing_action.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s.', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_action.ctp");?>
</p>

View file

@ -25,11 +25,11 @@
<h2><?php __('Missing Component Class'); ?></h2>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Component class %1$s in %2$s was not found.', true), "<em>". $component ."Component</em>", "<em>". $controller ."Controller</em>");?>
<?php echo sprintf(__('Component class %1$s in %2$s was not found.', true), "<em>" . $component . "Component</em>", "<em>" . $controller . "Controller</em>");?>
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Create the class %s in file: %s', true), "<em>". $component ."Component</em>", APP_DIR.DS."controllers".DS."components".DS.$file);?>
<?php echo sprintf(__('Create the class %s in file: %s', true), "<em>" . $component . "Component</em>", APP_DIR . DS . "controllers" . DS . "components" . DS . $file);?>
</p>
<pre>
&lt;?php
@ -40,5 +40,5 @@ class <?php echo $component;?>Component extends Object {<br />
</pre>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_component_class.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_component_class.ctp");?>
</p>

View file

@ -29,7 +29,7 @@
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Create the class %s in file: %s', true), "<em>". $component ."Component</em>", APP_DIR.DS."controllers".DS."components".DS.$file);?>
<?php echo sprintf(__('Create the class %s in file: %s', true), "<em>" . $component . "Component</em>", APP_DIR . DS . "controllers" . DS . "components" . DS . $file);?>
</p>
<pre>
&lt;?php
@ -40,5 +40,5 @@ class <?php echo $component;?>Component extends Object {<br />
</pre>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_component_file.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_component_file.ctp");?>
</p>

View file

@ -25,11 +25,11 @@
<h2><?php __('Missing Controller'); ?></h2>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('%s could not be found.', true), "<em>".$controller."</em>");?>
<?php echo sprintf(__('%s could not be found.', true), "<em>" . $controller . "</em>");?>
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Create the class %s below in file: %s', true), "<em>".$controller."</em>", APP_DIR.DS."controllers".DS.Inflector::underscore($controller).".php");?>
<?php echo sprintf(__('Create the class %s below in file: %s', true), "<em>" . $controller . "</em>", APP_DIR . DS . "controllers" . DS . Inflector::underscore($controller) . ".php");?>
</p>
<pre>
&lt;?php
@ -41,5 +41,5 @@ class <?php echo $controller;?> extends AppController {
</pre>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_controller.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_controller.ctp");?>
</p>

View file

@ -29,7 +29,7 @@
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Create the class below in file: %s', true), APP_DIR.DS."views".DS."helpers".DS.$file);?>
<?php echo sprintf(__('Create the class below in file: %s', true), APP_DIR . DS . "views" . DS . "helpers" . DS . $file);?>
</p>
<pre>
&lt;?php
@ -40,5 +40,5 @@ class <?php echo $helperClass;?> extends AppHelper {
</pre>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_helper_class.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_helper_class.ctp");?>
</p>

View file

@ -25,11 +25,11 @@
<h2><?php __('Missing Helper File'); ?></h2>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__("The helper file %s can not be found or does not exist.", true), APP_DIR.DS."views".DS."helpers".DS.$file);?>
<?php echo sprintf(__("The helper file %s can not be found or does not exist.", true), APP_DIR . DS . "views" . DS . "helpers" . DS . $file);?>
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Create the class below in file: %s', true), APP_DIR.DS."views".DS."helpers".DS.$file);?>
<?php echo sprintf(__('Create the class below in file: %s', true), APP_DIR . DS . "views" . DS . "helpers" . DS . $file);?>
</p>
<pre>
&lt;?php
@ -40,5 +40,5 @@ class <?php echo $helperClass;?> extends AppHelper {
</pre>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_helper_file.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_helper_file.ctp");?>
</p>

View file

@ -25,13 +25,13 @@
<h2><?php __('Missing Layout'); ?></h2>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__("The layout file %s can not be found or does not exist.", true), "<em>". $file ."</em>");?>
<?php echo sprintf(__("The layout file %s can not be found or does not exist.", true), "<em>" . $file . "</em>");?>
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Confirm you have created the file: %s', true), "<em>". $file ."</em>");?>
<?php echo sprintf(__('Confirm you have created the file: %s', true), "<em>" . $file . "</em>");?>
</p>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_layout.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_layout.ctp");?>
</p>

View file

@ -29,7 +29,7 @@
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Create the class %s in file: %s', true), "<em>". $model . "</em>", APP_DIR.DS."models".DS.Inflector::underscore($model).".php");?>
<?php echo sprintf(__('Create the class %s in file: %s', true), "<em>" . $model . "</em>", APP_DIR . DS . "models" . DS . Inflector::underscore($model) . ".php");?>
</p>
<pre>
&lt;?php
@ -42,5 +42,5 @@ class <?php echo $model;?> extends AppModel {
</pre>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_model.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_model.ctp");?>
</p>

View file

@ -29,9 +29,9 @@
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Confirm you have created the file: %s', true), APP_DIR.DS."config".DS."database.php");?>
<?php echo sprintf(__('Confirm you have created the file: %s', true), APP_DIR . DS . "config" . DS . "database.php");?>
</p>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_scaffolddb.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_scaffolddb.ctp");?>
</p>

View file

@ -25,9 +25,9 @@
<h2><?php __('Missing Database Table'); ?></h2>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('Database table %1$s for model %2$s was not found.', true),"<em>". $table ."</em>", "<em>". $model ."</em>");?>
<?php echo sprintf(__('Database table %1$s for model %2$s was not found.', true),"<em>" . $table . "</em>", "<em>" . $model . "</em>");?>
</p>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_table.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_table.ctp");?>
</p>

View file

@ -25,7 +25,7 @@
<h2><?php __('Missing View'); ?></h2>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__('The view for %1$s%2$s was not found.', true), "<em>". $controller."Controller::</em>", "<em>". $action ."()</em>");?>
<?php echo sprintf(__('The view for %1$s%2$s was not found.', true), "<em>" . $controller . "Controller::</em>", "<em>". $action . "()</em>");?>
</p>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
@ -33,5 +33,5 @@
</p>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."missing_view.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "missing_view.ctp");?>
</p>

View file

@ -25,9 +25,9 @@
<h2><?php echo sprintf(__('Private Method in %s', true), $controller);?></h2>
<p class="error">
<strong><?php __('Error'); ?>: </strong>
<?php echo sprintf(__("%s%s cannot be accessed directly.", true), "<em>". $controller ."::</em>", "<em>". $action ."()</em>");?>
<?php echo sprintf(__("%s%s cannot be accessed directly.", true), "<em>" . $controller . "::</em>", "<em>" . $action . "()</em>");?>
</p>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."private_action.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "private_action.ctp");?>
</p>

View file

@ -29,7 +29,7 @@
</p>
<p class="notice">
<strong><?php __('Notice'); ?>: </strong>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR.DS."views".DS."errors".DS."scaffold_error.ctp");?>
<?php echo sprintf(__('If you want to customize this error message, create %s', true), APP_DIR . DS . "views" . DS . "errors" . DS . "scaffold_error.ctp");?>
</p>
<pre>
&lt;?php

View file

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

View file

@ -264,7 +264,8 @@ class CacheHelper extends AppHelper {
$controller->params = $this->params = unserialize(stripslashes(\'' . addslashes(serialize($this->params)) . '\'));
$controller->action = $this->action = unserialize(\'' . serialize($this->action) . '\');
$controller->data = $this->data = unserialize(stripslashes(\'' . addslashes(serialize($this->data)) . '\'));
$controller->themeWeb = $this->themeWeb = \'' . $this->themeWeb . '\';';
$controller->themeWeb = $this->themeWeb = \'' . $this->themeWeb . '\';
Router::setRequestInfo(array($this->params, array(\'base\' => $this->base, \'webroot\' => $this->webroot)));';
if ($useCallbacks == true) {
$file .= '
@ -275,7 +276,6 @@ class CacheHelper extends AppHelper {
}
$file .= '
Router::setRequestInfo(array($this->params, array(\'base\' => $this->base, \'webroot\' => $this->webroot)));
$loadedHelpers = array();
$loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers);
foreach (array_keys($loadedHelpers) as $helper) {

View file

@ -437,10 +437,11 @@ class HtmlHelper extends AppHelper {
} elseif ($path[0] === '/') {
$path = $this->webroot($path);
} 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);
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'])) {

View file

@ -60,10 +60,10 @@ class JavascriptHelper extends AppHelper {
* @access public
*/
var $tags = array(
'javascriptblock' => '<script type="text/javascript">%s</script>',
'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
@ -173,70 +173,53 @@ class JavascriptHelper extends AppHelper {
$options = array();
}
$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) {
$this->_cachedEvents[] = $script;
} else {
$block = ($script !== null);
$safe = ($options['safe'] || $this->safe);
if ($safe && !($this->_cacheAll && $options['allowCache'])) {
$script = "\n" . '//<![CDATA[' . "\n" . $script;
if ($block) {
$script .= "\n" . '//]]>' . "\n";
}
}
if ($script === null) {
if (empty($script)) {
$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 ($this->_cacheEvents && $this->_cacheAll && $options['allowCache']) {
$this->_cachedEvents[] = $script;
return null;
}
if ($options['safe'] || $this->safe) {
$script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
}
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));
}
}
}
/**
* Ends a block of cached JavaScript code
*
* @return mixed
*/
function blockEnd() {
if (!isset($this->inBlock) || !$this->inBlock) {
return;
}
$script = @ob_get_contents();
@ob_end_clean();
ob_start();
echo $this->__scriptBuffer;
$this->__scriptBuffer = null;
$options = $this->_blockOptions;
$safe = ((isset($options['safe']) && $options['safe']) || $this->safe);
$this->_blockOptions = array();
$this->inBlock = false;
if (isset($options['inline']) && !$options['inline']) {
$view =& ClassRegistry::getObject('view');
$view->addScript(sprintf($this->tags['javascriptblock'], $script));
}
if (!empty($script) && $this->_cacheAll && $options['allowCache']) {
$this->_cachedEvents[] = $script;
if (empty($script)) {
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 "/",
@ -319,8 +302,104 @@ class JavascriptHelper extends AppHelper {
* @return string Escaped string.
*/
function escapeString($string) {
$escape = array('\n' => '\\\n', "\r\n" => '\n', "\r" => '\n', "\n" => '\n', '"' => '\"', "'" => "\\'");
return str_replace(array_keys($escape), array_values($escape), $string);
App::import('Core', 'Multibyte');
$escape = array("\r\n" => "\n", "\r" => "\n");
$string = str_replace(array_keys($escape), array_values($escape), $string);
return $this->_utf8ToHex($string);
}
/**
* Encode a string into JSON. Converts and escapes necessary characters.
*
* @return void
**/
function _utf8ToHex($string) {
$length = strlen($string);
$return = '';
for ($i = 0; $i < $length; ++$i) {
$ord = ord($string{$i});
switch (true) {
case $ord == 0x08:
$return .= '\b';
break;
case $ord == 0x09:
$return .= '\t';
break;
case $ord == 0x0A:
$return .= '\n';
break;
case $ord == 0x0C:
$return .= '\f';
break;
case $ord == 0x0D:
$return .= '\r';
break;
case $ord == 0x22:
case $ord == 0x2F:
case $ord == 0x5C:
case $ord == 0x27:
$return .= '\\' . $string{$i};
break;
case (($ord >= 0x20) && ($ord <= 0x7F)):
$return .= $string{$i};
break;
case (($ord & 0xE0) == 0xC0):
if ($i + 1 >= $length) {
$i += 1;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 1;
break;
case (($ord & 0xF0) == 0xE0):
if ($i + 2 >= $length) {
$i += 2;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1} . $string{$i + 2};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 2;
break;
case (($ord & 0xF8) == 0xF0):
if ($i + 3 >= $length) {
$i += 3;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 3;
break;
case (($ord & 0xFC) == 0xF8):
if ($i + 4 >= $length) {
$i += 4;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 4;
break;
case (($ord & 0xFE) == 0xFC):
if ($i + 5 >= $length) {
$i += 5;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 5;
break;
}
}
return $return;
}
/**
* Attach an event to an element. Used with the Prototype library.
@ -493,6 +572,15 @@ class JavascriptHelper extends AppHelper {
* Generates a JavaScript object in JavaScript Object Notation (JSON)
* from an array
*
* ### Options
*
* - block - Wraps the return value in a script tag if true. Default is false
* - prefix - Prepends the string to the returned data. Default is ''
* - postfix - Appends the string to the returned data. Default is ''
* - stringKeys - A list of array keys to be treated as a string.
* - quoteKeys - If false treats $stringKeys as a list of keys **not** to be quoted. Default is true.
* - q - The type of quote to use. Default is "'"
*
* @param array $data Data to be converted
* @param array $options Set of options: block, prefix, postfix, stringKeys, quoteKeys, q
* @param string $prefix DEPRECATED, use $options['prefix'] instead. Prepends the string to the returned data

View file

@ -67,10 +67,10 @@ class PaginatorHelper extends AppHelper {
*/
var $options = array();
/**
* Gets the current page of the in the recordset for the given model
* Gets the current paging parameters from the resultset for the given model
*
* @param string $model Optional model name. Uses the default if none is specified.
* @return string The current page number of the paginated resultset.
* @return array The array of paging parameters for the paginated resultset.
*/
function params($model = null) {
if (empty($model)) {
@ -140,8 +140,10 @@ class PaginatorHelper extends AppHelper {
if (isset($options['sort']) && !empty($options['sort'])) {
if (preg_match('/(?:\w+\.)?(\w+)/', $options['sort'], $result) && isset($result[1])) {
if ($result[0] == $this->defaultModel()) {
return $result[1];
}
}
return $options['sort'];
} elseif (isset($options['order']) && is_array($options['order'])) {
return key($options['order']);
@ -149,6 +151,7 @@ class PaginatorHelper extends AppHelper {
if (preg_match('/(?:\w+\.)?(\w+)/', $options['order'], $result) && isset($result[1])) {
return $result[1];
}
return $options['order'];
}
return null;
}
@ -223,17 +226,12 @@ class PaginatorHelper extends AppHelper {
}
$dir = 'asc';
$sortKey = $this->sortKey($options['model']);
$defaultModel = $this->defaultModel();
if (strpos($sortKey, $defaultModel) !== false && strpos($key, $defaultModel) === false) {
$isSorted = ($sortKey === $defaultModel . '.' . $key);
} else {
$isSorted = ($sortKey === $key);
}
$isSorted = ($sortKey === $key || $sortKey === $this->defaultModel() . '.' . $key);
if ($isSorted && $this->sortDir($options['model']) === 'asc') {
$dir = 'desc';
}
if (is_array($title) && array_key_exists($dir, $title)) {
$title = $title[$dir];
}
@ -493,11 +491,12 @@ class PaginatorHelper extends AppHelper {
$end = $params['page'] + ($modulus - $params['page']) + 1;
}
if ($first && $start > (int)$first) {
if ($start == $first + 1) {
$out .= $this->first($first, array('tag' => $tag, 'after' => $separator));
if ($first && $start > 1) {
$offset = ($start <= (int)$first) ? $start - 1 : $first;
if ($offset < $start - 1) {
$out .= $this->first($offset, array('tag' => $tag, 'separator' => $separator));
} else {
$out .= $this->first($first, array('tag' => $tag));
$out .= $this->first($offset, array('tag' => $tag, 'after' => $separator, 'separator' => $separator));
}
}
@ -523,11 +522,12 @@ class PaginatorHelper extends AppHelper {
$out .= $after;
if ($last && $end <= $params['pageCount'] - (int)$last) {
if ($end + 1 == $params['pageCount']) {
$out .= $this->last($last, array('tag' => $tag, 'before' => $separator));
if ($last && $end < $params['pageCount']) {
$offset = ($params['pageCount'] < $end + (int)$last) ? $params['pageCount'] - $end : $last;
if ($offset <= $last && $params['pageCount'] - $end > $offset) {
$out .= $this->last($offset, array('tag' => $tag, 'separator' => $separator));
} else {
$out .= $this->last($last, array('tag' => $tag));
$out .= $this->last($offset, array('tag' => $tag, 'before' => $separator, 'separator' => $separator));
}
}

View file

@ -142,10 +142,10 @@ class SessionHelper extends CakeSession {
$out = $flash['message'];
} else {
$view =& ClassRegistry::getObject('view');
list($tmpLayout, $tmpVars, $tmpTitle) = array($view->layout, $view->viewVars, $view->pageTitle);
list($view->layout, $view->viewVars, $view->pageTitle) = array($flash['layout'], $flash['params'], '');
$out = $view->renderLayout($flash['message']);
list($view->layout, $view->viewVars, $view->pageTitle) = array($tmpLayout, $tmpVars, $tmpTitle);
list($tmpVars, $tmpTitle) = array($view->viewVars, $view->pageTitle);
list($view->viewVars, $view->pageTitle) = array($flash['params'], '');
$out = $view->renderLayout($flash['message'], $flash['layout']);
list($view->viewVars, $view->pageTitle) = array($tmpVars, $tmpTitle);
}
echo($out);
parent::del('Message.' . $key);

View file

@ -277,17 +277,20 @@ class TextHelper extends AppHelper {
}
$pos = strpos(strtolower($text), strtolower($phrase));
$startPos = 0;
if ($pos > $radius) {
$startPos = $pos - $radius;
}
$textLen = strlen($text);
$endPos = $pos + $phraseLen + $radius;
if ($endPos >= $textLen) {
$endPos = $textLen;
}
$excerpt = substr($text, $startPos, $endPos - $startPos);
$excerpt = substr($text, $startPos, $endPos - $startPos);
if ($startPos != 0) {
$excerpt = substr_replace($excerpt, $ending, 0, $phraseLen);
}

View file

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

View file

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

View file

@ -25,7 +25,7 @@
<div class="<?php echo $pluralVar;?> form">
<?php
echo $form->create();
echo $form->inputs(null, array('created', 'modified', 'updated'));
echo $form->inputs($scaffoldFields, array('created', 'modified', 'updated'));
echo $form->end(__('Submit', true));
?>
</div>
@ -40,8 +40,8 @@
foreach ($associations as $_type => $_data) {
foreach ($_data as $_alias => $_details) {
if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) {
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' =>'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' =>'add'))."</li>\n";
echo "\t\t<li>" . $html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' =>'index')) . "</li>\n";
echo "\t\t<li>" . $html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' =>'add')) . "</li>\n";
$done[] = $_details['controller'];
}
}

View file

@ -86,8 +86,8 @@ echo "\n";
foreach ($associations as $_type => $_data) {
foreach ($_data as $_alias => $_details) {
if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) {
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' => 'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' => 'add'))."</li>\n";
echo "\t\t<li>" . $html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' => 'index')) . "</li>\n";
echo "\t\t<li>" . $html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' => 'add')) . "</li>\n";
$done[] = $_details['controller'];
}
}

View file

@ -37,14 +37,14 @@ foreach ($scaffoldFields as $_field) {
foreach ($associations['belongsTo'] as $_alias => $_details) {
if ($_field === $_details['foreignKey']) {
$isKey = true;
echo "\t\t<dt{$class}>".Inflector::humanize($_alias)."</dt>\n";
echo "\t\t<dt{$class}>" . Inflector::humanize($_alias) . "</dt>\n";
echo "\t\t<dd{$class}>\n\t\t\t" . $html->link(${$singularVar}[$_alias][$_details['displayField']], array('controller' => $_details['controller'], 'action' => 'view', ${$singularVar}[$_alias][$_details['primaryKey']])) . "\n\t\t&nbsp;</dd>\n";
break;
}
}
}
if ($isKey !== true) {
echo "\t\t<dt{$class}>".Inflector::humanize($_field)."</dt>\n";
echo "\t\t<dt{$class}>" . Inflector::humanize($_field) . "</dt>\n";
echo "\t\t<dd{$class}>\n\t\t\t{${$singularVar}[$modelClass][$_field]}\n&nbsp;\t\t</dd>\n";
}
}
@ -63,8 +63,8 @@ foreach ($scaffoldFields as $_field) {
foreach ($associations as $_type => $_data) {
foreach ($_data as $_alias => $_details) {
if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) {
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' => 'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' => 'add'))."</li>\n";
echo "\t\t<li>" . $html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' => 'index')) . "</li>\n";
echo "\t\t<li>" . $html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' => 'add')) . "</li>\n";
$done[] = $_details['controller'];
}
}
@ -87,8 +87,8 @@ foreach ($associations['hasOne'] as $_alias => $_details): ?>
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
echo "\t\t<dt{$class}>".Inflector::humanize($_field)."</dt>\n";
echo "\t\t<dd{$class}>\n\t" .${$singularVar}[$_alias][$_field] ."\n&nbsp;</dd>\n";
echo "\t\t<dt{$class}>" . Inflector::humanize($_field) . "</dt>\n";
echo "\t\t<dd{$class}>\n\t" . ${$singularVar}[$_alias][$_field] . "\n&nbsp;</dd>\n";
}
?>
</dl>
@ -122,7 +122,7 @@ $otherSingularVar = Inflector::variable($_alias);
<?php
$otherFields = array_keys(${$singularVar}[$_alias][0]);
foreach ($otherFields as $_field) {
echo "\t\t<th>".Inflector::humanize($_field)."</th>\n";
echo "\t\t<th>" . Inflector::humanize($_field) . "</th>\n";
}
?>
<th class="actions">Actions</th>
@ -137,7 +137,7 @@ $otherSingularVar = Inflector::variable($_alias);
echo "\t\t<tr{$class}>\n";
foreach ($otherFields as $_field) {
echo "\t\t\t<td>".${$otherSingularVar}[$_field]."</td>\n";
echo "\t\t\t<td>" . ${$otherSingularVar}[$_field] . "</td>\n";
}
echo "\t\t\t<td class=\"actions\">\n";

View file

@ -417,6 +417,10 @@ class View extends Object {
*/
function renderLayout($content_for_layout, $layout = null) {
$layoutFileName = $this->_getLayoutFileName($layout);
if (empty($layoutFileName)) {
return $this->output;
}
$debug = '';
if (isset($this->viewVars['cakeDebug']) && Configure::read() > 2) {
@ -800,7 +804,7 @@ class View extends Object {
}
}
$paths = $this->_paths($this->plugin);
$paths = $this->_paths(Inflector::underscore($this->plugin));
foreach ($paths as $path) {
if (file_exists($path . $name . $this->ext)) {
@ -840,7 +844,7 @@ class View extends Object {
if (!is_null($this->layoutPath)) {
$subDir = $this->layoutPath . DS;
}
$paths = $this->_paths($this->plugin);
$paths = $this->_paths(Inflector::underscore($this->plugin));
$file = 'layouts' . DS . $subDir . $name;
$exts = array($this->ext, '.ctp', '.thtml');
@ -892,7 +896,7 @@ class View extends Object {
$paths = array();
$viewPaths = Configure::read('viewPaths');
if ($plugin !== null) {
if (!empty($plugin)) {
$count = count($viewPaths);
for ($i = 0; $i < $count; $i++) {
$paths[] = $viewPaths[$i] . 'plugins' . DS . $plugin . DS;

View file

@ -201,6 +201,7 @@ class XmlNode extends Object {
}
$tagOpts = $this->__tagOptions($name);
if ($tagOpts === false) {
return;
}
@ -221,7 +222,6 @@ class XmlNode extends Object {
$attributes = array();
$children = array();
$chldObjs = array();
$document =& $this->document();
if (is_object($object)) {
$chldObjs = get_object_vars($object);
@ -239,7 +239,12 @@ class XmlNode extends Object {
$node->createTextNode($chldObjs[$tagOpts['value']]);
unset($chldObjs[$tagOpts['value']]);
}
$n = $name;
if (!empty($chldObjs['_name_'])) {
$n = null;
unset($chldObjs['_name_']);
}
$c = 0;
foreach ($chldObjs as $key => $val) {
@ -247,14 +252,11 @@ class XmlNode extends Object {
$attributes[$key] = $val;
} else {
if (!isset($tagOpts['children']) || $tagOpts['children'] === array() || (is_array($tagOpts['children']) && in_array($key, $tagOpts['children']))) {
if (!is_numeric($key)) {
$n = $key;
if (is_numeric($n)) {
$n = $name;
}
if (is_array($val)) {
foreach ($val as $i => $obj2) {
$n2 = $i;
foreach ($val as $n2 => $obj2) {
if (is_numeric($n2)) {
$n2 = $n;
}
@ -262,6 +264,7 @@ class XmlNode extends Object {
}
} else {
if (is_object($val)) {
$node->normalize($val, $n, $options);
} elseif ($options['format'] == 'tags' && $this->__tagOptions($key) !== false) {
$tmp =& $node->createElement($key);
@ -607,6 +610,9 @@ class XmlNode extends Object {
if (is_array($this->attributes) && count($this->attributes) > 0) {
foreach ($this->attributes as $key => $val) {
if (is_bool($val) && $val === false) {
$val = 0;
}
$d .= ' ' . $key . '="' . htmlspecialchars($val, ENT_QUOTES, Configure::read('App.encoding')) . '"';
}
}
@ -627,7 +633,6 @@ class XmlNode extends Object {
if ($options['whitespace']) {
$d .= "\n";
}
$count = count($this->children);
$cDepth = $depth + 1;
for ($i = 0; $i < $count; $i++) {
@ -682,6 +687,19 @@ class XmlNode extends Object {
$out[$child->name] = $value;
}
continue;
} elseif (count($child->children) === 0 && $child->value == '') {
$value = $child->attributes;
if (isset($out[$child->name]) || isset($multi[$key])) {
if (!isset($multi[$key])) {
$multi[$key] = array($out[$child->name]);
unset($out[$child->name]);
}
$multi[$key][] = $value;
} else {
$out[$key] = $value;
}
continue;
} else {
$value = $child->toArray($camelize);
}

View file

@ -54,6 +54,36 @@ class BasicsTest extends CakeTestCase {
Configure::write('localePaths', $this->_localePaths);
Configure::write('Config.language', $this->_language);
}
/**
* test the array_diff_key compatibility function.
*
* @return void
**/
function testArrayDiffKey() {
$one = array('one' => 1, 'two' => 2, 'three' => 3);
$two = array('one' => 'one', 'two' => 'two');
$result = array_diff_key($one, $two);
$expected = array('three' => 3);
$this->assertEqual($result, $expected);
$one = array('one' => array('value', 'value-two'), 'two' => 2, 'three' => 3);
$two = array('two' => 'two');
$result = array_diff_key($one, $two);
$expected = array('one' => array('value', 'value-two'), 'three' => 3);
$this->assertEqual($result, $expected);
$one = array('one' => null, 'two' => 2, 'three' => '', 'four' => 0);
$two = array('two' => 'two');
$result = array_diff_key($one, $two);
$expected = array('one' => null, 'three' => '', 'four' => 0);
$this->assertEqual($result, $expected);
$one = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true);
$two = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true);
$result = array_diff_key($one, $two);
$this->assertEqual($result, array());
}
/**
* testHttpBase method
*
@ -94,12 +124,29 @@ class BasicsTest extends CakeTestCase {
$_SERVER = $_ENV = array();
$this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = 'on';
$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';
$this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = false;
$this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = '';
$this->assertFalse(env('HTTPS'));
$_SERVER = array();
$_ENV['SCRIPT_URI'] = 'https://domain.test/a/test.php';
@ -388,16 +435,16 @@ class BasicsTest extends CakeTestCase {
function test__c() {
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)';
$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)';
$this->assertEqual($result, $expected);
ob_start();
__c('Plural Rule 1 (from core)', 5);
__c('Plural Rule 1 (from core)', 6);
$result = ob_get_clean();
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
@ -411,24 +458,24 @@ class BasicsTest extends CakeTestCase {
function test__dc() {
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)';
$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)';
$this->assertEqual($result, $expected);
$result = __dc('core', 'Plural Rule 1', 5, true);
$result = __dc('core', 'Plural Rule 1', 6, true);
$expected = 'Plural Rule 1';
$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)';
$this->assertEqual($result, $expected);
ob_start();
__dc('default', 'Plural Rule 1 (from core)', 5);
__dc('default', 'Plural Rule 1 (from core)', 6);
$result = ob_get_clean();
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
@ -442,20 +489,20 @@ class BasicsTest extends CakeTestCase {
function test__dcn() {
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)';
$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)';
$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';
$this->assertEqual($result, $expected);
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();
$expected = '%d = 1 (from core translated)';
$this->assertEqual($result, $expected);

View file

@ -396,6 +396,25 @@ class ShellDispatcherTest extends UnitTestCase {
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-working',
'D:\www',
'bake',
'my_app',
);
$expected = array(
'working' => 'D:\www',
'app' => 'www',
'root' => 'D:',
'webroot' => 'webroot'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
}
/**
* testBuildPaths method

View file

@ -86,7 +86,7 @@ class AclShellTest extends CakeTestCase {
function startTest() {
$this->Dispatcher =& new TestAclShellMockShellDispatcher();
$this->Task =& new MockAclShell($this->Dispatcher);
$this->Task->Dispatch = new $this->Dispatcher;
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->params['datasource'] = 'test_suite';
}

View file

@ -0,0 +1,116 @@
<?php
/* SVN FILE: $Id$ */
/**
* ApiShellTest file
*
* 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
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @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('ApiShell')) {
require CAKE . 'console' . DS . 'libs' . DS . 'api.php';
}
Mock::generatePartial(
'ShellDispatcher', 'ApiShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ApiShell', 'MockApiShell',
array('in', 'out', 'createFile', 'hr', '_stop')
);
/**
* ApiShellTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ApiShellTest extends CakeTestCase {
/**
* setUp method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new ApiShellMockShellDispatcher();
$this->Shell =& new MockApiShell($this->Dispatcher);
$this->Shell->Dispatch =& $this->Dispatcher;
}
/**
* tearDown method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* Test that method names are detected properly including those with no arguments.
*
* @access public
* @return void
*/
function testMethodNameDetection () {
$this->Shell->setReturnValueAt(0, 'in', 'q');
$this->Shell->expectAt(0, 'out', array('Controller'));
$expected = array(
array(
'1. afterFilter()',
'2. beforeFilter()',
'3. beforeRender()',
'4. constructClasses()',
'5. disableCache()',
'6. flash($message, $url, $pause = 1)',
'7. header($status)',
'8. isAuthorized()',
'9. loadModel($modelClass = null, $id = null)',
'10. paginate($object = null, $scope = array(), $whitelist = array())',
'11. postConditions($data = array(), $op = null, $bool = \'AND\', $exclusive = false)',
'12. redirect($url, $status = null, $exit = true)',
'13. referer($default = null, $local = false)',
'14. render($action = null, $layout = null, $file = null)',
'15. set($one, $two = null)',
'16. setAction($action)',
'17. validate()',
'18. validateErrors()'
)
);
$this->Shell->expectAt(1, 'out', $expected);
$this->Shell->args = array('controller');
$this->Shell->paths['controller'] = CAKE_CORE_INCLUDE_PATH . DS . LIBS . 'controller' . DS;
$this->Shell->main();
}
}
?>

View file

@ -37,10 +37,9 @@ if (!class_exists('ShellDispatcher')) {
ob_end_clean();
}
Mock::generatePartial(
'ShellDispatcher', 'TestShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial('ShellDispatcher', 'TestShellMockShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
/**
* TestShell class
*
@ -48,6 +47,13 @@ Mock::generatePartial(
* @subpackage cake.tests.cases.console.libs
*/
class TestShell extends Shell {
/**
* Fixtures used in this test case
*
* @var name
* @access public
*/
var $name = 'TestShell';
}
/**
* TestAppleTask class

View file

@ -65,7 +65,7 @@ class TestTaskTest extends CakeTestCase {
function setUp() {
$this->Dispatcher =& new TestTestTaskMockShellDispatcher();
$this->Task =& new MockTestTask($this->Dispatcher);
$this->Task->Dispatch = new $this->Dispatcher;
$this->Task->Dispatch =& $this->Dispatcher;
}
/**
* tearDown method

View file

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

View file

@ -60,9 +60,9 @@ class CakeTestFixtureTestFixture extends CakeTestFixture {
* @var array
*/
var $records = array(
array('name' => 'Gandalf'),
array('name' => 'Captain Picard'),
array('name' => 'Chewbacca')
array('name' => 'Gandalf', 'created' => '2009-04-28 19:20:00'),
array('name' => 'Captain Picard', 'created' => '2009-04-28 19:20:00'),
array('name' => 'Chewbacca', 'created' => '2009-04-28 19:20:00')
);
}
/**

View file

@ -436,6 +436,21 @@ class ComponentTest extends CakeTestCase {
$this->assertEqual($Controller->Orange->settings, $expected);
$this->assertEqual($Controller->ParamTest->test, 'value');
}
/**
* Ensure that settings are not duplicated when passed into component initialize.
*
* @return void
**/
function testComponentParamsNoDuplication() {
$Controller =& new ComponentTestController();
$Controller->components = array('Orange' => array('setting' => array('itemx')));
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$expected = array('setting' => array('itemx'), 'colour' => 'blood orange');
$this->assertEqual($Controller->Orange->settings, $expected, 'Params duplication has occured %s');
}
/**
* Test mutually referencing components.
*

View file

@ -728,7 +728,36 @@ class AuthTest extends CakeTestCase {
$this->Controller->params['action'] = 'Add';
$this->assertFalse($this->Controller->Auth->startup($this->Controller));
}
/**
* test that allow() and allowedActions work with camelCase method names.
*
* @return void
**/
function testAllowedActionsWithCamelCaseMethods() {
$url = '/auth_test/camelCase';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->allow('*');
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertTrue($result, 'startup() should return true, as action is allowed. %s');
$url = '/auth_test/camelCase';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->allowedActions = array('delete', 'camelCase', 'add');
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertTrue($result, 'startup() should return true, as action is allowed. %s');
$this->Controller->Auth->allowedActions = array('delete', 'add');
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertFalse($result, 'startup() should return false, as action is not allowed. %s');
}
/**
* testLoginRedirect method
*

View file

@ -104,6 +104,15 @@ class EmailTestComponent extends EmailComponent {
function getMessage() {
return $this->__message;
}
/**
* Convenience method for testing.
*
* @access public
* @return string
*/
function strip($content, $message = false) {
return parent::__strip($content, $message);
}
}
/**
* EmailTestController class
@ -328,7 +337,8 @@ MSGBLOC;
// TODO: better test for format of message sent?
$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->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
}
@ -403,10 +413,11 @@ HTMLBLOC;
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
$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/html; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 7bit' . "\n\n" . $html . "\n\n";
$expect = '<pre>' . $expect . '--alt---' . "\n\n" . '</pre>';
$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));
@ -499,9 +510,21 @@ TEXTBLOC;
$content = "Previous content\n--alt-\nContent-TypeContent-Type:: text/html; charsetcharset==utf-8\nContent-Transfer-Encoding: 7bit";
$content .= "\n\n<p>My own html content</p>";
$result = $this->Controller->EmailTest->__strip($content, true);
$result = $this->Controller->EmailTest->strip($content, true);
$expected = "Previous content\n--alt-\n text/html; utf-8\n 7bit\n\n<p>My own html content</p>";
$this->assertEqual($result, $expected);
$content = '<p>Some HTML content with an <a href="mailto:test@example.com">email link</a>';
$result = $this->Controller->EmailTest->strip($content, true);
$expected = $content;
$this->assertEqual($result, $expected);
$content = '<p>Some HTML content with an ';
$content .= '<a href="mailto:test@example.com,test2@example.com">email link</a>';
$result = $this->Controller->EmailTest->strip($content, true);
$expected = $content;
$this->assertEqual($result, $expected);
}
/**
* testMultibyte method
@ -535,6 +558,66 @@ TEXTBLOC;
preg_match('/Subject: (.*)Header:/s', $this->Controller->Session->read('Message.email.message'), $matches);
$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
*
@ -553,6 +636,7 @@ TEXTBLOC;
$this->Controller->EmailTest->additionalParams = 'X-additional-header';
$this->Controller->EmailTest->delivery = 'smtp';
$this->Controller->EmailTest->smtpOptions['host'] = 'blah';
$this->Controller->EmailTest->attachments = array('attachment1', 'attachment2');
$this->assertFalse($this->Controller->EmailTest->send('Should not work'));
@ -571,6 +655,7 @@ TEXTBLOC;
$this->assertNull($this->Controller->EmailTest->getBoundary());
$this->assertIdentical($this->Controller->EmailTest->getMessage(), array());
$this->assertNull($this->Controller->EmailTest->smtpError);
$this->assertIdentical($this->Controller->EmailTest->attachments, array());
}
/**
* osFix method

View file

@ -35,6 +35,13 @@ Mock::generatePartial('RequestHandlerComponent', 'NoStopRequestHandler', array('
* @subpackage cake.tests.cases.libs.controller.components
*/
class RequestHandlerTestController extends Controller {
/**
* name property
*
* @var string
* @access public
**/
var $name = 'RequestHandlerTest';
/**
* uses property
*
@ -124,21 +131,32 @@ class RequestHandlerComponentTest extends CakeTestCase {
*/
var $RequestHandler;
/**
* setUp method
* startTest method
*
* @access public
* @return void
*/
function setUp() {
function startTest() {
$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
* @return void
*/
function tearDown() {
function endTest() {
unset($this->RequestHandler);
unset($this->Controller);
if (!headers_sent()) {
@ -241,6 +259,24 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->RequestHandler->renderAs($this->Controller, 'xml');
$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
*
@ -502,16 +538,5 @@ class RequestHandlerComponentTest extends CakeTestCase {
Configure::write('viewPaths', $_paths);
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

@ -363,6 +363,14 @@ class SecurityComponentTest extends CakeTestCase {
* @return void
*/
function testDigestAuth() {
$skip = $this->skipIf((version_compare(PHP_VERSION, '5.1') == -1) XOR (!function_exists('apache_request_headers')),
"%s Cannot run Digest Auth test for PHP versions < 5.1"
);
if ($skip) {
return;
}
$this->Controller->action = 'posted';
$_SERVER['PHP_AUTH_DIGEST'] = $digest = <<<DIGEST
Digest username="Mufasa",

View file

@ -0,0 +1,222 @@
<?php
/* SVN FILE: $Id$ */
/**
* Controller Merge vars Test file
*
* Isolated from the Controller and Component test as to not pollute their AppController class
*
* 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.controller
* @since CakePHP(tm) v 1.2.3
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('AppController')) {
/**
* Test case AppController requred
*
* @package cake.tests.cases.libs.controller
**/
class AppController extends Controller {
/**
* components
*
* @var array
**/
var $components = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false));
/**
* helpers
*
* @var array
**/
var $helpers = array('MergeVar' => array('format' => 'html', 'terse'));
}
} elseif (!defined('APP_CONTROLLER_EXISTS')) {
define('APP_CONTROLLER_EXISTS', true);
}
/**
* MergeVar Component
*
* @package cake.tests.cases.libs.controller
**/
class MergeVarComponent extends Object {
}
/**
* Additional controller for testing
*
* @package cake.tests.cases.libs.controller
**/
class MergeVariablesController extends AppController {
/**
* name
*
* @var string
**/
var $name = 'MergeVariables';
/**
* uses
*
* @var arrays
**/
var $uses = array();
}
/**
* MergeVarPlugin App Controller
*
* @package cake.tests.cases.libs.controller
**/
class MergeVarPluginAppController extends AppController {
/**
* components
*
* @var array
**/
var $components = array('Auth' => array('setting' => 'val', 'otherVal'));
/**
* helpers
*
* @var array
**/
var $helpers = array('Javascript');
}
/**
* MergePostsController
*
* @package cake.tests.cases.libs.controller
**/
class MergePostsController extends MergeVarPluginAppController {
/**
* name
*
* @var string
**/
var $name = 'MergePosts';
/**
* uses
*
* @var array
**/
var $uses = array();
}
/**
* Test Case for Controller Merging of Vars.
*
* @package cake.tests.cases.libs.controller
**/
class ControllerMergeVarsTestCase extends CakeTestCase {
/**
* end test
*
* @return void
**/
function endTest() {
ClassRegistry::flush();
}
/**
* test that component settings are not duplicated when merging component settings
*
* @return void
**/
function testComponentParamMergingNoDuplication() {
$Controller =& new MergeVariablesController();
$Controller->constructClasses();
$expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false));
$this->assertEqual($Controller->components, $expected, 'Duplication of settings occured. %s');
}
/**
* test component merges with redeclared components
*
* @return void
**/
function testComponentMergingWithRedeclarations() {
$Controller =& new MergeVariablesController();
$Controller->components['MergeVar'] = array('remote', 'redirect' => true);
$Controller->constructClasses();
$expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => true, 'remote'));
$this->assertEqual($Controller->components, $expected, 'Merging of settings is wrong. %s');
}
/**
* test merging of helpers array, ensure no duplication occurs
*
* @return void
**/
function testHelperSettingMergingNoDuplication() {
$Controller =& new MergeVariablesController();
$Controller->constructClasses();
$expected = array('MergeVar' => array('format' => 'html', 'terse'));
$this->assertEqual($Controller->helpers, $expected, 'Duplication of settings occured. %s');
}
/**
* test merging of vars with plugin
*
* @return void
**/
function testMergeVarsWithPlugin() {
$Controller =& new MergePostsController();
$Controller->components = array('Email' => array('ports' => 'open'));
$Controller->plugin = 'MergeVarPlugin';
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('flag', 'otherFlag', 'redirect' => false),
'Auth' => array('setting' => 'val', 'otherVal'),
'Email' => array('ports' => 'open')
);
$this->assertEqual($Controller->components, $expected, 'Components are unexpected %s');
$expected = array(
'Javascript',
'MergeVar' => array('format' => 'html', 'terse')
);
$this->assertEqual($Controller->helpers, $expected, 'Helpers are unexpected %s');
$Controller =& new MergePostsController();
$Controller->components = array();
$Controller->plugin = 'MergeVarPlugin';
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('flag', 'otherFlag', 'redirect' => false),
'Auth' => array('setting' => 'val', 'otherVal'),
);
$this->assertEqual($Controller->components, $expected, 'Components are unexpected %s');
}
/**
* Ensure that __mergeVars is not being greedy and merging with
* AppController when you make an instance of Controller
*
* @return void
**/
function testMergeVarsNotGreedy() {
$Controller =& new Controller();
$Controller->components = array();
$Controller->uses = array();
$Controller->constructClasses();
$this->assertTrue(isset($Controller->Session));
}
}

View file

@ -47,6 +47,37 @@ class ScaffoldMockController extends Controller {
*/
var $scaffold;
}
/**
* ScaffoldMockControllerWithFields class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldMockControllerWithFields extends Controller {
/**
* name property
*
* @var string 'ScaffoldMock'
* @access public
*/
var $name = 'ScaffoldMock';
/**
* scaffold property
*
* @var mixed
* @access public
*/
var $scaffold;
/**
* function _beforeScaffold
*
* @param string method
*/
function _beforeScaffold($method) {
$this->set('scaffoldFields', array('title'));
return true;
}
}
/**
* TestScaffoldMock class
*
@ -197,21 +228,21 @@ class ScaffoldViewTest extends CakeTestCase {
*/
var $fixtures = array('core.article', 'core.user', 'core.comment');
/**
* setUp method
* startTest method
*
* @access public
* @return void
*/
function setUp() {
function startTest() {
$this->Controller =& new ScaffoldMockController();
}
/**
* tearDown method
* endTest method
*
* @access public
* @return void
*/
function tearDown() {
function endTest() {
unset($this->Controller);
}
/**
@ -421,7 +452,6 @@ class ScaffoldViewTest extends CakeTestCase {
$this->assertPattern('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result);
$this->assertPattern('/<li><a href="\/scaffold_mock\/delete\/1"[^>]*>Delete<\/a>\s*<\/li>/', $result);
}
/**
* Test Admin Index Scaffolding.
*
@ -531,21 +561,21 @@ class ScaffoldTest extends CakeTestCase {
*/
var $fixtures = array('core.article', 'core.user', 'core.comment');
/**
* setUp method
* startTest method
*
* @access public
* @return void
*/
function setUp() {
function startTest() {
$this->Controller =& new ScaffoldMockController();
}
/**
* tearDown method
* endTest method
*
* @access public
* @return void
*/
function tearDown() {
function endTest() {
unset($this->Controller);
}
/**
@ -580,7 +610,6 @@ class ScaffoldTest extends CakeTestCase {
$result = $Scaffold->getParams();
$this->assertEqual($result['action'], 'admin_edit');
}
/**
* test that the proper names and variable values are set by Scaffold
*
@ -608,7 +637,7 @@ class ScaffoldTest extends CakeTestCase {
$this->Controller->base = '/';
$this->Controller->constructClasses();
$Scaffold =& new TestScaffoldMock($this->Controller, $params);
$result = $this->Controller->viewVars;
$result = $Scaffold->controller->viewVars;
$this->assertEqual($result['singularHumanName'], 'Scaffold Mock');
$this->assertEqual($result['pluralHumanName'], 'Scaffold Mock');
@ -619,5 +648,37 @@ class ScaffoldTest extends CakeTestCase {
$this->assertEqual($result['pluralVar'], 'scaffoldMock');
$this->assertEqual($result['scaffoldFields'], array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated'));
}
/**
* test that the proper names and variable values are set by Scaffold
*
* @return void
**/
function testEditScaffoldWithScaffoldFields() {
$this->Controller = new ScaffoldMockControllerWithFields();
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertNoPattern('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result);
}
}
?>

View file

@ -399,12 +399,12 @@ class HttpSocketTest extends CakeTestCase {
$this->Socket->setReturnValue('read', false);
$this->Socket->_mock->_call_counts['read'] = 0;
$number = mt_rand(0, 9999999);
$serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>Hello, your lucky number is ".$number."</h1>";
$serverResponse = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>Hello, your lucky number is " . $number . "</h1>";
$this->Socket->setReturnValueAt(0, 'read', $serverResponse);
$this->Socket->expect('write', array("GET / HTTP/1.1\r\nHost: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n\r\n"));
$this->Socket->expectCallCount('read', 2);
$response = $this->Socket->request($request);
$this->assertIdentical($response, "<h1>Hello, your lucky number is ".$number."</h1>");
$this->assertIdentical($response, "<h1>Hello, your lucky number is " . $number . "</h1>");
$this->Socket->reset();
$serverResponse = "HTTP/1.x 200 OK\r\nSet-Cookie: foo=bar\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>This is a cookie test!</h1>";

View file

@ -39,8 +39,15 @@ class I18nTest extends CakeTestCase {
* @return void
*/
function setUp() {
$this->_objects = Configure::read('__objects');
Configure::write('__objects', array());
$this->_localePaths = Configure::read('localePaths');
Configure::write('localePaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'locale'));
$this->_pluginPaths = Configure::read('pluginPaths');
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins'));
}
/**
* tearDown method
@ -50,6 +57,9 @@ class I18nTest extends CakeTestCase {
*/
function tearDown() {
Configure::write('localePaths', $this->_localePaths);
Configure::write('pluginPaths', $this->_pluginPaths);
Configure::write('__objects', $this->_objects);
}
/**
* testDefaultStrings method
@ -2353,9 +2363,6 @@ class I18nTest extends CakeTestCase {
* @return void
*/
function testPluginTranslation() {
$pluginPaths = Configure::read('pluginPaths');
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins'));
Configure::write('Config.language', 'po');
$singular = $this->__domainSingular();
$this->assertEqual('Plural Rule 1 (from plugin)', $singular);
@ -2387,8 +2394,6 @@ class I18nTest extends CakeTestCase {
$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('25 = 0 or > 1 (from plugin)', $plurals));
Configure::write('pluginPaths', $pluginPaths);
}
/**
* testPoMultipleLineTranslation method
@ -2484,6 +2489,12 @@ class I18nTest extends CakeTestCase {
$expected = 'this is a "quoted string" (translated)';
$this->assertEqual(__('this is a "quoted string"', true), $expected);
}
/**
* testFloatValue method
*
* @access public
* @return void
*/
function testFloatValue() {
Configure::write('Config.language', 'rule_9_po');
@ -2499,6 +2510,70 @@ class I18nTest extends CakeTestCase {
$expected = "%d everything else (translated)";
$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
*
@ -2522,6 +2597,16 @@ class I18nTest extends CakeTestCase {
}
return $plurals;
}
/**
* category method
*
* @access private
* @return void
*/
function __category($category = LC_MONETARY) {
$singular = __c('Plural Rule 1', $category, true);
return $singular;
}
/**
* Singular method
*

View file

@ -848,7 +848,7 @@ class L10nTest extends CakeTestCase {
$result = $l10n->catalog(array('sk'));
$expected = array(
'sk' => array('language' => 'Slovack', 'locale' => 'slo', 'localeFallback' => 'slo', 'charset' => 'utf-8')
'sk' => array('language' => 'Slovak', 'locale' => 'slo', 'localeFallback' => 'slo', 'charset' => 'utf-8')
);
$this->assertEqual($result, $expected);

View file

@ -257,7 +257,7 @@ class TestBehavior extends ModelBehavior {
}
echo "onError trigger success";
}
/**
/**
* beforeTest method
*
* @param mixed $model
@ -265,8 +265,8 @@ class TestBehavior extends ModelBehavior {
* @return void
*/
function beforeTest(&$model) {
$model->beforeTestResult[] = get_class($this);
return get_class($this);
$model->beforeTestResult[] = strtolower(get_class($this));
return strtolower(get_class($this));
}
/**
* testMethod method
@ -337,6 +337,58 @@ class Test2Behavior 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
*
@ -350,7 +402,10 @@ class BehaviorTest extends CakeTestCase {
* @var array
* @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
*
@ -928,26 +983,73 @@ class BehaviorTest extends CakeTestCase {
* @return void
*/
function testBehaviorTrigger() {
$Apple = new Apple();
$Apple =& new Apple();
$Apple->Behaviors->attach('Test');
$Apple->Behaviors->attach('Test2');
$Apple->Behaviors->attach('Test3');
$Apple->beforeTestResult = array();
$Apple->Behaviors->trigger($Apple, 'beforeTest');
$expected = array('TestBehavior', 'Test2Behavior', 'Test3Behavior');
$expected = array('testbehavior', 'test2behavior', 'test3behavior');
$this->assertIdentical($Apple->beforeTestResult, $expected);
$Apple->beforeTestResult = array();
$Apple->Behaviors->trigger($Apple, 'beforeTest', array(), array('break' => true, 'breakOn' => 'Test2Behavior'));
$expected = array('TestBehavior', 'Test2Behavior');
$Apple->Behaviors->trigger($Apple, 'beforeTest', array(), array('break' => true, 'breakOn' => 'test2behavior'));
$expected = array('testbehavior', 'test2behavior');
$this->assertIdentical($Apple->beforeTestResult, $expected);
$Apple->beforeTestResult = array();
$Apple->Behaviors->trigger($Apple, 'beforeTest', array(), array('break' => true, 'breakOn' => array('Test2Behavior', 'Test3Behavior')));
$expected = array('TestBehavior', 'Test2Behavior');
$Apple->Behaviors->trigger($Apple, 'beforeTest', array(), array('break' => true, 'breakOn' => array('test2behavior', 'test3behavior')));
$expected = array('testbehavior', 'test2behavior');
$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
*

View file

@ -1982,9 +1982,14 @@ class ContainableBehaviorTest extends CakeTestCase {
);
$this->assertEqual($result, $expected);
$orders = array(
'title DESC', 'title DESC, published DESC',
array('title' => 'DESC'), array('title' => 'DESC', 'published' => 'DESC'),
);
foreach ($orders as $order) {
$result = $this->User->find('all', array('contain' => array(
'ArticleFeatured' => array(
'title', 'order' => 'title DESC',
'title', 'order' => $order,
'Featured' => array(
'category_id',
'Category' => 'name'
@ -2047,6 +2052,7 @@ class ContainableBehaviorTest extends CakeTestCase {
);
$this->assertEqual($result, $expected);
}
}
/**
* testFindThirdLevelNonReset method
*
@ -3225,7 +3231,6 @@ class ContainableBehaviorTest extends CakeTestCase {
$options = array(
'conditions' => array(
'Comment.comment !=' => 'Crazy',
'Comment.published' => 'Y',
),
'contain' => 'User',
@ -3236,7 +3241,6 @@ class ContainableBehaviorTest extends CakeTestCase {
$dummyResult = $this->Article->Comment->find('all', array(
'conditions' => array(
'Comment.comment !=' => 'Silly',
'User.user' => 'mariano'
),
'fields' => array('User.password'),
@ -3320,7 +3324,6 @@ class ContainableBehaviorTest extends CakeTestCase {
$initialOptions = array(
'conditions' => array(
'Comment.comment' => '!= Crazy',
'Comment.published' => 'Y',
),
'contain' => 'User',
@ -3331,7 +3334,6 @@ class ContainableBehaviorTest extends CakeTestCase {
$findOptions = array(
'conditions' => array(
'Comment.comment !=' => 'Silly',
'User.user' => 'mariano',
),
'fields' => array('User.password'),
@ -3409,7 +3411,8 @@ class ContainableBehaviorTest extends CakeTestCase {
'joinTable' => 'articles_tags',
'foreignKey' => 'article_id',
'associationForeignKey' => 'tag_id',
'conditions' => 'LENGTH(ShortTag.tag) <= 3'
// LENGHT function mysql-only, using LIKE does almost the same
'conditions' => 'ShortTag.tag LIKE "???"'
)
)
);

View file

@ -427,6 +427,8 @@ class TranslateBehaviorTest extends CakeTestCase {
$expected = array(1 => 'Titel #1', 2 => 'Titel #2', 3 => 'Titel #3');
$this->assertEqual($result, $expected);
// MSSQL trigger an error and stops the page even if the debug = 0
if ($this->db->config['driver'] != 'mssql') {
$debug = Configure::read('debug');
Configure::write('debug', 0);
@ -436,6 +438,7 @@ class TranslateBehaviorTest extends CakeTestCase {
$result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'after'));
$this->assertEqual($result, array());
Configure::write('debug', $debug);
}
$result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'before'));
$expected = array(1 => null, 2 => null, 3 => null);

View file

@ -43,6 +43,13 @@ class DboMssqlTestDb extends DboMssql {
* @access public
*/
var $simulated = array();
/**
* simalate property
*
* @var array
* @access public
*/
var $simulate = true;
/**
* fetchAllResultsStack
*
@ -58,8 +65,12 @@ class DboMssqlTestDb extends DboMssql {
* @return void
*/
function _execute($sql) {
if ($this->simulate) {
$this->simulated[] = $sql;
return null;
} else {
return parent::_execute($sql);
}
}
/**
* fetchAll method
@ -104,6 +115,15 @@ class DboMssqlTestDb extends DboMssql {
function getPrimaryKey($model) {
return parent::_getPrimaryKey($model);
}
/**
* clearFieldMappings method
*
* @access public
* @return void
*/
function clearFieldMappings() {
$this->__fieldMappings = array();
}
}
/**
* MssqlTestModel class
@ -152,6 +172,17 @@ class MssqlTestModel extends Model {
'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array(
'MssqlClientTestModel' => array(
'foreignKey' => 'client_id'
)
);
/**
* find method
*
@ -189,6 +220,41 @@ class MssqlTestModel extends Model {
$this->_schema = $schema;
}
}
/**
* MssqlClientTestModel class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class MssqlClientTestModel extends Model {
/**
* name property
*
* @var string 'MssqlAssociatedTestModel'
* @access public
*/
var $name = 'MssqlClientTestModel';
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* _schema property
*
* @var array
* @access protected
*/
var $_schema = array(
'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'created' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
}
/**
* DboMssqlTest class
*
@ -203,6 +269,20 @@ class DboMssqlTest extends CakeTestCase {
* @access public
*/
var $db = null;
/**
* autoFixtures property
*
* @var bool false
* @access public
*/
var $autoFixtures = false;
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array('core.category');
/**
* Skip if cannot connect to mssql
*
@ -212,6 +292,26 @@ class DboMssqlTest extends CakeTestCase {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'mssql', '%s SQL Server connection not available');
}
/**
* Make sure all fixtures tables are being created
*
* @access public
*/
function start() {
$this->db->simulate = false;
parent::start();
$this->db->simulate = true;
}
/**
* Make sure all fixtures tables are being dropped
*
* @access public
*/
function end() {
$this->db->simulate = false;
parent::end();
$this->db->simulate = true;
}
/**
* Sets up a Dbo class instance for testing
*
@ -238,8 +338,22 @@ class DboMssqlTest extends CakeTestCase {
* @return void
*/
function testQuoting() {
$result = $this->db->fields($this->model);
$expected = array(
$expected = "1.2";
$result = $this->db->value(1.2, 'float');
$this->assertIdentical($expected, $result);
$expected = "'1,2'";
$result = $this->db->value('1,2', 'float');
$this->assertIdentical($expected, $result);
}
/**
* testFields method
*
* @access public
* @return void
*/
function testFields() {
$fields = array(
'[MssqlTestModel].[id] AS [MssqlTestModel__0]',
'[MssqlTestModel].[client_id] AS [MssqlTestModel__1]',
'[MssqlTestModel].[name] AS [MssqlTestModel__2]',
@ -259,15 +373,32 @@ class DboMssqlTest extends CakeTestCase {
'[MssqlTestModel].[created] AS [MssqlTestModel__16]',
'CONVERT(VARCHAR(20), [MssqlTestModel].[updated], 20) AS [MssqlTestModel__17]'
);
$result = $this->db->fields($this->model);
$expected = $fields;
$this->assertEqual($result, $expected);
$expected = "1.2";
$result = $this->db->value(1.2, 'float');
$this->assertIdentical($expected, $result);
$this->db->clearFieldMappings();
$result = $this->db->fields($this->model, null, 'MssqlTestModel.*');
$expected = $fields;
$this->assertEqual($result, $expected);
$expected = "'1,2'";
$result = $this->db->value('1,2', 'float');
$this->assertIdentical($expected, $result);
$this->db->clearFieldMappings();
$result = $this->db->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name'));
$expected = array_merge($fields, array(
'[AnotherModel].[id] AS [AnotherModel__18]',
'[AnotherModel].[name] AS [AnotherModel__19]'));
$this->assertEqual($result, $expected);
$this->db->clearFieldMappings();
$result = $this->db->fields($this->model, null, array('*', 'MssqlClientTestModel.*'));
$expected = array_merge($fields, array(
'[MssqlClientTestModel].[id] AS [MssqlClientTestModel__18]',
'[MssqlClientTestModel].[name] AS [MssqlClientTestModel__19]',
'[MssqlClientTestModel].[email] AS [MssqlClientTestModel__20]',
'CONVERT(VARCHAR(20), [MssqlClientTestModel].[created], 20) AS [MssqlClientTestModel__21]',
'CONVERT(VARCHAR(20), [MssqlClientTestModel].[updated], 20) AS [MssqlClientTestModel__22]'));
$this->assertEqual($result, $expected);
}
/**
* testDistinctFields method
@ -330,6 +461,64 @@ class DboMssqlTest extends CakeTestCase {
);
$this->assertEqual($result, $expected);
}
/**
* testBuildColumn
*
* @return unknown_type
* @access public
*/
function testBuildColumn() {
$column = array('name' => 'id', 'type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary');
$result = $this->db->buildColumn($column);
$expected = '[id] int IDENTITY (1, 1) NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'client_id', 'type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11');
$result = $this->db->buildColumn($column);
$expected = '[client_id] int DEFAULT 0 NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'client_id', 'type' => 'integer', 'null' => true);
$result = $this->db->buildColumn($column);
$expected = '[client_id] int NULL';
$this->assertEqual($result, $expected);
// 'name' => 'type' format for columns
$column = array('type' => 'integer', 'name' => 'client_id');
$result = $this->db->buildColumn($column);
$expected = '[client_id] int NULL';
$this->assertEqual($result, $expected);
$column = array('type' => 'string', 'name' => 'name');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => '', 'default' => '', 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) DEFAULT \'\' NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => false, 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => false, 'default' => null, 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => true, 'default' => null, 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => true, 'default' => '', 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) DEFAULT \'\'';
$this->assertEqual($result, $expected);
}
/**
* testUpdateAllSyntax method
*
@ -353,6 +542,7 @@ class DboMssqlTest extends CakeTestCase {
* @access public
*/
function testGetPrimaryKey() {
// When param is a model
$result = $this->db->getPrimaryKey($this->model);
$this->assertEqual($result, 'id');
@ -361,6 +551,12 @@ class DboMssqlTest extends CakeTestCase {
$this->model->setSchema($schema);
$result = $this->db->getPrimaryKey($this->model);
$this->assertNull($result);
// When param is a table name
$this->db->simulate = false;
$this->loadFixtures('Category');
$result = $this->db->getPrimaryKey('categories');
$this->assertEqual($result, 'id');
}
/**
* testInsertMulti

View file

@ -297,5 +297,21 @@ class DboMysqliTest extends CakeTestCase {
$expected = 'float';
$this->assertEqual($result, $expected);
}
/**
* undocumented function
*
* @return void
* @access public
*/
function testTransactions() {
$this->db->begin($this->model);
$this->assertTrue($this->db->_transactionStarted);
$beginSqlCalls = Set::extract('/.[query=START TRANSACTION]', $this->db->_queriesLog);
$this->assertEqual(1, count($beginSqlCalls));
$this->db->commit($this->model);
$this->assertFalse($this->db->_transactionStarted);
}
}
?>

View file

@ -290,6 +290,21 @@ class DboPostgresTest extends CakeTestCase {
$this->assertEqual($this->db2->value('1', 'boolean'), 'TRUE');
$this->assertEqual($this->db2->value(null, 'boolean'), "NULL");
}
/**
* test that date columns do not generate errors with null and nullish values.
*
* @return void
**/
function testDateAsNull() {
$this->assertEqual($this->db2->value(null, 'date'), 'NULL');
$this->assertEqual($this->db2->value('', 'date'), 'NULL');
$this->assertEqual($this->db2->value('', 'datetime'), 'NULL');
$this->assertEqual($this->db2->value(null, 'datetime'), 'NULL');
$this->assertEqual($this->db2->value('', 'timestamp'), 'NULL');
$this->assertEqual($this->db2->value(null, 'timestamp'), 'NULL');
}
/**
* Tests that different Postgres boolean 'flavors' are properly returned as native PHP booleans
*

View file

@ -1211,6 +1211,8 @@ class DboSourceTest extends CakeTestCase {
$this->testDb =& new DboTest($this->__config);
$this->testDb->cacheSources = false;
$this->testDb->startQuote = '`';
$this->testDb->endQuote = '`';
Configure::write('debug', 1);
$this->debug = Configure::read('debug');
$this->Model =& new TestModel();
@ -1235,6 +1237,7 @@ class DboSourceTest extends CakeTestCase {
function testFieldDoubleEscaping() {
$config = array_merge($this->__config, array('driver' => 'test'));
$test =& ConnectionManager::create('quoteTest', $config);
$test->simulated = array();
$this->Model =& new Article2(array('alias' => 'Article', 'ds' => 'quoteTest'));
$this->Model->setDataSource('quoteTest');
@ -2133,7 +2136,7 @@ class DboSourceTest extends CakeTestCase {
$this->assertEqual($result, $expected);
$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);
$result = $this->testDb->conditions("Aro.rght = Aro.lft + 1.1");
@ -2385,7 +2388,7 @@ class DboSourceTest extends CakeTestCase {
$this->assertEqual($result, $expected);
$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);
$result = $this->testDb->conditions(array('score' => array()));
@ -2476,7 +2479,7 @@ class DboSourceTest extends CakeTestCase {
'NOT' => array('Course.id' => null, 'Course.vet' => 'N', 'level_of_education_id' => array(912,999)),
'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'));
$this->assertPattern('/^\s*WHERE\s+`id`\s+<>\s+\'8\'\s*$/', $result);
@ -2495,16 +2498,24 @@ class DboSourceTest extends CakeTestCase {
"Listing.description LIKE" => "%term_2%"
);
$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);
$result = $this->testDb->conditions(array('MD5(CONCAT(Reg.email,Reg.id))' => 'blah'));
$expected = " WHERE MD5(CONCAT(`Reg`.`email`,`Reg`.`id`)) = 'blah'";
$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));
$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);
$conditions = array('title' => 'user(s)');
@ -3384,14 +3395,14 @@ class DboSourceTest extends CakeTestCase {
'MyIndex' => array('column' => 'id', 'unique' => true)
);
$result = $this->testDb->buildIndex($data);
$expected = array('UNIQUE KEY MyIndex (`id`)');
$expected = array('UNIQUE KEY `MyIndex` (`id`)');
$this->assertEqual($result, $expected);
$data = array(
'MyIndex' => array('column' => array('id', 'name'), 'unique' => true)
);
$result = $this->testDb->buildIndex($data);
$expected = array('UNIQUE KEY MyIndex (`id`, `name`)');
$expected = array('UNIQUE KEY `MyIndex` (`id`, `name`)');
$this->assertEqual($result, $expected);
}
/**

File diff suppressed because it is too large Load diff

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

Some files were not shown because too many files have changed in this diff Show more