Merge branch '2.0' into 2.0-http

This commit is contained in:
Juan Basso 2010-12-01 11:49:26 -02:00
commit 634d686288
164 changed files with 3947 additions and 3112 deletions

View file

@ -36,19 +36,46 @@
Configure::write('debug', 2);
/**
* CakePHP Log Level:
* Configure the Error handler used to handle errors for your application. By default
* ErrorHandler::handleError() is used. It will display errors using Debugger, when debug > 0
* and log errors with CakeLog when debug = 0.
*
* In case of Production Mode CakePHP gives you the possibility to continue logging errors.
* Options:
*
* The following parameters can be used:
* Boolean: Set true/false to activate/deactivate logging
* Configure::write('log', true);
* - `handler` - callback - The callback to handle errors. You can set this to any callback type,
* including anonymous functions.
* - `level` - int - The level of errors you are interested in capturing.
* - `trace` - boolean - Include stack traces for errors in log files.
*
* Integer: Use built-in PHP constants to set the error level (see error_reporting)
* Configure::write('log', E_ERROR | E_WARNING);
* Configure::write('log', E_ALL ^ E_NOTICE);
* @see ErrorHandler for more information on error handling and configuration.
*/
Configure::write('log', true);
Configure::write('Error', array(
'handler' => 'ErrorHandler::handleError',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
/**
* Configure the Exception handler used for uncaught exceptions. By default,
* ErrorHandler::handleException() is used. It will display a HTML page for the exception, and
* while debug > 0, framework errors like Missing Controller will be displayed. When debug = 0,
* framework errors will be coerced into generic HTTP errors.
*
* Options:
*
* - `handler` - callback - The callback to handle exceptions. You can set this to any callback type,
* including anonymous functions.
* - `renderer` - string - The class responsible for rendering uncaught exceptions. If you choose a custom class you
* should place the file for that class in app/libs. This class needs to implement a render method.
* - `log` - boolean - Should Exceptions be logged?
*
* @see ErrorHandler for more information on exception handling and configuration.
*/
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'ExceptionRenderer',
'log' => true
));
/**
* Application wide charset encoding

View file

@ -65,13 +65,8 @@
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
@ -79,7 +74,7 @@
if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') {
return;
} else {
require CAKE . 'dispatcher.php';
require LIBS . 'dispatcher.php';
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch();
$Dispatcher->dispatch(new CakeRequest(isset($_GET['url']) ? $_GET['url'] : null));
}

View file

@ -65,13 +65,8 @@ if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);

View file

@ -18,7 +18,8 @@
// @license MIT License (http://www.opensource.org/licenses/mit-license.php)
// +--------------------------------------------------------------------------------------------+ //
////////////////////////////////////////////////////////////////////////////////////////////////////
1.3.5
1.3.6

View file

@ -186,11 +186,7 @@ if (!function_exists('sortByKey')) {
if (is_string($double)) {
$charset = $double;
}
if ($charset) {
return htmlspecialchars($text, ENT_QUOTES, $charset, $double);
} else {
return htmlspecialchars($text, ENT_QUOTES, $defaultCharset, $double);
}
return htmlspecialchars($text, ENT_QUOTES, ($charset) ? $charset : $defaultCharset, $double);
}
/**
@ -264,14 +260,14 @@ if (!function_exists('sortByKey')) {
* @link http://book.cakephp.org/view/1130/env
*/
function env($key) {
if ($key == 'HTTPS') {
if ($key === 'HTTPS') {
if (isset($_SERVER['HTTPS'])) {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
}
return (strpos(env('SCRIPT_URI'), 'https://') === 0);
}
if ($key == 'SCRIPT_NAME') {
if ($key === 'SCRIPT_NAME') {
if (env('CGI_MODE') && isset($_ENV['SCRIPT_URL'])) {
$key = 'SCRIPT_URL';
}

View file

@ -26,14 +26,14 @@ error_reporting(E_ALL & ~E_DEPRECATED);
require CORE_PATH . 'cake' . DS . 'basics.php';
require CORE_PATH . 'cake' . DS . 'config' . DS . 'paths.php';
require LIBS . 'exceptions.php';
require LIBS . 'error' . DS . 'exceptions.php';
require LIBS . 'object.php';
require LIBS . 'inflector.php';
require LIBS . 'app.php';
require LIBS . 'configure.php';
require LIBS . 'set.php';
require LIBS . 'cache.php';
require LIBS . 'error_handler.php';
set_exception_handler(array('ErrorHandler', 'handleException'));
require LIBS . 'error' . DS . 'error_handler.php';
Configure::bootstrap(isset($boot) ? $boot : true);

View file

@ -17,4 +17,4 @@
* @since CakePHP(tm) v 1.1.11.4062
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
return $config['Cake.version'] = '1.3.5';
return $config['Cake.version'] = '1.3.6';

View file

@ -23,3 +23,4 @@
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR. 'shell_dispatcher.php');
return ShellDispatcher::run($argv);

View file

@ -35,17 +35,19 @@ class ConsoleErrorHandler extends ErrorHandler {
* @var filehandle
* @access public
*/
public $stderr;
public static $stderr;
/**
* Class constructor.
* Get the stderr object for the console error handling.
*
* @param Exception $error Exception to handle.
* @param array $messages Error messages
*/
function __construct($error) {
$this->stderr = new ConsoleOutput('php://stderr');
parent::__construct($error);
public static function getStderr() {
if (empty(self::$stderr)) {
self::$stderr = new ConsoleOutput('php://stderr');
}
return self::$stderr;
}
/**
@ -54,57 +56,37 @@ class ConsoleErrorHandler extends ErrorHandler {
* @return void
*/
public static function handleException($exception) {
$error = new ConsoleErrorHandler($exception);
$error->render();
$stderr = self::getStderr();
$stderr->write(sprintf(
__("<error>Error:</error> %s\n%s"),
$exception->getMessage(),
$exception->getTraceAsString()
));
}
/**
* Do nothing, no controllers are needed in the console.
* Handle errors in the console environment.
*
* @return void
*/
protected function _getController($exception) {
return null;
public static function handleError($code, $description, $file = null, $line = null, $context = null) {
$stderr = self::getStderr();
list($name, $log) = self::_mapErrorCode($code);
$message = sprintf(__('%s in [%s, line %s]'), $description, $file, $line);
$stderr->write(sprintf(__("<error>%s Error:</error> %s\n"), $name, $message));
if (Configure::read('debug') == 0) {
App::import('Core', 'CakeLog');
CakeLog::write($log, $message);
}
}
/**
* Overwrite how _cakeError behaves for console. There is no reason
* to prepare urls as they are not relevant for this.
* undocumented function
*
* @param $error Exception Exception being handled.
* @return void
*/
protected function _cakeError($error) {
$this->_outputMessage();
}
/**
* Override error404 method
*
* @param Exception $error Exception
* @return void
*/
public function error400($error) {
$this->_outputMessage();
}
/**
* Override error500 method
*
* @param Exception $error Exception
* @return void
*/
public function error500($error) {
$this->_outputMessage();
}
/**
* Outputs the exception to STDERR.
*
* @param string $template The name of the template to render.
* @return void
*/
public function _outputMessage($template = null) {
public function render() {
$this->stderr->write(sprintf(
__("<error>Error:</error> %s\n%s"),
$this->error->getMessage(),

View file

@ -51,9 +51,9 @@ class ConsoleInputArgument {
}
/**
* Get the name of the argument
* Get the value of the name attribute.
*
* @return string
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;
@ -141,4 +141,4 @@ class ConsoleInputArgument {
}
return $parent;
}
}
}

View file

@ -56,14 +56,23 @@ class ConsoleInputOption {
}
/**
* Get the name of the argument
* Get the value of the name attribute.
*
* @return string
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;
}
/**
* Get the value of the short attribute.
*
* @return string Value of this->_short.
*/
public function short() {
return $this->_short;
}
/**
* Generate the help for this this option.
*

View file

@ -27,9 +27,7 @@
*/
class ConsoleInputSubcommand {
protected $_name;
protected $_help;
protected $_parser;
protected $_name, $_help, $_parser;
/**
* Make a new Subcommand
@ -56,9 +54,9 @@ class ConsoleInputSubcommand {
}
/**
* Get the name of the subcommand
* Get the value of the name attribute.
*
* @return string
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;

View file

@ -265,18 +265,24 @@ class ConsoleOptionParser {
* @return returns $this.
*/
public function addOption($name, $params = array()) {
$defaults = array(
'name' => $name,
'short' => null,
'help' => '',
'default' => null,
'boolean' => false,
'choices' => array()
);
$options = array_merge($defaults, $params);
$this->_options[$name] = new ConsoleInputOption($options);
if (!empty($options['short'])) {
$this->_shortOptions[$options['short']] = $name;
if (is_object($name) && $name instanceof ConsoleInputOption) {
$option = $name;
$name = $option->name();
} else {
$defaults = array(
'name' => $name,
'short' => null,
'help' => '',
'default' => null,
'boolean' => false,
'choices' => array()
);
$options = array_merge($defaults, $params);
$option = new ConsoleInputOption($options);
}
$this->_options[$name] = $option;
if ($option->short() !== null) {
$this->_shortOptions[$option->short()] = $name;
}
return $this;
}
@ -299,18 +305,23 @@ class ConsoleOptionParser {
* @return $this.
*/
public function addArgument($name, $params = array()) {
$defaults = array(
'name' => $name,
'help' => '',
'index' => count($this->_args),
'required' => false,
'choices' => array()
);
$options = array_merge($defaults, $params);
$index = $options['index'];
unset($options['index']);
$this->_args[$index] = new ConsoleInputArgument($options);
if (is_object($name) && $name instanceof ConsoleInputArgument) {
$arg = $name;
$index = count($this->_args);
} else {
$defaults = array(
'name' => $name,
'help' => '',
'index' => count($this->_args),
'required' => false,
'choices' => array()
);
$options = array_merge($defaults, $params);
$index = $options['index'];
unset($options['index']);
$arg = new ConsoleInputArgument($options);
}
$this->_args[$index] = $arg;
return $this;
}
@ -361,13 +372,19 @@ class ConsoleOptionParser {
* @return $this.
*/
public function addSubcommand($name, $params = array()) {
$defaults = array(
'name' => $name,
'help' => '',
'parser' => null
);
$options = array_merge($defaults, $params);
$this->_subcommands[$name] = new ConsoleInputSubcommand($options);
if (is_object($name) && $name instanceof ConsoleInputSubcommand) {
$command = $name;
$name = $command->name();
} else {
$defaults = array(
'name' => $name,
'help' => '',
'parser' => null
);
$options = array_merge($defaults, $params);
$command = new ConsoleInputSubcommand($options);
}
$this->_subcommands[$name] = $command;
return $this;
}

View file

@ -17,6 +17,8 @@
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'String', false);
/**
* HelpFormatter formats help for console shells. Can format to either
* text or XML formats. Uses ConsoleOptionParser methods to generate help.

View file

@ -80,8 +80,6 @@ class ShellDispatcher {
*/
function __initConstants() {
if (function_exists('ini_set')) {
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL & ~E_DEPRECATED);
ini_set('html_errors', false);
ini_set('implicit_flush', true);
ini_set('max_execution_time', 0);
@ -90,7 +88,6 @@ class ShellDispatcher {
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
define('DS', DIRECTORY_SEPARATOR);
define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__))));
define('DISABLE_DEFAULT_ERROR_HANDLING', false);
define('CAKEPHP_SHELL', true);
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ini_get('include_path'))) {
@ -141,13 +138,15 @@ class ShellDispatcher {
$boot = file_exists(ROOT . DS . APP_DIR . DS . 'config' . DS . 'bootstrap.php');
require CORE_PATH . 'cake' . DS . 'bootstrap.php';
require_once CONSOLE_LIBS . 'console_error_handler.php';
set_exception_handler(array('ConsoleErrorHandler', 'handleException'));
if (!file_exists(APP_PATH . 'config' . DS . 'core.php')) {
include_once CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS . 'console' . DS . 'templates' . DS . 'skel' . DS . 'config' . DS . 'core.php';
App::build();
}
require_once CONSOLE_LIBS . 'console_error_handler.php';
set_exception_handler(array('ConsoleErrorHandler', 'handleException'));
set_error_handler(array('ConsoleErrorHandler', 'handleError'), Configure::read('Error.level'));
if (!defined('FULL_BASE_URL')) {
define('FULL_BASE_URL', '/');
}

View file

@ -94,7 +94,7 @@ class AclShell extends Shell {
if (!in_array($this->command, array('initdb'))) {
$collection = new ComponentCollection();
$this->Acl =& new AclComponent($collection);
$this->Acl = new AclComponent($collection);
$controller = null;
$this->Acl->startup($controller);
}

View file

@ -0,0 +1,33 @@
<?php
/**
* AppShell file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.console.shells
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* This is a placeholder class.
* Create the same file in app/console/shells/app_shell.php
*
* Add your application-wide methods in the class below, your shells
* will inherit them.
*
* @package cake
* @subpackage cake.cake.console.libs
*/
class AppShell extends Shell {
}

View file

@ -40,7 +40,14 @@ class BakeShell extends Shell {
public $tasks = array('Project', 'DbConfig', 'Model', 'Controller', 'View', 'Plugin', 'Fixture', 'Test');
/**
* Override loadTasks() to handle paths
* The connection being used.
*
* @var string
*/
public $connection = 'default';
/**
* Assign $this->connection to the active task if a connection param is set.
*
*/
public function startup() {
@ -121,7 +128,6 @@ class BakeShell extends Shell {
*
*/
public function all() {
$this->hr();
$this->out('Bake All');
$this->hr();
@ -156,7 +162,6 @@ class BakeShell extends Shell {
$modelBaked = $this->Model->bake($object, false);
if ($modelBaked && $modelExists === false) {
$this->out(sprintf(__('%s Model was baked.'), $model));
if ($this->_checkUnitTest()) {
$this->Model->bakeFixture($model);
$this->Model->bakeTest($model);
@ -167,7 +172,6 @@ class BakeShell extends Shell {
if ($modelExists === true) {
$controller = $this->_controllerName($name);
if ($this->Controller->bake($controller, $this->Controller->bakeActions($controller))) {
$this->out(sprintf(__('%s Controller was baked.'), $name));
if ($this->_checkUnitTest()) {
$this->Controller->bakeTest($controller);
}
@ -175,9 +179,9 @@ class BakeShell extends Shell {
if (App::import('Controller', $controller)) {
$this->View->args = array($controller);
$this->View->execute();
$this->out(sprintf(__('%s Views were baked.'), $name));
}
$this->out(__('Bake All complete'));
$this->out('', 1, Shell::QUIET);
$this->out(__('<success>Bake All complete</success>'), 1, Shell::QUIET);
array_shift($this->args);
} else {
$this->error(__('Bake All could not continue without a valid model'));

View file

@ -111,7 +111,7 @@ class CommandListShell extends Shell {
continue;
}
foreach ($shells as $shell) {
if ($shell !== 'shell.php') {
if ($shell !== 'shell.php' && $shell !== 'app_shell.php') {
$shell = str_replace('.php', '', $shell);
$shellList[$shell][$type] = $type;
}

View file

@ -61,7 +61,7 @@ class ConsoleShell extends Shell {
foreach ($this->models as $model) {
$class = Inflector::camelize(str_replace('.php', '', $model));
$this->models[$model] = $class;
$this->{$class} =& new $class();
$this->{$class} = new $class();
}
$this->out('Model classes:');
$this->out('--------------');
@ -290,7 +290,7 @@ class ConsoleShell extends Shell {
}
break;
case (preg_match("/^routes\s+reload/i", $command, $tmp) == true):
$router =& Router::getInstance();
$router = Router::getInstance();
if (!$this->_loadRoutes()) {
$this->out("There was an error loading the routes config. Please check that the file");
$this->out("exists and is free of parse errors.");
@ -299,7 +299,7 @@ class ConsoleShell extends Shell {
$this->out("Routes configuration reloaded, " . count($router->routes) . " routes connected");
break;
case (preg_match("/^routes\s+show/i", $command, $tmp) == true):
$router =& Router::getInstance();
$router = Router::getInstance();
$this->out(implode("\n", Set::extract($router->routes, '{n}.0')));
break;
case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
@ -335,7 +335,7 @@ class ConsoleShell extends Shell {
* @return boolean True if config reload was a success, otherwise false
*/
protected function _loadRoutes() {
$router =& Router::getInstance();
$router = Router::getInstance();
$router->reload();
extract($router->getNamedExpressions());

View file

@ -99,7 +99,7 @@ class SchemaShell extends Shell {
$name = $plugin;
}
}
$this->Schema =& new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
$this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
}
/**
@ -151,7 +151,7 @@ class SchemaShell extends Shell {
$content['file'] = $this->params['file'];
if ($snapshot === true) {
$Folder =& new Folder($this->Schema->path);
$Folder = new Folder($this->Schema->path);
$result = $Folder->read();
$numToUse = false;
@ -209,7 +209,7 @@ class SchemaShell extends Shell {
$write = $this->params['write'];
}
}
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db = ConnectionManager::getDataSource($this->Schema->connection);
$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);
@ -218,9 +218,9 @@ class SchemaShell extends Shell {
$write .= '.sql';
}
if (strpos($write, DS) !== false) {
$File =& new File($write, true);
$File = new File($write, true);
} else {
$File =& new File($this->Schema->path . DS . $write, true);
$File = new File($this->Schema->path . DS . $write, true);
}
if ($File->write($contents)) {
@ -280,7 +280,7 @@ class SchemaShell extends Shell {
$options['file'] = $fileName . '_' . $this->params['snapshot'] . '.php';
}
$Schema =& $this->Schema->load($options);
$Schema = $this->Schema->load($options);
if (!$Schema) {
$this->err(sprintf(__('%s could not be loaded'), $this->Schema->path . DS . $this->Schema->file));
@ -300,7 +300,7 @@ class SchemaShell extends Shell {
* @access private
*/
function __create(&$Schema, $table = null) {
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db = ConnectionManager::getDataSource($this->Schema->connection);
$drop = $create = array();
@ -343,7 +343,7 @@ class SchemaShell extends Shell {
* @access private
*/
function __update(&$Schema, $table = null) {
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db = ConnectionManager::getDataSource($this->Schema->connection);
$this->out(__('Comparing Database to Schema...'));
$options = array();
@ -390,7 +390,7 @@ class SchemaShell extends Shell {
return;
}
Configure::write('debug', 2);
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db = ConnectionManager::getDataSource($this->Schema->connection);
foreach ($contents as $table => $sql) {
if (empty($sql)) {

View file

@ -164,6 +164,14 @@ class Shell extends Object {
if ($this->stdin == null) {
$this->stdin = new ConsoleInput('php://stdin');
}
$parent = get_parent_class($this);
if ($this->tasks !== null && $this->tasks !== false) {
$this->_mergeVars(array('tasks'), $parent, true);
}
if ($this->uses !== null && $this->uses !== false) {
$this->_mergeVars(array('uses'), $parent, false);
}
}
/**

View file

@ -278,7 +278,7 @@ class ControllerTask extends BakeTask {
$this->_stop();
}
$modelObj =& ClassRegistry::init($currentModelName);
$modelObj = ClassRegistry::init($currentModelName);
$controllerPath = $this->_controllerPath($controllerName);
$pluralName = $this->_pluralName($currentModelName);
$singularName = Inflector::variable($currentModelName);
@ -302,6 +302,8 @@ class ControllerTask extends BakeTask {
* @return string Baked controller
*/
public function bake($controllerName, $actions = '', $helpers = null, $components = null) {
$this->out("\nBaking controller class for $controllerName...", 1, Shell::QUIET);
$isScaffold = ($actions === 'scaffold') ? true : false;
$this->Template->set('plugin', Inflector::camelize($this->plugin));

View file

@ -254,7 +254,7 @@ class FixtureTask extends BakeTask {
$this->Template->set($vars);
$content = $this->Template->generate('classes', 'fixture');
$this->out("\nBaking test fixture for $model...");
$this->out("\nBaking test fixture for $model...", 1, Shell::QUIET);
$this->createFile($path . $filename, $content);
return $content;
}
@ -394,12 +394,12 @@ class FixtureTask extends BakeTask {
$condition = 'WHERE 1=1 LIMIT ' . (isset($this->params['count']) ? $this->params['count'] : 10);
}
App::import('Model', 'Model', false);
$modelObject =& new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
$modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
$records = $modelObject->find('all', array(
'conditions' => $condition,
'recursive' => -1
));
$db =& ConnectionManager::getDataSource($modelObject->useDbConfig);
$db = ConnectionManager::getDataSource($modelObject->useDbConfig);
$schema = $modelObject->schema(true);
$out = array();
foreach ($records as $record) {

View file

@ -131,7 +131,7 @@ class ModelTask extends BakeTask {
if (!$table) {
$table = Inflector::tableize($className);
}
$object =& new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
$object = new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
return $object;
}
@ -180,7 +180,7 @@ class ModelTask extends BakeTask {
}
$currentModelName = $this->getName();
$useTable = $this->getTable($currentModelName);
$db =& ConnectionManager::getDataSource($this->connection);
$db = ConnectionManager::getDataSource($this->connection);
$fullTableName = $db->fullTableName($useTable);
if (in_array($useTable, $this->_tables)) {
@ -742,7 +742,7 @@ class ModelTask extends BakeTask {
$path = $this->getPath();
$filename = $path . Inflector::underscore($name) . '.php';
$this->out("\nBaking model class for $name...");
$this->out("\nBaking model class for $name...", 1, Shell::QUIET);
$this->createFile($filename, $out);
ClassRegistry::flush();
return $out;
@ -793,7 +793,7 @@ class ModelTask extends BakeTask {
}
App::import('Model', 'ConnectionManager', false);
$db =& ConnectionManager::getDataSource($useDbConfig);
$db = ConnectionManager::getDataSource($useDbConfig);
$useTable = Inflector::tableize($modelName);
$fullTableName = $db->fullTableName($useTable, false);
$tableIsGood = false;
@ -823,7 +823,7 @@ class ModelTask extends BakeTask {
App::import('Model', 'ConnectionManager', false);
$tables = array();
$db =& ConnectionManager::getDataSource($useDbConfig);
$db = ConnectionManager::getDataSource($useDbConfig);
$db->cacheSources = false;
$usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
if ($usePrefix) {

View file

@ -104,7 +104,7 @@ class PluginTask extends Shell {
$looksGood = $this->in(__('Look okay?'), array('y', 'n', 'q'), 'y');
if (strtolower($looksGood) == 'y') {
$Folder =& new Folder($this->path . $pluginPath);
$Folder = new Folder($this->path . $pluginPath);
$directories = array(
'config' . DS . 'schema',
'models' . DS . 'behaviors',
@ -127,7 +127,7 @@ class PluginTask extends Shell {
foreach ($directories as $directory) {
$dirPath = $this->path . $pluginPath . DS . $directory;
$Folder->create($dirPath);
$File =& new File($dirPath . DS . 'empty', true);
$File = new File($dirPath . DS . 'empty', true);
}
foreach ($Folder->messages() as $message) {

View file

@ -59,7 +59,7 @@ class TemplateTask extends Shell {
$separator = DS === '/' ? '/' : '\\\\';
$core = preg_replace('#shells' . $separator . '$#', '', $core);
$paths[] = $core;
$Folder =& new Folder($core . 'templates' . DS . 'default');
$Folder = new Folder($core . 'templates' . DS . 'default');
$contents = $Folder->read();
$themeFolders = $contents[0];
@ -76,14 +76,14 @@ class TemplateTask extends Shell {
$themes = array();
foreach ($paths as $path) {
$Folder =& new Folder($path . 'templates', false);
$Folder = new Folder($path . 'templates', false);
$contents = $Folder->read();
$subDirs = $contents[0];
foreach ($subDirs as $dir) {
if (empty($dir) || preg_match('@^skel$|_skel$@', $dir)) {
continue;
}
$Folder =& new Folder($path . 'templates' . DS . $dir);
$Folder = new Folder($path . 'templates' . DS . $dir);
$contents = $Folder->read();
$subDirs = $contents[0];
if (array_intersect($contents[0], $themeFolders)) {

View file

@ -19,6 +19,7 @@
*/
include_once dirname(__FILE__) . DS . 'bake.php';
App::import('Model', 'ClassRegistry');
/**
* Task class for creating and updating test files.
@ -114,8 +115,8 @@ class TestTask extends BakeTask {
*/
public function bake($type, $className) {
if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($type, $className)) {
$this->out(__('Bake is detecting possible fixtures..'));
$testSubject =& $this->buildTestSubject($type, $className);
$this->out(__('Bake is detecting possible fixtures...'));
$testSubject = $this->buildTestSubject($type, $className);
$this->generateFixtureList($testSubject);
} elseif ($this->interactive) {
$this->getUserFixtures();
@ -133,6 +134,7 @@ class TestTask extends BakeTask {
if ($this->plugin) {
$plugin = $this->plugin . '.';
}
$this->out("\nBaking test case for $className $type...", 1, Shell::QUIET);
$this->Template->set('fixtures', $this->_fixtures);
$this->Template->set('plugin', $plugin);
@ -228,9 +230,9 @@ class TestTask extends BakeTask {
App::import($type, $class);
$class = $this->getRealClassName($type, $class);
if (strtolower($type) == 'model') {
$instance =& ClassRegistry::init($class);
$instance = ClassRegistry::init($class);
} else {
$instance =& new $class();
$instance = new $class();
}
return $instance;
}

View file

@ -282,11 +282,11 @@ class ViewTask extends BakeTask {
$this->_stop();
}
$controllerClassName = $this->controllerName . 'Controller';
$controllerObj =& new $controllerClassName();
$controllerObj = new $controllerClassName();
$controllerObj->plugin = $this->plugin;
$controllerObj->constructClasses();
$modelClass = $controllerObj->modelClass;
$modelObj =& $controllerObj->{$controllerObj->modelClass};
$modelObj = $controllerObj->{$controllerObj->modelClass};
if ($modelObj) {
$primaryKey = $modelObj->primaryKey;
@ -366,6 +366,7 @@ class ViewTask extends BakeTask {
if (empty($content)) {
return false;
}
$this->out("\nBaking `$action` view file...", 1, Shell::QUIET);
$path = $this->getPath();
$filename = $path . $this->controllerPath . DS . Inflector::underscore($action) . '.ctp';
return $this->createFile($filename, $content);

View file

@ -56,7 +56,7 @@ class TestSuiteShell extends Shell {
))->addOption('log-dbus', array(
'help' => __('Log test execution to DBUS.'),
'default' => false
))->addOption('--coverage-html', array(
))->addOption('coverage-html', array(
'help' => __('<dir> Generate code coverage report in HTML format.'),
'default' => false
))->addOption('coverage-clover', array(
@ -253,6 +253,10 @@ class TestSuiteShell extends Shell {
*/
protected function run($runnerArgs, $options = array()) {
require_once CAKE . 'tests' . DS . 'lib' . DS . 'test_runner.php';
restore_error_handler();
restore_error_handler();
$testCli = new TestRunner($runnerArgs);
$testCli->run($options);
}
@ -280,8 +284,7 @@ class TestSuiteShell extends Shell {
if (empty($testCases)) {
$this->out(__("No test cases available \n\n"));
$this->help();
$this->_stop();
return $this->out($this->OptionParser->help());
}
$this->out($title);

View file

@ -39,7 +39,7 @@ class <?php echo $fullClassName; ?>TestCase extends CakeTestCase {
<?php endif; ?>
public function startTest() {
$this-><?php echo $className . ' =& ' . $construction; ?>
$this-><?php echo $className . ' = ' . $construction; ?>
}
public function endTest() {

View file

@ -36,19 +36,46 @@
Configure::write('debug', 2);
/**
* CakePHP Log Level:
* Configure the Error handler used to handle errors for your application. By default
* ErrorHandler::handleError() is used. It will display errors using Debugger, when debug > 0
* and log errors with CakeLog when debug = 0.
*
* In case of Production Mode CakePHP gives you the possibility to continue logging errors.
* Options:
*
* The following parameters can be used:
* Boolean: Set true/false to activate/deactivate logging
* Configure::write('log', true);
* - `handler` - callback - The callback to handle errors. You can set this to any callback type,
* including anonymous functions.
* - `level` - int - The level of errors you are interested in capturing.
* - `trace` - boolean - Include stack traces for errors in log files.
*
* Integer: Use built-in PHP constants to set the error level (see error_reporting)
* Configure::write('log', E_ERROR | E_WARNING);
* Configure::write('log', E_ALL ^ E_NOTICE);
* @see ErrorHandler for more information on error handling and configuration.
*/
Configure::write('log', true);
Configure::write('Error', array(
'handler' => 'ErrorHandler::handleError',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
/**
* Configure the Exception handler used for uncaught exceptions. By default,
* ErrorHandler::handleException() is used. It will display a HTML page for the exception, and
* while debug > 0, framework errors like Missing Controller will be displayed. When debug = 0,
* framework errors will be coerced into generic HTTP errors.
*
* Options:
*
* - `handler` - callback - The callback to handle exceptions. You can set this to any callback type,
* including anonymous functions.
* - `renderer` - string - The class responsible for rendering uncaught exceptions. If you choose a custom class you
* should place the file for that class in app/libs. This class needs to implement a render method.
* - `log` - boolean - Should Exceptions be logged?
*
* @see ErrorHandler for more information on exception handling and configuration.
*/
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'ExceptionRenderer',
'log' => true
));
/**
* Application wide charset encoding
@ -121,14 +148,14 @@
* - `Session.name` - The name of the cookie to use. Defaults to 'CAKEPHP'
* - `Session.timeout` - The number of minutes you want sessions to live for. This timeout is handled by CakePHP
* - `Session.cookieTimeout` - The number of minutes you want session cookies to live for.
* - `Session.checkAgent` - Do you want the user agent to be checked when starting sessions? You might want to set the
* - `Session.checkAgent` - Do you want the user agent to be checked when starting sessions? You might want to set the
* value to false, when dealing with older versions of IE, Chrome Frame or certain web-browsing devices and AJAX
* - `Session.defaults` - The default configuration set to use as a basis for your session.
* There are four builtins: php, cake, cache, database.
* - `Session.handler` - Can be used to enable a custom session handler. Expects an array of of callables,
* that can be used with `session_save_handler`. Using this option will automatically add `session.save_handler`
* to the ini array.
* - `Session.autoRegenerate` - Enabling this setting, turns on automatic regeneration of sessions, and
* - `Session.autoRegenerate` - Enabling this setting, turns on automatic renewal of sessions, and
* sessionids that change frequently. See CakeSession::$requestCountdown.
* - `Session.ini` - An associative array of additional ini values to set.
*

View file

@ -65,13 +65,8 @@
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
@ -79,7 +74,7 @@
if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') {
return;
} else {
require CAKE . 'dispatcher.php';
require LIBS . 'dispatcher.php';
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch();
$Dispatcher->dispatch(new CakeRequest(isset($_GET['url']) ? $_GET['url'] : null));
}

View file

@ -65,13 +65,8 @@ if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);

889
cake/libs/app.php Normal file
View file

@ -0,0 +1,889 @@
<?php
/**
* App class
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 1.2.0.6001
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* App is responsible for path managment, class location and class loading.
*
* ### Adding paths
*
* You can add paths to the search indexes App uses to find classes using `App::build()`. Adding
* additional controller paths for example would alter where CakePHP looks for controllers when you
* call App::import('Controller', 'Posts'); This allows you to split your application up across the filesystem.
*
* ### Inspecting loaded paths
*
* You can inspect the currently loaded paths using `App::path('controller')` for example to see loaded
* controller paths.
*
* ### Locating plugins and themes
*
* Plugins and Themes can be located with App as well. Using App::pluginPath('DebugKit') for example, will
* give you the full path to the DebugKit plugin. App::themePath('purple'), would give the full path to the
* `purple` theme.
*
* ### Inspecting known objects
*
* You can find out which objects App knows about using App::objects('controller') for example to find
* which application controllers App knows about.
*
* @link http://book.cakephp.org/view/933/The-App-Class
* @package cake
* @subpackage cake.cake.libs
*/
class App {
/**
* List of object types and their properties
*
* @var array
*/
public static $types = array(
'class' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'file' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'model' => array('suffix' => '.php', 'extends' => 'AppModel', 'core' => false),
'behavior' => array('suffix' => '.php', 'extends' => 'ModelBehavior', 'core' => true),
'controller' => array('suffix' => '_controller.php', 'extends' => 'AppController', 'core' => true),
'component' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'lib' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'view' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'helper' => array('suffix' => '.php', 'extends' => 'AppHelper', 'core' => true),
'vendor' => array('suffix' => '', 'extends' => null, 'core' => true),
'shell' => array('suffix' => '.php', 'extends' => 'Shell', 'core' => true),
'plugin' => array('suffix' => '', 'extends' => null, 'core' => true)
);
/**
* List of additional path(s) where model files reside.
*
* @var array
*/
public static $models = array();
/**
* List of additional path(s) where behavior files reside.
*
* @var array
*/
public static $behaviors = array();
/**
* List of additional path(s) where controller files reside.
*
* @var array
*/
public static $controllers = array();
/**
* List of additional path(s) where component files reside.
*
* @var array
*/
public static $components = array();
/**
* List of additional path(s) where datasource files reside.
*
* @var array
*/
public static $datasources = array();
/**
* List of additional path(s) where libs files reside.
*
* @var array
*/
public static $libs = array();
/**
* List of additional path(s) where view files reside.
*
* @var array
*/
public static $views = array();
/**
* List of additional path(s) where helper files reside.
*
* @var array
*/
public static $helpers = array();
/**
* List of additional path(s) where plugins reside.
*
* @var array
*/
public static $plugins = array();
/**
* List of additional path(s) where vendor packages reside.
*
* @var array
*/
public static $vendors = array();
/**
* List of additional path(s) where locale files reside.
*
* @var array
*/
public static $locales = array();
/**
* List of additional path(s) where console shell files reside.
*
* @var array
*/
public static $shells = array();
/**
* Paths to search for files.
*
* @var array
*/
public static $search = array();
/**
* Whether or not to return the file that is loaded.
*
* @var boolean
*/
public static $return = false;
/**
* Determines if $__maps and $__paths cache should be written.
*
* @var boolean
*/
private static $__cache = false;
/**
* Holds key/value pairs of $type => file path.
*
* @var array
*/
private static $__map = array();
/**
* Holds paths for deep searching of files.
*
* @var array
*/
private static $__paths = array();
/**
* Holds loaded files.
*
* @var array
*/
private static $__loaded = array();
/**
* Holds and key => value array of object types.
*
* @var array
*/
private static $__objects = array();
/**
* Used to read information stored path
*
* Usage:
*
* `App::path('models'); will return all paths for models`
*
* @param string $type type of path
* @return string array
*/
public static function path($type) {
if (!isset(self::${$type})) {
return array();
}
return self::${$type};
}
/**
* Build path references. Merges the supplied $paths
* with the base paths and the default core paths.
*
* @param array $paths paths defines in config/bootstrap.php
* @param boolean $reset true will set paths, false merges paths [default] false
* @return void
*/
public static function build($paths = array(), $reset = false) {
$defaults = array(
'models' => array(MODELS),
'behaviors' => array(BEHAVIORS),
'datasources' => array(MODELS . 'datasources'),
'controllers' => array(CONTROLLERS),
'components' => array(COMPONENTS),
'libs' => array(APPLIBS),
'views' => array(VIEWS),
'helpers' => array(HELPERS),
'locales' => array(APP . 'locale' . DS),
'shells' => array(
APP . 'console' . DS . 'shells' . DS,
APP . 'vendors' . DS . 'shells' . DS,
VENDORS . 'shells' . DS
),
'vendors' => array(APP . 'vendors' . DS, VENDORS),
'plugins' => array(APP . 'plugins' . DS)
);
if ($reset == true) {
foreach ($paths as $type => $new) {
self::${$type} = (array)$new;
}
return $paths;
}
$core = self::core();
$app = array('models' => true, 'controllers' => true, 'helpers' => true);
foreach ($defaults as $type => $default) {
$merge = array();
if (isset($app[$type])) {
$merge = array(APP);
}
if (isset($core[$type])) {
$merge = array_merge($merge, (array)$core[$type]);
}
if (empty(self::${$type}) || empty($paths)) {
self::${$type} = $default;
}
if (!empty($paths[$type])) {
$path = array_flip(array_flip(array_merge(
(array)$paths[$type], self::${$type}, $merge
)));
self::${$type} = array_values($path);
} else {
$path = array_flip(array_flip(array_merge(self::${$type}, $merge)));
self::${$type} = array_values($path);
}
}
}
/**
* Get the path that a plugin is on. Searches through the defined plugin paths.
*
* @param string $plugin CamelCased/lower_cased plugin name to find the path of.
* @return string full path to the plugin.
*/
public static function pluginPath($plugin) {
$pluginDir = Inflector::underscore($plugin);
for ($i = 0, $length = count(self::$plugins); $i < $length; $i++) {
if (is_dir(self::$plugins[$i] . $pluginDir)) {
return self::$plugins[$i] . $pluginDir . DS ;
}
}
return self::$plugins[0] . $pluginDir . DS;
}
/**
* Find the path that a theme is on. Search through the defined theme paths.
*
* @param string $theme lower_cased theme name to find the path of.
* @return string full path to the theme.
*/
public static function themePath($theme) {
$themeDir = 'themed' . DS . Inflector::underscore($theme);
for ($i = 0, $length = count(self::$views); $i < $length; $i++) {
if (is_dir(self::$views[$i] . $themeDir)) {
return self::$views[$i] . $themeDir . DS ;
}
}
return self::$views[0] . $themeDir . DS;
}
/**
* Returns a key/value list of all paths where core libs are found.
* Passing $type only returns the values for a given value of $key.
*
* @param string $type valid values are: 'model', 'behavior', 'controller', 'component',
* 'view', 'helper', 'datasource', 'libs', and 'cake'
* @return array numeric keyed array of core lib paths
*/
public static function core($type = null) {
static $paths = false;
if (!$paths) {
$paths = array();
$libs = dirname(__FILE__) . DS;
$cake = dirname($libs) . DS;
$path = dirname($cake) . DS;
$paths['cake'][] = $cake;
$paths['libs'][] = $libs;
$paths['models'][] = $libs . 'model' . DS;
$paths['datasources'][] = $libs . 'model' . DS . 'datasources' . DS;
$paths['behaviors'][] = $libs . 'model' . DS . 'behaviors' . DS;
$paths['controllers'][] = $libs . 'controller' . DS;
$paths['components'][] = $libs . 'controller' . DS . 'components' . DS;
$paths['views'][] = $libs . 'view' . DS;
$paths['helpers'][] = $libs . 'view' . DS . 'helpers' . DS;
$paths['plugins'][] = $path . 'plugins' . DS;
$paths['vendors'][] = $path . 'vendors' . DS;
$paths['shells'][] = $cake . 'console' . DS . 'shells' . DS;
// Provide BC path to vendors/shells
$paths['shells'][] = $path . 'vendors' . DS . 'shells' . DS;
}
if ($type && isset($paths[$type])) {
return $paths[$type];
}
return $paths;
}
/**
* Returns an array of objects of the given type.
*
* Example usage:
*
* `App::objects('plugin');` returns `array('DebugKit', 'Blog', 'User');`
*
* @param string $type Type of object, i.e. 'model', 'controller', 'helper', or 'plugin'
* @param mixed $path Optional Scan only the path given. If null, paths for the chosen
* type will be used.
* @param boolean $cache Set to false to rescan objects of the chosen type. Defaults to true.
* @return mixed Either false on incorrect / miss. Or an array of found objects.
*/
public static function objects($type, $path = null, $cache = true) {
$objects = array();
$extension = false;
$name = $type;
if ($type === 'file' && !$path) {
return false;
} elseif ($type === 'file') {
$extension = true;
$name = $type . str_replace(DS, '', $path);
}
if (empty(self::$__objects) && $cache === true) {
self::$__objects = Cache::read('object_map', '_cake_core_');
}
if (!isset(self::$__objects[$name]) || $cache !== true) {
$types = self::$types;
if (!isset($types[$type])) {
return false;
}
$objects = array();
if (empty($path)) {
$path = self::${"{$type}s"};
if (isset($types[$type]['core']) && $types[$type]['core'] === false) {
array_pop($path);
}
}
$items = array();
foreach ((array)$path as $dir) {
if ($dir != APP) {
$items = self::__list($dir, $types[$type]['suffix'], $extension);
$objects = array_merge($items, array_diff($objects, $items));
}
}
if ($type !== 'file') {
foreach ($objects as $key => $value) {
$objects[$key] = Inflector::camelize($value);
}
}
if ($cache === true) {
self::$__cache = true;
}
self::$__objects[$name] = $objects;
}
return self::$__objects[$name];
}
/**
* Allows you to modify the object listings that App maintains inside of it
* Useful for testing
*
* @param string $type Type of object listing you are changing
* @param array $values The values $type should be set to.
* @return void
*/
public static function setObjects($type, $values) {
self::$__objects[$type] = $values;
}
/**
* Finds classes based on $name or specific file(s) to search. Calling App::import() will
* not construct any classes contained in the files. It will only find and require() the file.
*
* @link http://book.cakephp.org/view/934/Using-App-import
* @param mixed $type The type of Class if passed as a string, or all params can be passed as
* an single array to $type,
* @param string $name Name of the Class or a unique name for the file
* @param mixed $parent boolean true if Class Parent should be searched, accepts key => value
* array('parent' => $parent ,'file' => $file, 'search' => $search, 'ext' => '$ext');
* $ext allows setting the extension of the file name
* based on Inflector::underscore($name) . ".$ext";
* @param array $search paths to search for files, array('path 1', 'path 2', 'path 3');
* @param string $file full name of the file to search for including extension
* @param boolean $return, return the loaded file, the file must have a return
* statement in it to work: return $variable;
* @return boolean true if Class is already in memory or if file is found and loaded, false if not
*/
public static function import($type = null, $name = null, $parent = true, $search = array(), $file = null, $return = false) {
$plugin = $directory = null;
if (is_array($type)) {
extract($type, EXTR_OVERWRITE);
}
if (is_array($parent)) {
extract($parent, EXTR_OVERWRITE);
}
if ($name === null && $file === null) {
$name = $type;
$type = 'Core';
} elseif ($name === null) {
$type = 'File';
}
if (is_array($name)) {
foreach ($name as $class) {
$tempType = $type;
$plugin = null;
if (strpos($class, '.') !== false) {
$value = explode('.', $class);
$count = count($value);
if ($count > 2) {
$tempType = $value[0];
$plugin = $value[1] . '.';
$class = $value[2];
} elseif ($count === 2 && ($type === 'Core' || $type === 'File')) {
$tempType = $value[0];
$class = $value[1];
} else {
$plugin = $value[0] . '.';
$class = $value[1];
}
}
if (!App::import($tempType, $plugin . $class, $parent)) {
return false;
}
}
return true;
}
if ($name != null && strpos($name, '.') !== false) {
list($plugin, $name) = explode('.', $name);
$plugin = Inflector::camelize($plugin);
}
self::$return = $return;
if (isset($ext)) {
$file = Inflector::underscore($name) . ".{$ext}";
}
$ext = self::__settings($type, $plugin, $parent);
$className = $name;
if (strpos($className, '/') !== false) {
$className = substr($className, strrpos($className, '/') + 1);
}
if ($name != null && !class_exists($className . $ext['class'])) {
if ($load = self::__mapped($name . $ext['class'], $type, $plugin)) {
if (self::__load($load)) {
if (self::$return) {
return include($load);
}
return true;
} else {
self::__remove($name . $ext['class'], $type, $plugin);
self::$__cache = true;
}
}
if (!empty($search)) {
self::$search = $search;
} elseif ($plugin) {
self::$search = self::__paths('plugin');
} else {
self::$search = self::__paths($type);
}
$find = $file;
if ($find === null) {
$find = Inflector::underscore($name . $ext['suffix']).'.php';
if ($plugin) {
$paths = self::$search;
foreach ($paths as $key => $value) {
self::$search[$key] = $value . $ext['path'];
}
}
}
if (strtolower($type) !== 'vendor' && empty($search) && self::__load($file)) {
$directory = false;
} else {
$file = $find;
$directory = self::__find($find, true);
}
if ($directory !== null) {
self::$__cache = true;
self::__map($directory . $file, $name . $ext['class'], $type, $plugin);
if (self::$return) {
return include($directory . $file);
}
return true;
}
return false;
}
return true;
}
/**
* Initializes the cache for App, registers a shutdown function.
*
* @return void
*/
public static function init() {
self::$__map = (array)Cache::read('file_map', '_cake_core_');
register_shutdown_function(array('App', 'shutdown'));
}
/**
* Locates the $file in $__paths, searches recursively.
*
* @param string $file full file name
* @param boolean $recursive search $__paths recursively
* @return mixed boolean on fail, $file directory path on success
*/
private static function __find($file, $recursive = true) {
static $appPath = false;
if (empty(self::$search)) {
return null;
} elseif (is_string(self::$search)) {
$this->search = array(self::$search);
}
if (empty(self::$__paths)) {
self::$__paths = Cache::read('dir_map', '_cake_core_');
}
foreach (self::$search as $path) {
if ($appPath === false) {
$appPath = rtrim(APP, DS);
}
$path = rtrim($path, DS);
if ($path === $appPath) {
$recursive = false;
}
if ($recursive === false) {
if (self::__load($path . DS . $file)) {
return $path . DS;
}
continue;
}
if (!isset(self::$__paths[$path])) {
if (!class_exists('Folder')) {
require LIBS . 'folder.php';
}
$Folder = new Folder();
$directories = $Folder->tree($path, array('.svn', '.git', 'CVS', 'tests', 'templates'), 'dir');
sort($directories);
self::$__paths[$path] = $directories;
}
foreach (self::$__paths[$path] as $directory) {
if (self::__load($directory . DS . $file)) {
return $directory . DS;
}
}
}
return null;
}
/**
* Attempts to load $file.
*
* @param string $file full path to file including file name
* @return boolean
* @access private
*/
private static function __load($file) {
if (empty($file)) {
return false;
}
if (!self::$return && isset(self::$__loaded[$file])) {
return true;
}
if (file_exists($file)) {
if (!self::$return) {
require($file);
self::$__loaded[$file] = true;
}
return true;
}
return false;
}
/**
* Maps the $name to the $file.
*
* @param string $file full path to file
* @param string $name unique name for this map
* @param string $type type object being mapped
* @param string $plugin camelized if object is from a plugin, the name of the plugin
* @return void
* @access private
*/
private static function __map($file, $name, $type, $plugin) {
if ($plugin) {
self::$__map['Plugin'][$plugin][$type][$name] = $file;
} else {
self::$__map[$type][$name] = $file;
}
}
/**
* Returns a file's complete path.
*
* @param string $name unique name
* @param string $type type object
* @param string $plugin camelized if object is from a plugin, the name of the plugin
* @return mixed, file path if found, false otherwise
* @access private
*/
private static function __mapped($name, $type, $plugin) {
if ($plugin) {
if (isset(self::$__map['Plugin'][$plugin][$type]) && isset(self::$__map['Plugin'][$plugin][$type][$name])) {
return self::$__map['Plugin'][$plugin][$type][$name];
}
return false;
}
if (isset(self::$__map[$type]) && isset(self::$__map[$type][$name])) {
return self::$__map[$type][$name];
}
return false;
}
/**
* Loads parent classes based on $type.
* Returns a prefix or suffix needed for loading files.
*
* @param string $type type of object
* @param string $plugin camelized name of plugin
* @param boolean $parent false will not attempt to load parent
* @return array
* @access private
*/
private static function __settings($type, $plugin, $parent) {
if (!$parent) {
return array('class' => null, 'suffix' => null, 'path' => null);
}
if ($plugin) {
$pluginPath = Inflector::underscore($plugin);
}
$path = null;
$load = strtolower($type);
switch ($load) {
case 'model':
if (!class_exists('Model')) {
require LIBS . 'model' . DS . 'model.php';
}
if (!class_exists('AppModel')) {
App::import($type, 'AppModel', false);
}
if ($plugin) {
if (!class_exists($plugin . 'AppModel')) {
App::import($type, $plugin . '.' . $plugin . 'AppModel', false, array(), $pluginPath . DS . $pluginPath . '_app_model.php');
}
$path = $pluginPath . DS . 'models' . DS;
}
return array('class' => null, 'suffix' => null, 'path' => $path);
break;
case 'behavior':
if ($plugin) {
$path = $pluginPath . DS . 'models' . DS . 'behaviors' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'datasource':
if ($plugin) {
$path = $pluginPath . DS . 'models' . DS . 'datasources' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
case 'controller':
App::import($type, 'AppController', false);
if ($plugin) {
App::import($type, $plugin . '.' . $plugin . 'AppController', false, array(), $pluginPath . DS . $pluginPath . '_app_controller.php');
$path = $pluginPath . DS . 'controllers' . DS;
}
return array('class' => $type, 'suffix' => $type, 'path' => $path);
break;
case 'component':
App::import('Core', 'Component', false);
if ($plugin) {
$path = $pluginPath . DS . 'controllers' . DS . 'components' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'lib':
if ($plugin) {
$path = $pluginPath . DS . 'libs' . DS;
}
return array('class' => null, 'suffix' => null, 'path' => $path);
break;
case 'view':
App::import('View', 'View', false);
if ($plugin) {
$path = $pluginPath . DS . 'views' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'helper':
if (!class_exists('AppHelper')) {
App::import($type, 'AppHelper', false);
}
if ($plugin) {
$path = $pluginPath . DS . 'views' . DS . 'helpers' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'shell':
if (!class_exists('Shell')) {
App::import($type, 'Shell', false);
}
if (!class_exists('AppShell')) {
App::import($type, 'AppShell', false);
}
if ($plugin) {
$path = $pluginPath . DS . 'console' . DS . 'shells' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'vendor':
if ($plugin) {
$path = $pluginPath . DS . 'vendors' . DS;
}
return array('class' => null, 'suffix' => null, 'path' => $path);
break;
default:
$type = $suffix = $path = null;
break;
}
return array('class' => null, 'suffix' => null, 'path' => null);
}
/**
* Returns default search paths.
*
* @param string $type type of object to be searched
* @return array list of paths
*/
private static function __paths($type) {
$type = strtolower($type);
$paths = array();
if ($type === 'core') {
return App::core('libs');
}
if (isset(self::${$type . 's'})) {
return self::${$type . 's'};
}
return $paths;
}
/**
* Removes file location from map if the file has been deleted.
*
* @param string $name name of object
* @param string $type type of object
* @param string $plugin camelized name of plugin
* @return void
*/
private static function __remove($name, $type, $plugin) {
if ($plugin) {
unset(self::$__map['Plugin'][$plugin][$type][$name]);
} else {
unset(self::$__map[$type][$name]);
}
}
/**
* Returns an array of filenames of PHP files in the given directory.
*
* @param string $path Path to scan for files
* @param string $suffix if false, return only directories. if string, match and return files
* @return array List of directories or files in directory
*/
private static function __list($path, $suffix = false, $extension = false) {
if (!class_exists('Folder')) {
require LIBS . 'folder.php';
}
$items = array();
$Folder = new Folder($path);
$contents = $Folder->read(false, true);
if (is_array($contents)) {
if (!$suffix) {
return $contents[0];
} else {
foreach ($contents[1] as $item) {
if (substr($item, - strlen($suffix)) === $suffix) {
if ($extension) {
$items[] = $item;
} else {
$items[] = substr($item, 0, strlen($item) - strlen($suffix));
}
}
}
}
}
return $items;
}
/**
* Object destructor.
*
* Writes cache file if changes have been made to the $__map or $__paths
*
* @return void
*/
public static function shutdown() {
if (self::$__cache) {
$core = App::core('cake');
unset(self::$__paths[rtrim($core[0], DS)]);
Cache::write('dir_map', array_filter(self::$__paths), '_cake_core_');
Cache::write('file_map', array_filter(self::$__map), '_cake_core_');
Cache::write('object_map', self::$__objects, '_cake_core_');
}
}
}

View file

@ -78,7 +78,7 @@ class MemcacheEngine extends CacheEngine {
}
if (!isset($this->__Memcache)) {
$return = false;
$this->__Memcache =& new Memcache();
$this->__Memcache = new Memcache();
foreach ($this->settings['servers'] as $server) {
list($host, $port) = $this->_parseServerString($server);
if ($this->__Memcache->addServer($host, $port)) {

View file

@ -99,7 +99,7 @@ class CakeLog {
* @return boolean success of configuration.
* @throws Exception
*/
static function config($key, $config) {
public static function config($key, $config) {
if (empty($config['engine'])) {
throw new Exception(__('Missing logger classname'));
}
@ -222,54 +222,4 @@ class CakeLog {
}
return true;
}
/**
* An error_handler that will log errors to file using CakeLog::write();
* You can control how verbose and what type of errors this error_handler will
* catch using `Configure::write('log', $value)`. See core.php for more information.
*
*
* @param integer $code Code of error
* @param string $description Error description
* @param string $file File on which error occurred
* @param integer $line Line that triggered the error
* @param array $context Context
* @return void
*/
public static function handleError($code, $description, $file = null, $line = null, $context = null) {
if ($code === 2048 || $code === 8192) {
return;
}
switch ($code) {
case E_PARSE:
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
$level = LOG_ERROR;
break;
case E_WARNING:
case E_USER_WARNING:
case E_COMPILE_WARNING:
case E_RECOVERABLE_ERROR:
$error = 'Warning';
$level = LOG_WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
$level = LOG_NOTICE;
break;
default:
return;
break;
}
$message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
CakeLog::write($level, $message);
}
}
if (!defined('DISABLE_DEFAULT_ERROR_HANDLING')) {
set_error_handler(array('CakeLog', 'handleError'));
}

View file

@ -550,7 +550,7 @@ class CakeRequest implements ArrayAccess {
* @param string $name Name of the header you want.
* @return mixed Either false on no header being set or the value of the header.
*/
public function header($name) {
public static function header($name) {
$name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
if (!empty($_SERVER[$name])) {
return $_SERVER[$name];
@ -582,7 +582,7 @@ class CakeRequest implements ArrayAccess {
* @param int $tldLength Number of segments your tld contains
* @return string Domain name without subdomains.
*/
function domain($tldLength = 1) {
public function domain($tldLength = 1) {
$segments = explode('.', $this->host());
$domain = array_slice($segments, -1 * ($tldLength + 1));
return implode('.', $domain);
@ -594,7 +594,7 @@ class CakeRequest implements ArrayAccess {
* @param int $tldLength Number of segments your tld contains.
* @return array of subdomains.
*/
function subdomains($tldLength = 1) {
public function subdomains($tldLength = 1) {
$segments = explode('.', $this->host());
return array_slice($segments, 0, -1 * ($tldLength + 1));
}
@ -629,6 +629,26 @@ class CakeRequest implements ArrayAccess {
return in_array($type, $acceptTypes);
}
/**
* Get the lanaguages accepted by the client, or check if a specific language is accepted.
*
* @param string $language The language to test.
* @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
*/
public static function acceptLanguage($language = null) {
$accepts = preg_split('/[;,]/', self::header('Accept-Language'));
foreach ($accepts as &$accept) {
$accept = strtolower($accept);
if (strpos($accept, '_') !== false) {
$accept = str_replace('_', '-', $accept);
}
}
if ($language === null) {
return $accepts;
}
return in_array($language, $accepts);
}
/**
* Provides a read/write accessor for `$this->data`. Allows you
* to use a syntax similar to `CakeSession` for reading post data.

View file

@ -141,7 +141,7 @@ class CakeSession {
* @param boolean $start Should session be started right now
*/
public static function init($base = null, $start = true) {
App::import('Core', array('Set', 'Security'));
App::import('Core', 'Security');
self::$time = time();
$checkAgent = Configure::read('Session.checkAgent');

View file

@ -0,0 +1,101 @@
<?php
/**
* IniFile
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs.controller.components
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Ini file configuration parser. Since IniFile uses parse_ini_file underneath,
* you should be aware that this class shares the same behavior, especially with
* regards to boolean and null values.
*
* @package cake.config
* @see http://php.net/parse_ini_file
*/
class IniFile implements ArrayAccess {
/**
* Values inside the ini file.
*
* @var array
*/
protected $_values = array();
/**
* Build and construct a new ini file parser, the parser will be a representation of the ini
* file as an object.
*
* @param string $filename Full path to the file to parse.
* @param string $section Only get one section.
*/
public function __construct($filename, $section = null) {
$contents = parse_ini_file($filename, true);
if (!empty($section) && isset($contents[$section])) {
$this->_values = $contents[$section];
} else {
$this->_values = $contents;
}
}
/**
* Get the contents of the ini file as a plain array.
*
* @return array
*/
public function asArray() {
return $this->_values;
}
/**
* Part of ArrayAccess implementation.
*
* @param string $name
*/
public function offsetExists($name) {
return isset($this->_values[$name]);
}
/**
* Part of ArrayAccess implementation.
*
* @param string $name
*/
public function offsetGet($name) {
if (!isset($this->_values[$name])) {
return null;
}
return $this->_values[$name];
}
/**
* Part of ArrayAccess implementation.
*
* @param string $name
*/
public function offsetSet($name, $value) {
throw new LogicException('You cannot modify an IniFile parse result.');
}
/**
* Part of ArrayAccess implementation.
*
* @param string $name
*/
public function offsetUnset($name) {
unset($this->_values[$name]);
}
}

File diff suppressed because it is too large Load diff

View file

@ -93,9 +93,8 @@ class Component extends Object {
*/
public function __get($name) {
if (isset($this->_componentMap[$name]) && !isset($this->{$name})) {
$this->{$name} = $this->_Collection->load(
$this->_componentMap[$name]['class'], $this->_componentMap[$name]['settings'], false
);
$settings = array_merge((array)$this->_componentMap[$name]['settings'], array('enabled' => false));
$this->{$name} = $this->_Collection->load($this->_componentMap[$name]['class'], $settings);
}
if (isset($this->{$name})) {
return $this->{$name};

View file

@ -56,14 +56,15 @@ class ComponentCollection extends ObjectCollection {
/**
* Loads/constructs a component. Will return the instance in the registry if it already exists.
* You can use `$settings['enabled'] = false` to disable callbacks on a component when loading it.
* Callbacks default to on. Disabled component methods work as normal, only callbacks are disabled.
*
* @param string $component Component name to load
* @param array $settings Settings for the component.
* @param boolean $enable Whether or not this component should be enabled by default
* @return Component A component object, Either the existing loaded component or a new one.
* @throws MissingComponentFileException, MissingComponentClassException when the component could not be found
*/
public function load($component, $settings = array(), $enable = true) {
public function load($component, $settings = array()) {
list($plugin, $name) = pluginSplit($component);
if (isset($this->_loaded[$name])) {
return $this->_loaded[$name];
@ -84,6 +85,7 @@ class ComponentCollection extends ObjectCollection {
}
}
$this->_loaded[$name] = new $componentClass($this, $settings);
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) {
$this->_enabled[] = $name;
}

View file

@ -280,8 +280,8 @@ class DbAcl extends Object implements AclInterface {
* @return void
*/
public function initialize($component) {
$component->Aro =& $this->Aro;
$component->Aco =& $this->Aco;
$component->Aro = $this->Aro;
$component->Aco = $this->Aco;
}
/**
@ -538,6 +538,15 @@ class IniAcl extends Object implements AclInterface {
*/
public $config = null;
/**
* The Set::classicExtract() path to the user/aro identifier in the
* acl.ini file. This path will be used to extract the string
* representation of a user used in the ini file.
*
* @var string
*/
public $userPath = 'User.username';
/**
* Initialize method
*
@ -599,6 +608,10 @@ class IniAcl extends Object implements AclInterface {
$this->config = $this->readConfigFile(CONFIGS . 'acl.ini.php');
}
$aclConfig = $this->config;
if (is_array($aro)) {
$aro = Set::classicExtract($aro, $this->userPath);
}
if (isset($aclConfig[$aro]['deny'])) {
$userDenies = $this->arrayTrim(explode(",", $aclConfig[$aro]['deny']));
@ -622,7 +635,7 @@ class IniAcl extends Object implements AclInterface {
foreach ($userGroups as $group) {
if (array_key_exists($group, $aclConfig)) {
if (isset($aclConfig[$group]['deny'])) {
$groupDenies=$this->arrayTrim(explode(",", $aclConfig[$group]['deny']));
$groupDenies = $this->arrayTrim(explode(",", $aclConfig[$group]['deny']));
if (array_search($aco, $groupDenies)) {
return false;
@ -645,43 +658,13 @@ class IniAcl extends Object implements AclInterface {
/**
* Parses an INI file and returns an array that reflects the INI file's section structure. Double-quote friendly.
*
* @param string $fileName File
* @param string $filename File
* @return array INI section structure
*/
public function readConfigFile($fileName) {
$fileLineArray = file($fileName);
foreach ($fileLineArray as $fileLine) {
$dataLine = trim($fileLine);
$firstChar = substr($dataLine, 0, 1);
if ($firstChar != ';' && $dataLine != '') {
if ($firstChar == '[' && substr($dataLine, -1, 1) == ']') {
$sectionName = preg_replace('/[\[\]]/', '', $dataLine);
} else {
$delimiter = strpos($dataLine, '=');
if ($delimiter > 0) {
$key = strtolower(trim(substr($dataLine, 0, $delimiter)));
$value = trim(substr($dataLine, $delimiter + 1));
if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
$value = substr($value, 1, -1);
}
$iniSetting[$sectionName][$key]=stripcslashes($value);
} else {
if (!isset($sectionName)) {
$sectionName = '';
}
$iniSetting[$sectionName][strtolower(trim($dataLine))]='';
}
}
}
}
return $iniSetting;
public function readConfigFile($filename) {
App::import('Core', 'config/IniFile');
$iniFile = new IniFile($filename);
return $iniFile->asArray();
}
/**

View file

@ -20,7 +20,8 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Router', 'Security'), false);
App::import('Core', 'Router', false);
App::import('Core', 'Security', false);
/**
* Authentication control component class
@ -322,7 +323,7 @@ class AuthComponent extends Component {
if (!$this->__setDefaults()) {
return false;
}
$request =& $controller->request;
$request = $controller->request;
$this->request->data = $controller->request->data = $this->hashPasswords($request->data);
$url = '';
@ -520,7 +521,6 @@ class AuthComponent extends Component {
$valid = $this->Acl->check($user, $this->action());
break;
case 'crud':
$this->mapActions();
if (!isset($this->actionMap[$this->request['action']])) {
trigger_error(
sprintf(__('Auth::startup() - Attempted access of un-mapped action "%1$s" in controller "%2$s"'), $this->request['action'], $this->request['controller']),
@ -535,7 +535,6 @@ class AuthComponent extends Component {
}
break;
case 'model':
$this->mapActions();
$action = $this->request['action'];
if (isset($this->actionMap[$action])) {
$action = $this->actionMap[$action];

View file

@ -810,7 +810,7 @@ class EmailComponent extends Component {
* @access private
*/
function _smtp() {
App::import('Core', array('CakeSocket'));
App::import('Core', 'CakeSocket');
$defaults = array(
'host' => 'localhost',

View file

@ -121,8 +121,8 @@ class RequestHandlerComponent extends Component {
public function initialize(&$controller, $settings = array()) {
$this->request = $controller->request;
$this->response = $controller->response;
if (isset($controller->params['url']['ext'])) {
$this->ext = $controller->params['url']['ext'];
if (isset($this->request->params['url']['ext'])) {
$this->ext = $this->request->params['url']['ext'];
}
if (empty($this->ext)) {
$accepts = $this->request->accepts();

View file

@ -17,7 +17,8 @@
* @since CakePHP(tm) v 0.10.8.2156
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('String', 'Security'));
App::import('Core', 'String', false);
App::import('Core', 'Security', false);
/**
* SecurityComponent
@ -618,10 +619,15 @@ class SecurityComponent extends Component {
}
unset($check['_Token']);
$locked = str_rot13($locked);
if (preg_match('/(\A|;|{|})O\:[0-9]+/', $locked)) {
return false;
}
$lockedFields = array();
$fields = Set::flatten($check);
$fieldList = array_keys($fields);
$locked = unserialize(str_rot13($locked));
$locked = unserialize($locked);
$multi = array();
foreach ($fieldList as $i => $key) {

View file

@ -22,8 +22,8 @@
* Include files
*/
App::import('Core', 'CakeResponse', false);
App::import('Core', 'ClassRegistry', false);
App::import('Controller', 'Component', false);
App::import('Core', 'CakeResponse', false);
App::import('View', 'View', false);
/**
@ -415,23 +415,21 @@ class Controller extends Object {
* @return void
*/
protected function __mergeVars() {
$pluginName = Inflector::camelize($this->plugin);
$pluginController = $pluginName . 'AppController';
$pluginName = $pluginController = $plugin = null;
if (is_subclass_of($this, 'AppController') || is_subclass_of($this, $pluginController)) {
if (!empty($this->plugin)) {
$pluginName = Inflector::camelize($this->plugin);
$pluginController = $pluginName . 'AppController';
if (!is_subclass_of($this, $pluginController)) {
$pluginController = null;
}
$plugin = $pluginName . '.';
}
if (is_subclass_of($this, 'AppController') || !empty($pluginController)) {
$appVars = get_class_vars('AppController');
$uses = $appVars['uses'];
$merge = array('components', 'helpers');
$plugin = null;
if (!empty($this->plugin)) {
$plugin = $pluginName . '.';
if (!is_subclass_of($this, $pluginController)) {
$pluginController = null;
}
} else {
$pluginController = null;
}
if ($uses == $this->uses && !empty($this->uses)) {
if (!in_array($plugin . $this->modelClass, $this->uses)) {
@ -443,50 +441,18 @@ class Controller extends Object {
array_unshift($this->uses, $plugin . $this->modelClass);
}
} elseif ($this->uses !== null || $this->uses !== false) {
$merge[] = 'uses';
}
foreach ($merge as $var) {
if (!empty($appVars[$var]) && is_array($this->{$var})) {
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})
);
}
}
$this->_mergeVars(array('uses'), 'AppController', false);
}
$this->_mergeVars($merge, 'AppController', true);
}
if ($pluginController && $pluginName != null) {
$appVars = get_class_vars($pluginController);
$uses = $appVars['uses'];
$merge = array('components', 'helpers');
if ($this->uses !== null || $this->uses !== false) {
$merge[] = 'uses';
}
foreach ($merge as $var) {
if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
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})
);
}
}
$this->_mergeVars(array('uses'), $pluginController, false);
}
$this->_mergeVars($merge, $pluginController);
}
}
@ -627,7 +593,7 @@ class Controller extends Object {
if ($this->persistModel === true) {
$this->_persist($modelClass, true, $this->{$modelClass});
$registry =& ClassRegistry::getInstance();
$registry = ClassRegistry::getInstance();
$this->_persist($modelClass . 'registry', true, $registry->__objects, 'registry');
}
} else {
@ -1039,7 +1005,7 @@ class Controller extends Object {
), E_USER_WARNING);
return array();
}
$options = array_merge($this->request->params, $this->params['url'], $this->passedArgs);
$options = array_merge($this->request->params, $this->request->query, $this->passedArgs);
if (isset($this->paginate[$object->alias])) {
$defaults = $this->paginate[$object->alias];
@ -1170,11 +1136,11 @@ class Controller extends Object {
'defaults' => array_merge(array('limit' => 20, 'step' => 1), $defaults),
'options' => $options
);
if (!isset($this->request['paging'])) {
$this->request['paging'] = array();
if (!isset($this->request->params['paging'])) {
$this->request->params['paging'] = array();
}
$this->request['paging'] = array_merge(
(array)$this->request['paging'],
$this->request->params['paging'] = array_merge(
(array)$this->request->params['paging'],
array($object->alias => $paging)
);

View file

@ -19,6 +19,7 @@
* @since Cake v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('View', 'Scaffold');
/**
* Scaffolding is a set of automatic actions for starting web development work faster.
@ -455,78 +456,3 @@ class Scaffold {
return $associations;
}
}
/**
* Scaffold View.
*
* @package cake
* @subpackage cake.cake.libs.controller
*/
App::import('View', 'Theme');
/**
* ScaffoldView provides specific view file loading features for scaffolded views.
*
* @package cake.libs.view
*/
class ScaffoldView extends ThemeView {
/**
* Override _getViewFileName Appends special scaffolding views in.
*
* @param string $name name of the view file to get.
* @return string action
*/
protected function _getViewFileName($name = null) {
if ($name === null) {
$name = $this->action;
}
$name = Inflector::underscore($name);
$prefixes = Configure::read('Routing.prefixes');
if (!empty($prefixes)) {
foreach ($prefixes as $prefix) {
if (strpos($name, $prefix . '_') !== false) {
$name = substr($name, strlen($prefix) + 1);
break;
}
}
}
if ($name === 'add') {
$name = 'edit';
}
$scaffoldAction = 'scaffold.' . $name;
if (!is_null($this->subDir)) {
$subDir = strtolower($this->subDir) . DS;
} else {
$subDir = null;
}
$names[] = $this->viewPath . DS . $subDir . $scaffoldAction;
$names[] = 'scaffolds' . DS . $subDir . $name;
$paths = $this->_paths($this->plugin);
$exts = array($this->ext);
if ($this->ext !== '.ctp') {
array_push($exts, '.ctp');
}
foreach ($exts as $ext) {
foreach ($paths as $path) {
foreach ($names as $name) {
if (file_exists($path . $name . $ext)) {
return $path . $name . $ext;
}
}
}
}
if ($name === 'scaffolds' . DS . $subDir . 'error') {
return LIBS . 'view' . DS . 'errors' . DS . 'scaffold_error.ctp';
}
throw new MissingViewException($paths[0] . $name . $this->ext);
}
}

View file

@ -236,11 +236,7 @@ class Debugger {
* @param array $context Context
* @return boolean true if error was handled
*/
public function handleError($code, $description, $file = null, $line = null, $context = null) {
if (error_reporting() == 0 || $code === 2048 || $code === 8192) {
return;
}
public function showError($code, $description, $file = null, $line = null, $context = null) {
$_this = Debugger::getInstance();
if (empty($file)) {
@ -295,13 +291,7 @@ class Debugger {
$data = compact(
'level', 'error', 'code', 'helpID', 'description', 'file', 'path', 'line', 'context'
);
echo self::_output($data);
if (Configure::read('log')) {
$tpl = $_this->_templates['log']['error'];
$options = array('before' => '{:', 'after' => '}');
CakeLog::write($level, String::insert($tpl, $data, $options));
}
echo $_this->outputError($data);
if ($error == 'Fatal Error') {
exit();
@ -585,11 +575,12 @@ class Debugger {
}
/**
* Renders error messages
* Takes a processed array of data from an error and displays it in the chosen format.
*
* @param array $data Data about the current error
* @param string $data
* @return void
*/
protected function _output($data = array()) {
public function outputError($data) {
$defaults = array(
'level' => 0,
'error' => 0,
@ -598,13 +589,14 @@ class Debugger {
'description' => '',
'file' => '',
'line' => 0,
'context' => array()
'context' => array(),
'start' => 2
);
$data += $defaults;
$files = $this->trace(array('start' => 2, 'format' => 'points'));
$files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
$code = $this->excerpt($files[0]['file'], $files[0]['line'] - 1, 1);
$trace = $this->trace(array('start' => 2, 'depth' => '20'));
$trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
$insertOpts = array('before' => '{:', 'after' => '}');
$context = array();
$links = array();
@ -672,20 +664,4 @@ class Debugger {
}
}
/**
* Invokes the given debugger object as the current error handler, taking over control from the
* previous handler in a stack-like hierarchy.
*
* @param object $debugger A reference to the Debugger object
* @access public
* @static
* @link http://book.cakephp.org/view/1191/Using-the-Debugger-Class
*/
function invoke(&$debugger) {
set_error_handler(array(&$debugger, 'handleError'));
}
}
if (!defined('DISABLE_DEFAULT_ERROR_HANDLING')) {
Debugger::invoke(Debugger::getInstance());
}

View file

@ -24,35 +24,21 @@
/**
* List of helpers to include
*/
App::import('Core', array('Router', 'CakeRequest', 'CakeResponse'));
App::import('Core', 'Router', false);
App::import('Core', 'CakeRequest', false);
App::import('Core', 'CakeResponse', false);
App::import('Controller', 'Controller', false);
/**
* Dispatcher translates URLs to controller-action-paramter triads.
*
* Dispatches the request, creating appropriate models and controllers.
* Dispatcher converts Requests into controller actions. It uses the dispatched Request
* to locate and load the correct controller. If found, the requested action is called on
* the controller.
*
* @package cake
* @subpackage cake.cake
*/
class Dispatcher {
/**
* Base URL
*
* @var string
* @access public
*/
public $base = false;
/**
* webroot path
*
* @var string
* @access public
*/
public $webroot = '/';
/**
* Current URL
*
@ -61,14 +47,6 @@ class Dispatcher {
*/
public $here = false;
/**
* the params for this request
*
* @var string
* @access public
*/
public $params = null;
/**
* The request object
*
@ -97,40 +75,32 @@ class Dispatcher {
}
/**
* Dispatches and invokes given URL, handing over control to the involved controllers, and then renders the
* results (if autoRender is set).
* Dispatches and invokes given Request, handing over control to the involved controller. If the controller is set
* to autoRender, via Controller::$autoRender, then Dispatcher will render the view.
*
* If no controller of given name can be found, invoke() shows error messages in
* the form of Missing Controllers information. It does the same with Actions (methods of Controllers are called
* Actions).
* Actions in CakePHP can be any public method on a controller, that is not declared in Controller. If you
* want controller methods to be public and in-accesible by URL, then prefix them with a `_`.
* For example `public function _loadPosts() { }` would not be accessible via URL. Private and protected methods
* are also not accessible via URL.
*
* @param mixed $url Either a string url or a CakeRequest object information to work on. If $url is a string
* It will be used to create the request object.
* If no controller of given name can be found, invoke() will throw an exception.
* If the controller is found, and the action is not found an exception will be thrown.
*
* @param CakeRequest $request Request object to dispatch.
* @param array $additionalParams Settings array ("bare", "return") which is melded with the GET and POST params
* @return boolean Success
* @throws MissingControllerException, MissingActionException, PrivateActionException if any of those error states
* are encountered.
*/
public function dispatch($url = null, $additionalParams = array()) {
if (is_array($url)) {
$url = $this->_extractParams($url, $additionalParams);
}
if ($url instanceof CakeRequest) {
$request = $url;
} else {
$request = new CakeRequest($url);
}
public function dispatch(CakeRequest $request, $additionalParams = array()) {
$this->here = $request->here;
if ($this->asset($request->url) || $this->cached($request->url)) {
return;
}
$request = $this->parseParams($request, $additionalParams);
$this->request = $request;
$controller = $this->_getController();
$controller = $this->_getController($request);
if (!is_object($controller)) {
Router::setRequestInfo($request);
@ -138,6 +108,27 @@ class Dispatcher {
'controller' => Inflector::camelize($request->params['controller']) . 'Controller'
));
}
Router::setRequestInfo($request);
if ($this->_isPrivateAction($request)) {
throw new PrivateActionException(array(
'controller' => Inflector::camelize($request->params['controller']) . "Controller",
'action' => $request->params['action']
));
}
return $this->_invoke($controller, $request);
}
/**
* Check if the request's action is marked as private, with an underscore, of if the request is attempting to
* directly accessing a prefixed action.
*
* @param CakeRequest $request The request to check
* @return boolean
*/
protected function _isPrivateAction($request) {
$privateAction = $request->params['action'][0] === '_';
$prefixes = Router::prefixes();
@ -149,17 +140,7 @@ class Dispatcher {
$privateAction = in_array($prefix, $prefixes);
}
}
Router::setRequestInfo($request);
if ($privateAction) {
throw new PrivateActionException(array(
'controller' => Inflector::camelize($request->params['controller']) . "Controller",
'action' => $request->params['action']
));
}
return $this->_invoke($controller, $request);
return $privateAction;
}
/**
@ -167,18 +148,17 @@ class Dispatcher {
* Triggers the controller action, and invokes the rendering if Controller::$autoRender is true and echo's the output.
* Otherwise the return value of the controller action are returned.
*
* @param object $controller Controller to invoke
* @param array $params Parameters with at least the 'action' to invoke
* @param boolean $missingAction Set to true if missing action should be rendered, false otherwise
* @param Controller $controller Controller to invoke
* @param CakeRequest $request The request object to invoke the controller for.
* @return string Output as sent by controller
* @throws MissingActionException when the action being called is missing.
*/
protected function _invoke(&$controller, $request) {
protected function _invoke(Controller $controller, CakeRequest $request) {
$controller->constructClasses();
$controller->startupProcess();
$methods = array_flip($controller->methods);
if (!isset($methods[$request->params['action']])) {
if ($controller->scaffold !== false) {
App::import('Controller', 'Scaffold', false);
@ -206,32 +186,20 @@ class Dispatcher {
}
/**
* Sets the params when $url is passed as an array to Object::requestAction();
* Merges the $url and $additionalParams and creates a string url.
* Applies Routing and additionalParameters to the request to be dispatched.
* If Routes have not been loaded they will be loaded, and app/config/routes.php will be run.
*
* @param array $url Array or request parameters
* @param array $additionalParams Array of additional parameters.
* @return string $url The generated url string.
*/
protected function _extractParams($url, $additionalParams = array()) {
$defaults = array('pass' => array(), 'named' => array(), 'form' => array());
$params = array_merge($defaults, $url, $additionalParams);
$this->params = $params;
$params += array('base' => false, 'url' => array());
return ltrim(Router::reverse($params), '/');
}
/**
* Returns array of GET and POST parameters. GET parameters are taken from given URL.
*
* @param CakeRequest $fromUrl CakeRequest object to mine for parameter information.
* @return array Parameters found in POST and GET.
* @param CakeRequest $request CakeRequest object to mine for parameter information.
* @param array $additionalParams An array of additional parameters to set to the request.
* Useful when Object::requestAction() is involved
* @return CakeRequest The request object with routing params set.
*/
public function parseParams(CakeRequest $request, $additionalParams = array()) {
$namedExpressions = Router::getNamedExpressions();
extract($namedExpressions);
include CONFIGS . 'routes.php';
if (count(Router::$routes) > 0) {
$namedExpressions = Router::getNamedExpressions();
extract($namedExpressions);
include CONFIGS . 'routes.php';
}
$params = Router::parse($request->url);
$request->addParams($params);
@ -248,17 +216,15 @@ class Dispatcher {
* @param array $params Array of parameters
* @return mixed name of controller if not loaded, or object if loaded
*/
protected function &_getController() {
$controller = false;
$ctrlClass = $this->__loadController($this->request);
protected function _getController($request) {
$ctrlClass = $this->_loadController($request);
if (!$ctrlClass) {
return $controller;
return false;
}
$ctrlClass .= 'Controller';
if (class_exists($ctrlClass)) {
$controller = new $ctrlClass($this->request);
return new $ctrlClass($request);
}
return $controller;
}
/**
@ -266,9 +232,8 @@ class Dispatcher {
*
* @param array $params Array of parameters
* @return string|bool Name of controller class name
* @access private
*/
function __loadController($request) {
protected function _loadController($request) {
$pluginName = $pluginPath = $controller = null;
if (!empty($request->params['plugin'])) {
$pluginName = $controller = Inflector::camelize($request->params['plugin']);

View file

@ -0,0 +1,213 @@
<?php
/**
* Error handler
*
* Provides Error Capturing for Framework errors.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 0.10.5.1732
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
*
* Error Handler provides basic error and exception handling for your application. It captures and
* handles all unhandled exceptions and errors. Displays helpful framework errors when debug > 1.
*
* ### Uncaught exceptions
*
* When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown
* and it is a type that ErrorHandler does not know about it will be treated as a 500 error.
*
* ### Implementing application specific exception handling
*
* You can implement application specific exception handling in one of a few ways. Each approach
* gives you different amounts of control over the exception handling process.
*
* - Set Configure::write('Exception.handler', 'YourClass::yourMethod');
* - Create AppController::appError();
* - Set Configure::write('Exception.renderer', 'YourClass');
*
* #### Create your own Exception handler with `Exception.handler`
*
* This gives you full control over the exception handling process. The class you choose should be
* loaded in your app/config/bootstrap.php, so its available to handle any exceptions. You can
* define the handler as any callback type. Using Exception.handler overrides all other exception
* handling settings and logic.
*
* #### Using `AppController::appError();`
*
* This controller method is called instead of the default exception rendering. It receives the
* thrown exception as its only argument. You should implement your error handling in that method.
* Using AppController::appError(), will superseed any configuration for Exception.renderer.
*
* #### Using a custom renderer with `Exception.renderer`
*
* If you don't want to take control of the exception handling, but want to change how exceptions are
* rendered you can use `Exception.renderer` to choose a class to render exception pages. By default
* `ExceptionRenderer` is used. Your custom exception renderer class should be placed in app/libs.
*
* Your custom renderer should expect an exception in its constructor, and implement a render method.
* Failing to do so will cause additional errors.
*
* #### Logging exceptions
*
* Using the built-in exception handling, you can log all the exceptions
* that are dealt with by ErrorHandler by setting `Exception.log` to true in your core.php.
* Enabling this will log every exception to CakeLog and the configured loggers.
*
* ### PHP errors
*
* Error handler also provides the built in features for handling php errors (trigger_error).
* While in debug mode, errors will be output to the screen using debugger. While in production mode,
* errors will be logged to CakeLog. You can control which errors are logged by setting
* `Error.level` in your core.php.
*
* #### Logging errors
*
* When ErrorHandler is used for handling errors, you can enable error logging by setting `Error.log` to true.
* This will log all errors to the configured log handlers.
*
* #### Controlling what errors are logged/displayed
*
* You can control which errors are logged / displayed by ErrorHandler by setting `Error.level`. Setting this
* to one or a combination of a few of the E_* constants will only enable the specified errors.
*
* e.g. `Configure::write('Error.level', E_ALL & ~E_NOTICE);`
*
* Would enable handling for all non Notice errors.
*
* @package cake
* @subpackage cake.cake.libs
* @see ExceptionRenderer for more information on how to customize exception rendering.
*/
class ErrorHandler {
/**
* Set as the default exception handler by the CakePHP bootstrap process.
*
* This will either use an AppError class if your application has one,
* or use the default ExceptionRenderer.
*
* @return void
* @see http://php.net/manual/en/function.set-exception-handler.php
*/
public static function handleException(Exception $exception) {
App::import('Core', 'error/ExceptionRenderer');
$config = Configure::read('Exception');
if (!empty($config['log'])) {
if (!class_exists('CakeLog')) {
require LIBS . 'cake_log.php';
}
CakeLog::write(LOG_ERR, '[' . get_class($exception) . '] ' . $exception->getMessage());
}
if ($config['renderer'] !== 'ExceptionRenderer') {
App::import('Lib', $config['renderer']);
}
$error = new $config['renderer']($exception);
$error->render();
}
/**
* Set as the default error handler by CakePHP. Use Configure::write('Error.handler', $callback), to use your own
* error handling methods. This function will use Debugger to display errors when debug > 0. And
* will log errors to CakeLog, when debug == 0.
*
* You can use Configure::write('Error.level', $value); to set what type of errors will be handled here.
* Stack traces for errors can be enabled with Configure::write('Error.trace', true);
*
* @param integer $code Code of error
* @param string $description Error description
* @param string $file File on which error occurred
* @param integer $line Line that triggered the error
* @param array $context Context
* @return boolean true if error was handled
*/
public static function handleError($code, $description, $file = null, $line = null, $context = null) {
$errorConfig = Configure::read('Error');
list($error, $log) = self::_mapErrorCode($code);
$debug = Configure::read('debug');
if ($debug) {
if (!class_exists('Debugger')) {
require LIBS . 'debugger.php';
}
$data = array(
'level' => $log,
'code' => $code,
'error' => $error,
'description' => $description,
'file' => $file,
'line' => $line,
'context' => $context,
'start' => 2,
'path' => Debugger::trimPath($file)
);
return Debugger::getInstance()->outputError($data);
} else {
if (!class_exists('CakeLog')) {
require LIBS . 'cake_log.php';
}
$message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
if (!empty($errorConfig['trace'])) {
if (!class_exists('Debugger')) {
require LIBS . 'debugger.php';
}
$trace = Debugger::trace(array('start' => 1, 'format' => 'log'));
$message .= "\nTrace:\n" . $trace . "\n";
}
return CakeLog::write($log, $message);
}
}
/**
* Map an error code into an Error word, and log location.
*
* @param int $code Error code to map
* @return array Array of error word, and log location.
*/
protected static function _mapErrorCode($code) {
switch ($code) {
case E_PARSE:
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
$log = LOG_ERROR;
break;
case E_WARNING:
case E_USER_WARNING:
case E_COMPILE_WARNING:
case E_RECOVERABLE_ERROR:
$error = 'Warning';
$log = LOG_WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
$log = LOG_NOTICE;
break;
case E_STRICT:
$error = 'Strict';
$log = LOG_NOTICE;
break;
case E_DEPRECATED:
$error = 'Deprecated';
$log = LOG_NOTICE;
break;
}
return array($error, $log);
}
}

View file

@ -1,8 +1,9 @@
<?php
/**
* Error handler
* Exception Renderer
*
* Provides Error Capturing for Framework errors.
* Provides Exception rendering features. Which allow exceptions to be rendered
* as HTML pages.
*
* PHP 5
*
@ -16,43 +17,38 @@
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 0.10.5.1732
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Error Handler.
* Exception Renderer.
*
* Captures and handles all unhandled exceptions. Displays helpful framework errors when debug > 1.
* When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown
* and it is a type that ErrorHandler does not know about it will be treated as a 500 error.
* and it is a type that ExceptionHandler does not know about it will be treated as a 500 error.
*
* ### Implementing application specific exception handling
* ### Implementing application specific exception rendering
*
* You can implement application specific exception handling in one of a few ways:
*
* - Create a AppController::appError();
* - Create an AppError class.
* - Create a subclass of ExceptionRenderer and configure it to be the `Exception.renderer`
*
* #### Using AppController::appError();
*
* This controller method is called instead of the default exception handling. It receives the
* thrown exception as its only argument. You should implement your error handling in that method.
*
* #### Using an AppError class
* #### Using a subclass of ExceptionRenderer
*
* This approach gives more flexibility and power in how you handle exceptions. You can create
* `app/libs/app_error.php` and create a class called `AppError`. The core ErrorHandler class
* will attempt to construct this class and let it handle the exception. This provides a more
* flexible way to handle exceptions in your application.
*
* Finally, in your `app/config/bootstrap.php` you can configure use `set_exception_handler()`
* to take total control over application exception handling.
* Using a subclass of ExceptionRenderer gives you full control over how Exceptions are rendered, you
* can configure your class in your core.php, with `Configure::write('Exception.renderer', 'MyClass');`
* You should place any custom exception renderers in `app/libs`.
*
* @package cake
* @subpackage cake.cake.libs
*/
class ErrorHandler {
class ExceptionRenderer {
/**
* Controller instance.
@ -118,7 +114,7 @@ class ErrorHandler {
if (Configure::read('debug') == 0) {
$parentClass = get_parent_class($this);
if ($parentClass != 'ErrorHandler') {
if ($parentClass != __CLASS__) {
$method = 'error400';
}
$parentMethods = (array)get_class_methods($parentClass);
@ -157,34 +153,15 @@ class ErrorHandler {
return $controller;
}
/**
* Set as the default exception handler by the CakePHP bootstrap process.
*
* This will either use an AppError class if your application has one,
* or use the default ErrorHandler.
*
* @return void
* @see http://php.net/manual/en/function.set-exception-handler.php
*/
public static function handleException(Exception $exception) {
if (file_exists(APP . 'app_error.php') || class_exists('AppError')) {
if (!class_exists('AppError')) {
require(APP . 'app_error.php');
}
$AppError = new AppError($exception);
return $AppError->render();
}
$error = new ErrorHandler($exception);
$error->render();
}
/**
* Renders the response for the exception.
*
* @return void
*/
public function render() {
call_user_func_array(array($this, $this->method), array($this->error));
if ($this->method) {
call_user_func_array(array($this, $this->method), array($this->error));
}
}
/**
@ -254,4 +231,4 @@ class ErrorHandler {
$this->controller->afterFilter();
$this->controller->response->send();
}
}
}

View file

@ -93,7 +93,7 @@ class File {
* @access private
*/
function __construct($path, $create = false, $mode = 0755) {
$this->Folder =& new Folder(dirname($path), $create, $mode);
$this->Folder = new Folder(dirname($path), $create, $mode);
if (!is_dir($path)) {
$this->name = basename($path);
}

View file

@ -244,7 +244,7 @@ class Folder {
* @static
*/
function isWindowsPath($path) {
return (bool)preg_match('/^[A-Z]:\\\\/i', $path);
return (preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) == '\\\\');
}
/**
@ -256,7 +256,7 @@ class Folder {
* @static
*/
function isAbsolute($path) {
return !empty($path) && ($path[0] === '/' || preg_match('/^[A-Z]:\\\\/i', $path));
return !empty($path) && ($path[0] === '/' || preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) == '\\\\');
}
/**

View file

@ -17,7 +17,8 @@
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('CakeSocket', 'Set', 'Router'));
App::import('Core', 'CakeSocket');
App::import('Core', 'Router');
/**
* Cake network socket connection class.

View file

@ -21,7 +21,8 @@
/**
* Included libraries.
*/
App::import('Core', array('l10n', 'Multibyte'));
App::import('Core', 'L10n');
App::import('Core', 'Multibyte');
/**
* I18n handles translation of Text and time format strings.
@ -139,11 +140,11 @@ class I18n {
$_this->domain = $domain . '_' . $_this->l10n->lang;
if (empty($_this->__domains[$domain][$_this->__lang])) {
if (!isset($_this->__domains[$domain][$_this->__lang])) {
$_this->__domains[$domain][$_this->__lang] = Cache::read($_this->domain, '_cake_core_');
}
if (empty($_this->__domains[$domain][$_this->__lang][$_this->category])) {
if (!isset($_this->__domains[$domain][$_this->__lang][$_this->category])) {
$_this->__bindTextDomain($domain);
Cache::write($_this->domain, $_this->__domains[$domain][$_this->__lang], '_cake_core_');
}

View file

@ -17,6 +17,7 @@
* @since CakePHP(tm) v 1.2.0.4116
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'CakeRequest');
/**
* Localization
@ -407,13 +408,8 @@ class L10n {
* @access private
*/
function __autoLanguage() {
$_detectableLanguages = preg_split('/[,;]/', env('HTTP_ACCEPT_LANGUAGE'));
$_detectableLanguages = CakeRequest::acceptLanguage();
foreach ($_detectableLanguages as $key => $langKey) {
$langKey = strtolower($langKey);
if (strpos($langKey, '_') !== false) {
$langKey = str_replace('_', '-', $langKey);
}
if (isset($this->__l10nCatalog[$langKey])) {
$this->__setLanguage($langKey);
return true;

View file

@ -67,9 +67,6 @@ class FileLog implements CakeLogInterface {
$filename = $this->_path . $type . '.log';
}
$output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
$log = new SplFileObject($filename, 'a+');
if ($log->isWritable()) {
return $log->fwrite($output);
}
return file_put_contents($filename, $output, FILE_APPEND);
}
}

View file

@ -53,7 +53,7 @@ class MagicDb extends Object {
if (is_array($magicDb) || strpos($magicDb, '# FILE_ID DB') === 0) {
$data = $magicDb;
} else {
$File =& new File($magicDb);
$File = new File($magicDb);
if (!$File->exists()) {
return false;
}
@ -155,7 +155,7 @@ class MagicDb extends Object {
}
$matches = array();
$MagicFileResource =& new MagicFileResource($file);
$MagicFileResource = new MagicFileResource($file);
foreach ($this->db['database'] as $format) {
$magic = $format[0];
$match = $MagicFileResource->test($magic);
@ -201,7 +201,7 @@ class MagicFileResource extends Object{
*/
public function __construct($file) {
if (file_exists($file)) {
$this->resource =& new File($file);
$this->resource = new File($file);
} else {
$this->resource = $file;
}

View file

@ -64,8 +64,8 @@ class BehaviorCollection extends ObjectCollection {
$this->modelName = $modelName;
if (!empty($behaviors)) {
foreach (Set::normalize($behaviors) as $behavior => $config) {
$this->load($behavior, $config);
foreach (BehaviorCollection::normalizeObjectArray($behaviors) as $behavior => $config) {
$this->load($config['class'], $config['settings']);
}
}
}
@ -81,15 +81,16 @@ class BehaviorCollection extends ObjectCollection {
}
/**
* Loads a behavior into the collection.
* Loads a behavior into the collection. You can use use `$config['enabled'] = false`
* to load a behavior with callbacks disabled. By default callbacks are enabled. Disable behaviors
* can still be used as normal.
*
* @param string $behavior CamelCased name of the behavior to load
* @param array $config Behavior configuration parameters
* @param boolean $enable Whether or not this helper should be enabled by default
* @return boolean True on success, false on failure
* @throws MissingBehaviorFileException or MissingBehaviorClassException when a behavior could not be found.
*/
public function load($behavior, $config = array(), $enable = true) {
public function load($behavior, $config = array()) {
list($plugin, $name) = pluginSplit($behavior);
$class = $name . 'Behavior';

View file

@ -121,7 +121,7 @@ class ContainableBehavior extends ModelBehavior {
$mandatory = array();
foreach ($containments['models'] as $name => $model) {
$instance =& $model['instance'];
$instance = $model['instance'];
$needed = $this->fieldDependencies($instance, $map, false);
if (!empty($needed)) {
$mandatory = array_merge($mandatory, $needed);
@ -431,7 +431,7 @@ class ContainableBehavior extends ModelBehavior {
public function containmentsMap($containments) {
$map = array();
foreach ($containments['models'] as $name => $model) {
$instance =& $model['instance'];
$instance = $model['instance'];
foreach ($this->types as $type) {
foreach ($instance->{$type} as $assoc => $options) {
if (isset($model['keep'][$assoc])) {

View file

@ -52,7 +52,7 @@ class TranslateBehavior extends ModelBehavior {
* @return mixed
*/
public function setup(&$model, $config = array()) {
$db =& ConnectionManager::getDataSource($model->useDbConfig);
$db = ConnectionManager::getDataSource($model->useDbConfig);
if (!$db->connected) {
trigger_error(
sprintf(__('Datasource %s for TranslateBehavior of model %s is not connected'), $model->useDbConfig, $model->alias),
@ -91,8 +91,8 @@ class TranslateBehavior extends ModelBehavior {
if (empty($locale)) {
return $query;
}
$db =& ConnectionManager::getDataSource($model->useDbConfig);
$RuntimeModel =& $this->translateModel($model);
$db = ConnectionManager::getDataSource($model->useDbConfig);
$RuntimeModel = $this->translateModel($model);
if (!empty($RuntimeModel->tablePrefix)) {
$tablePrefix = $RuntimeModel->tablePrefix;
} else {

View file

@ -17,7 +17,8 @@
* @since CakePHP(tm) v 1.2.0.5550
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Model', 'ConnectionManager'));
App::import('Core', 'Model');
App::import('Core', 'ConnectionManager');
/**
* Base Class for Schema management

View file

@ -17,7 +17,7 @@
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Set', 'String'));
App::import('Core', 'String');
/**
* DboSource
@ -612,7 +612,7 @@ class DboSource extends DataSource {
if (PHP_SAPI != 'cli') {
App::import('Core', 'View');
$controller = null;
$View =& new View($controller, false);
$View = new View($controller, false);
$View->set('logs', array($this->configKeyName => $log));
echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
} else {

View file

@ -23,7 +23,9 @@
/**
* Included libs
*/
App::import('Core', array('ClassRegistry', 'Validation', 'Set', 'String'));
App::import('Core', 'ClassRegistry', false);
App::import('Core', 'Validation', false);
App::import('Core', 'String', false);
App::import('Model', 'BehaviorCollection', false);
App::import('Model', 'ModelBehavior', false);
App::import('Model', 'ConnectionManager', false);
@ -438,27 +440,15 @@ class Model extends Object {
}
if (is_subclass_of($this, 'AppModel')) {
$appVars = get_class_vars('AppModel');
$merge = array('_findMethods');
if ($this->actsAs !== null || $this->actsAs !== false) {
$merge[] = 'actsAs';
}
$parentClass = get_parent_class($this);
if (strtolower($parentClass) !== 'appmodel') {
$parentVars = get_class_vars($parentClass);
foreach ($merge as $var) {
if (isset($parentVars[$var]) && !empty($parentVars[$var])) {
$appVars[$var] = Set::merge($appVars[$var], $parentVars[$var]);
}
}
}
foreach ($merge as $var) {
if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
$this->{$var} = Set::merge($appVars[$var], $this->{$var});
}
if ($parentClass !== 'AppModel') {
$this->_mergeVars($merge, $parentClass);
}
$this->_mergeVars($merge, 'AppModel');
}
$this->Behaviors = new BehaviorCollection();
@ -629,9 +619,9 @@ class Model extends Object {
*
* Example: Turn off the associated Model Support request,
* to temporarily lighten the User model:
*
*
* `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
*
*
* unbound models that are not made permanent will reset with the next call to Model::find()
*
* @param array $params Set of bindings to unbind (indexed by binding type)
@ -1636,7 +1626,7 @@ class Model extends Object {
}
if ($options['atomic'] && $options['validate'] !== 'only') {
$db->begin($this);
$transactionBegun = $db->begin($this);
}
if (Set::numeric(array_keys($data))) {
@ -1676,8 +1666,12 @@ class Model extends Object {
break;
default:
if ($options['atomic']) {
if ($validates && ($db->commit($this) !== false)) {
return true;
if ($validates) {
if ($transactionBegun) {
return $db->commit($this) !== false;
} else {
return true;
}
}
$db->rollback($this);
return false;
@ -1787,7 +1781,11 @@ class Model extends Object {
default:
if ($options['atomic']) {
if ($validates) {
return ($db->commit($this) !== false);
if ($transactionBegun) {
return $db->commit($this) !== false;
} else {
return true;
}
} else {
$db->rollback($this);
}
@ -1870,7 +1868,7 @@ class Model extends Object {
));
}
if ($db->delete($this)) {
if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
if (!empty($this->belongsTo)) {
$this->updateCounterCache($keys[$this->alias]);
}

View file

@ -67,7 +67,7 @@ class Object {
return false;
}
if (!class_exists('dispatcher')) {
require CAKE . 'dispatcher.php';
require LIBS . 'dispatcher.php';
}
if (in_array('return', $extra, true)) {
$extra = array_merge($extra, array('return' => 0, 'autoRender' => 1));
@ -75,9 +75,21 @@ class Object {
if (is_array($url) && !isset($extra['url'])) {
$extra['url'] = array();
}
$params = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
$dispatcher = new Dispatcher;
return $dispatcher->dispatch($url, $params);
$extra = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
if (is_string($url)) {
$request = new CakeRequest($url);
} elseif (is_array($url)) {
$params = $url + array('pass' => array(), 'named' => array(), 'base' => false);
$params = array_merge($params, $extra);
$request = new CakeRequest(Router::reverse($params), false);
if (isset($params['data'])) {
$request->data = $params['data'];
}
}
$dispatcher = new Dispatcher();
return $dispatcher->dispatch($request, $extra);
}
/**
@ -186,6 +198,36 @@ class Object {
}
}
/**
* Merges this objects $property with the property in $class' definition.
* This classes value for the property will be merged on top of $class'
*
* This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine
* this method as an empty function.
*
* @param array $properties The name of the properties to merge.
* @param sting $class The class to merge the property with.
* @param boolean $normalize Set to true to run the properties through Set::normalize() before merging.
* @return void
*/
protected function _mergeVars($properties, $class, $normalize = true) {
$classProperties = get_class_vars($class);
foreach ($properties as $var) {
if (
isset($classProperties[$var]) &&
!empty($classProperties[$var]) &&
is_array($this->{$var}) &&
$this->{$var} != $classProperties[$var]
) {
if ($normalize) {
$classProperties[$var] = Set::normalize($classProperties[$var]);
$this->{$var} = Set::normalize($this->{$var});
}
$this->{$var} = Set::merge($classProperties[$var], $this->{$var});
}
}
}
/**
* You should choose a unique name for the persistent file
*

View file

@ -38,12 +38,14 @@ abstract class ObjectCollection {
/**
* Loads a new object onto the collection. Can throw a variety of exceptions
*
* Implementations of this class support a `$options['callbacks']` flag which enables/disables
* a loaded object.
*
* @param string $name Name of object to load.
* @param array $options Array of configuration options for the object to be constructed.
* @param boolean $enable Whether or not this helper should be enabled by default
* @return object the constructed object
*/
abstract public function load($name, $options = array(), $enable = true);
abstract public function load($name, $options = array());
/**
* Trigger a callback method on every object in the collection.

View file

@ -886,10 +886,9 @@ class Router {
*
* @param array $url A url that didn't match any routes
* @return string A generated url for the array
* @access protected
* @see Router::url()
*/
function _handleNoRoute($url) {
protected static function _handleNoRoute($url) {
$named = $args = array();
$skip = array_merge(
array('bare', 'action', 'controller', 'plugin', 'prefix'),

View file

@ -140,9 +140,8 @@ class Helper extends Object {
*/
public function __get($name) {
if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
$this->{$name} = $this->_View->loadHelper(
$this->_helperMap[$name]['class'], $this->_helperMap[$name]['settings'], false
);
$settings = array_merge((array)$this->_helperMap[$name]['settings'], array('enabled' => false));
$this->{$name} = $this->_View->loadHelper($this->_helperMap[$name]['class'], $settings);
}
if (isset($this->{$name})) {
return $this->{$name};
@ -356,14 +355,13 @@ class Helper extends Object {
if (!is_array($exclude)) {
$exclude = array();
}
$keys = array_diff(array_keys($options), array_merge($exclude, array('escape')));
$values = array_intersect_key(array_values($options), $keys);
$filtered = array_diff_key($options, array_merge(array_flip($exclude), array('escape' => true)));
$escape = $options['escape'];
$attributes = array();
foreach ($keys as $index => $key) {
if ($values[$index] !== false && $values[$index] !== null) {
$attributes[] = $this->__formatAttribute($key, $values[$index], $escape);
foreach ($filtered as $key => $value) {
if ($value !== false && $value !== null) {
$attributes[] = $this->__formatAttribute($key, $value, $escape);
}
}
$out = implode(' ', $attributes);
@ -801,9 +799,10 @@ class Helper extends Object {
*
* Overridden in subclasses.
*
* @param string $viewFile The view file that is going to be rendered
* @return void
*/
public function beforeRender() {
public function beforeRender($viewFile) {
}
/**
@ -812,9 +811,10 @@ class Helper extends Object {
*
* Overridden in subclasses.
*
* @param string $viewFile The view file that was rendered.
* @return void
*/
public function afterRender() {
public function afterRender($viewFile) {
}
/**
@ -822,9 +822,10 @@ class Helper extends Object {
*
* Overridden in subclasses.
*
* @param string $layoutFile The layout about to be rendered.
* @return void
*/
public function beforeLayout() {
public function beforeLayout($layoutFile) {
}
/**
@ -832,9 +833,10 @@ class Helper extends Object {
*
* Overridden in subclasses.
*
* @param string $layoutFile The layout file that was rendered.
* @return void
*/
public function afterLayout() {
public function afterLayout($layoutFile) {
}
/**

View file

@ -38,14 +38,16 @@ class HelperCollection extends ObjectCollection {
/**
* Loads/constructs a helper. Will return the instance in the registry if it already exists.
* By setting `$enable` to false you can disable callbacks for a helper. Alternatively you
* can set `$settings['enabled'] = false` to disable callbacks. This alias is provided so that when
* declaring $helpers arrays you can disable callbacks on helpers.
*
* @param string $helper Helper name to load
* @param array $settings Settings for the helper.
* @param boolean $enable Whether or not this helper should be enabled by default
* @return Helper A helper object, Either the existing loaded helper or a new one.
* @throws MissingHelperFileException, MissingHelperClassException when the helper could not be found
*/
public function load($helper, $settings = array(), $enable = true) {
public function load($helper, $settings = array()) {
list($plugin, $name) = pluginSplit($helper, true);
if (isset($this->_loaded[$name])) {
@ -72,7 +74,7 @@ class HelperCollection extends ObjectCollection {
foreach ($vars as $var) {
$this->_loaded[$name]->{$var} = $this->_View->{$var};
}
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) {
$this->_enabled[] = $name;
}

View file

@ -32,29 +32,44 @@ class CacheHelper extends AppHelper {
/**
* Array of strings replaced in cached views.
* The strings are found between <cake:nocache><cake:nocache> in views
* The strings are found between `<!--nocache--><!--/nocache-->` in views
*
* @var array
* @access private
*/
private $__replace = array();
protected $_replace = array();
/**
* Array of string that are replace with there var replace above.
* The strings are any content inside <cake:nocache><cake:nocache> and includes the tags in views
* The strings are any content inside `<!--nocache--><!--/nocache-->` and includes the tags in views
*
* @var array
* @access private
*/
private $__match = array();
protected $_match = array();
/**
* cache action time
* Parses the view file and stores content for cache file building.
*
* @var object
* @access public
* @return void
*/
public $cacheAction;
public function afterRender($viewFile) {
$caching = (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true);
if ($caching) {
$this->cache($viewFile, $this->_View->output, false);
}
}
/**
* Parses the layout file and stores content for cache file building.
*
* @return void
*/
public function afterLayout($layoutFile) {
$caching = (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true);
if ($caching) {
$this->cache($layoutFile, $this->_View->output, true);
}
$this->_View->output = preg_replace('/<!--\/?nocache-->/', '', $this->_View->output);
}
/**
* Main method used to cache a view
@ -64,11 +79,13 @@ class CacheHelper extends AppHelper {
* @param boolean $cache Whether or not a cache file should be written.
* @return string view ouput
*/
function cache($file, $out, $cache = false) {
public function cache($file, $out, $cache = false) {
$cacheTime = 0;
$useCallbacks = false;
if (is_array($this->cacheAction)) {
$keys = array_keys($this->cacheAction);
$cacheAction = $this->_View->cacheAction;
if (is_array($cacheAction)) {
$keys = array_keys($cacheAction);
$index = null;
foreach ($keys as $action) {
@ -82,12 +99,12 @@ class CacheHelper extends AppHelper {
$index = 'index';
}
$options = $this->cacheAction;
if (isset($this->cacheAction[$index])) {
if (is_array($this->cacheAction[$index])) {
$options = array_merge(array('duration' => 0, 'callbacks' => false), $this->cacheAction[$index]);
$options = $cacheAction;
if (isset($cacheAction[$index])) {
if (is_array($cacheAction[$index])) {
$options = array_merge(array('duration' => 0, 'callbacks' => false), $cacheAction[$index]);
} else {
$cacheTime = $this->cacheAction[$index];
$cacheTime = $cacheAction[$index];
}
}
if (isset($options['duration'])) {
@ -97,14 +114,14 @@ class CacheHelper extends AppHelper {
$useCallbacks = $options['callbacks'];
}
} else {
$cacheTime = $this->cacheAction;
$cacheTime = $cacheAction;
}
if ($cacheTime != '' && $cacheTime > 0) {
$this->__parseFile($file, $out);
$this->_parseFile($file, $out);
if ($cache === true) {
$cached = $this->__parseOutput($out);
$this->__writeFile($cached, $cacheTime, $useCallbacks);
$cached = $this->_parseOutput($out);
$this->_writeFile($cached, $cacheTime, $useCallbacks);
}
return $out;
} else {
@ -117,22 +134,21 @@ class CacheHelper extends AppHelper {
*
* @param string $file The filename that needs to be parsed.
* @param string $cache The cached content
* @access private
*/
function __parseFile($file, $cache) {
protected function _parseFile($file, $cache) {
if (is_file($file)) {
$file = file_get_contents($file);
} elseif ($file = fileExistsInPath($file)) {
$file = file_get_contents($file);
}
preg_match_all('/(<cake:nocache>(?<=<cake:nocache>)[\\s\\S]*?(?=<\/cake:nocache>)<\/cake:nocache>)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
preg_match_all('/(?<=<cake:nocache>)([\\s\\S]*?)(?=<\/cake:nocache>)/i', $file, $fileResult, PREG_PATTERN_ORDER);
preg_match_all('/(<!--nocache-->(?<=<!--nocache-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
preg_match_all('/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', $file, $fileResult, PREG_PATTERN_ORDER);
$fileResult = $fileResult[0];
$outputResult = $outputResult[0];
if (!empty($this->__replace)) {
if (!empty($this->_replace)) {
foreach ($outputResult as $i => $element) {
$index = array_search($element, $this->__match);
$index = array_search($element, $this->_match);
if ($index !== false) {
unset($outputResult[$i]);
}
@ -144,8 +160,8 @@ class CacheHelper extends AppHelper {
$i = 0;
foreach ($fileResult as $cacheBlock) {
if (isset($outputResult[$i])) {
$this->__replace[] = $cacheBlock;
$this->__match[] = $outputResult[$i];
$this->_replace[] = $cacheBlock;
$this->_match[] = $outputResult[$i];
}
$i++;
}
@ -156,13 +172,12 @@ class CacheHelper extends AppHelper {
* Parse the output and replace cache tags
*
* @param string $cache Output to replace content in.
* @return string with all replacements made to <cake:nocache><cake:nocache>
* @access private
* @return string with all replacements made to <!--nocache--><!--nocache-->
*/
function __parseOutput($cache) {
protected function _parseOutput($cache) {
$count = 0;
if (!empty($this->__match)) {
foreach ($this->__match as $found) {
if (!empty($this->_match)) {
foreach ($this->_match as $found) {
$original = $cache;
$length = strlen($found);
$position = 0;
@ -172,7 +187,7 @@ class CacheHelper extends AppHelper {
if ($position !== false) {
$cache = substr($original, 0, $position);
$cache .= $this->__replace[$count];
$cache .= $this->_replace[$count];
$cache .= substr($original, $position + $length);
} else {
break;
@ -191,9 +206,8 @@ class CacheHelper extends AppHelper {
* @param string $content view content to write to a cache file.
* @param sting $timestamp Duration to set for cache file.
* @return boolean success of caching view.
* @access private
*/
function __writeFile($content, $timestamp, $useCallbacks = false) {
protected function _writeFile($content, $timestamp, $useCallbacks = false) {
$now = time();
if (is_numeric($timestamp)) {
@ -213,36 +227,28 @@ class CacheHelper extends AppHelper {
$cache = $cache . '.php';
$file = '<!--cachetime:' . $cacheTime . '--><?php';
if (empty($this->plugin)) {
if (empty($this->_View->plugin)) {
$file .= '
App::import(\'Controller\', \'' . $this->controllerName. '\');
App::import(\'Controller\', \'' . $this->_View->name. '\');
';
} else {
$file .= '
App::import(\'Controller\', \'' . $this->plugin . '.' . $this->controllerName. '\');
App::import(\'Controller\', \'' . $this->_View->plugin . '.' . $this->_View->name. '\');
';
}
$file .= '$controller =& new ' . $this->controllerName . 'Controller();
$controller->plugin = $this->plugin = \''.$this->plugin.'\';
$controller->helpers = $this->helpers = unserialize(\'' . serialize($this->helpers) . '\');
$controller->base = $this->base = \'' . $this->base . '\';
$controller->layout = $this->layout = \'' . $this->layout. '\';
$controller->webroot = $this->webroot = \'' . $this->webroot . '\';
$controller->here = $this->here = \'' . $this->here . '\';
$controller->params = $this->params = unserialize(\'' . str_replace("'", "\\'", serialize($this->params)) . '\');
$file .= '$controller = new ' . $this->_View->name . 'Controller();
$controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
$controller->helpers = $this->helpers = unserialize(\'' . serialize($this->_View->helpers) . '\');
$controller->layout = $this->layout = \'' . $this->_View->layout. '\';
$controller->request = $this->request = unserialize(\'' . str_replace("'", "\\'", serialize($this->request)) . '\');
$controller->action = $this->action = unserialize(\'' . serialize($this->action) . '\');
$controller->data = $this->data = unserialize(\'' . str_replace("'", "\\'", serialize($this->data)) . '\');
$controller->theme = $this->theme = \'' . $this->theme . '\';
Router::setRequestInfo($this->params);';
$controller->theme = $this->theme = \'' . $this->_View->theme . '\';
Router::setRequestInfo($controller->request);';
if ($useCallbacks == true) {
$file .= '
$controller->constructClasses();
$controller->Component->initialize($controller);
$controller->beforeFilter();
$controller->Component->startup($controller);';
$controller->startupProcess();';
}
$file .= '

View file

@ -218,7 +218,8 @@ class FormHelper extends AppHelper {
$data = $this->fieldset[$modelEntity];
$recordExists = (
isset($this->request->data[$model]) &&
!empty($this->request->data[$model][$data['key']])
!empty($this->request->data[$model][$data['key']]) &&
!is_array($this->request->data[$model][$data['key']])
);
if ($recordExists) {
@ -242,12 +243,12 @@ class FormHelper extends AppHelper {
if (empty($options['url']['controller'])) {
if (!empty($model) && $model != $this->defaultModel) {
$options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
} elseif (!empty($this->request['controller'])) {
$options['url']['controller'] = Inflector::underscore($this->request['controller']);
} elseif (!empty($this->request->params['controller'])) {
$options['url']['controller'] = Inflector::underscore($this->request->params['controller']);
}
}
if (empty($options['action'])) {
$options['action'] = $this->request['action'];
$options['action'] = $this->request->params['action'];
}
$actionDefaults = array(
@ -306,9 +307,9 @@ class FormHelper extends AppHelper {
$htmlAttributes = array_merge($options, $htmlAttributes);
$this->fields = array();
if (isset($this->request['_Token']) && !empty($this->request['_Token'])) {
if (isset($this->request->params['_Token']) && !empty($this->request->params['_Token'])) {
$append .= $this->hidden('_Token.key', array(
'value' => $this->request['_Token']['key'], 'id' => 'Token' . mt_rand())
'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand())
);
}

View file

@ -48,7 +48,7 @@ class NumberHelper extends AppHelper {
'decimals' => '.', 'negative' => '()','escape' => false
),
'EUR' => array(
'before'=>'&#8364;', 'after' => 'c', 'zero' => 0, 'places' => 2, 'thousands' => '.',
'before'=>'&#8364;', 'after' => false, 'zero' => 0, 'places' => 2, 'thousands' => '.',
'decimals' => ',', 'negative' => '()', 'escape' => false
)
);

View file

@ -110,10 +110,10 @@ class PaginatorHelper extends AppHelper {
*
* @return void
*/
public function beforeRender() {
public function beforeRender($viewFile) {
$this->options['url'] = array_merge($this->request->params['pass'], $this->request->params['named']);
parent::beforeRender();
parent::beforeRender($viewFile);
}
/**

View file

@ -21,7 +21,7 @@ if (Configure::read() == 0):
endif;
?>
<h2><?php echo sprintf(__('Release Notes for CakePHP %s.', true), Configure::version()); ?></h2>
<a href="http://cakephp.lighthouseapp.com/projects/42648/changelog-1-3-5"><?php __('Read the changelog'); ?> </a>
<a href="http://cakephp.org/changelogs/1.3.6"><?php __('Read the changelog'); ?> </a>
<?php
if (Configure::read() > 0):
Debugger::checkSecurityKeys();

View file

@ -0,0 +1,89 @@
<?php
/**
* Scaffold.
*
* Automatic forms and actions generation for rapid web application development.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs.view
* @since Cake v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('View', 'Theme');
/**
* ScaffoldView provides specific view file loading features for scaffolded views.
*
* @package cake.libs.view
*/
class ScaffoldView extends ThemeView {
/**
* Override _getViewFileName Appends special scaffolding views in.
*
* @param string $name name of the view file to get.
* @return string action
*/
protected function _getViewFileName($name = null) {
if ($name === null) {
$name = $this->action;
}
$name = Inflector::underscore($name);
$prefixes = Configure::read('Routing.prefixes');
if (!empty($prefixes)) {
foreach ($prefixes as $prefix) {
if (strpos($name, $prefix . '_') !== false) {
$name = substr($name, strlen($prefix) + 1);
break;
}
}
}
if ($name === 'add') {
$name = 'edit';
}
$scaffoldAction = 'scaffold.' . $name;
if (!is_null($this->subDir)) {
$subDir = strtolower($this->subDir) . DS;
} else {
$subDir = null;
}
$names[] = $this->viewPath . DS . $subDir . $scaffoldAction;
$names[] = 'scaffolds' . DS . $subDir . $name;
$paths = $this->_paths($this->plugin);
$exts = array($this->ext);
if ($this->ext !== '.ctp') {
array_push($exts, '.ctp');
}
foreach ($exts as $ext) {
foreach ($paths as $path) {
foreach ($names as $name) {
if (file_exists($path . $name . $ext)) {
return $path . $name . $ext;
}
}
}
}
if ($name === 'scaffolds' . DS . $subDir . 'error') {
return LIBS . 'view' . DS . 'errors' . DS . 'scaffold_error.ctp';
}
throw new MissingViewException($paths[0] . $name . $this->ext);
}
}

View file

@ -38,7 +38,7 @@ class ThemeView extends View {
*
* @param Controller $controller Controller object to be rendered.
*/
function __construct(&$controller) {
function __construct($controller) {
parent::__construct($controller);
$this->theme = $controller->theme;
}

View file

@ -21,7 +21,6 @@
/**
* Included libraries.
*/
App::import('Core', 'ClassRegistry');
App::import('View', 'HelperCollection', false);
App::import('View', 'Helper', false);
@ -241,6 +240,16 @@ class View extends Object {
*/
public $request;
/**
* The Cache configuration View will use to store cached elements. Changing this will change
* the default configuration elements are stored under. You can also choose a cache config
* per element.
*
* @var string
* @see View::element()
*/
public $elementCache = 'default';
/**
* List of variables to collect from the associated controller
*
@ -268,12 +277,19 @@ class View extends Object {
*/
private $__paths = array();
/**
* boolean to indicate that helpers have been loaded.
*
* @var boolean
*/
protected $_helpersLoaded = false;
/**
* Constructor
*
* @param Controller $controller A controller object to pull View::__passedArgs from.
*/
function __construct(&$controller) {
function __construct($controller) {
if (is_object($controller)) {
$count = count($this->__passedVars);
for ($j = 0; $j < $count; $j++) {
@ -294,68 +310,70 @@ class View extends Object {
*
* ### Special params
*
* - `cache` - enable caching for this element accepts boolean or strtotime compatible string.
* Can also be an array. If `cache` is an array,
* `time` is used to specify duration of cache.
* `key` can be used to create unique cache files.
* - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
* If an array, the following keys can be used:
* - `config` - Used to store the cached element in a custom cache configuration.
* - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
* - `plugin` - Load an element from a specific plugin.
*
* @param string $name Name of template file in the/app/views/elements/ folder
* @param array $params Array of data to be made available to the for rendered
* view (i.e. the Element)
* @param boolean $callbacks Set to true to fire beforeRender and afterRender helper callbacks for this element.
* Defaults to false.
* @return string Rendered Element
*/
public function element($name, $params = array(), $loadHelpers = false) {
public function element($name, $params = array(), $callbacks = false) {
$file = $plugin = $key = null;
if (isset($params['plugin'])) {
$plugin = $params['plugin'];
}
if (isset($this->plugin) && !$plugin) {
$plugin = $this->plugin;
}
if (isset($params['cache'])) {
$expires = '+1 day';
$keys = array_merge(array($plugin, $name), array_keys($params));
$caching = array(
'config' => $this->elementCache,
'key' => implode('_', $keys)
);
if (is_array($params['cache'])) {
$expires = $params['cache']['time'];
$key = Inflector::slug($params['cache']['key']);
} elseif ($params['cache'] !== true) {
$expires = $params['cache'];
$key = implode('_', array_keys($params));
$defaults = array(
'config' => $this->elementCache,
'key' => $caching['key']
);
$caching = array_merge($defaults, $params['cache']);
}
if ($expires) {
$cacheFile = 'element_' . $key . '_' . $plugin . Inflector::slug($name);
$cache = cache('views' . DS . $cacheFile, null, $expires);
if (is_string($cache)) {
return $cache;
}
$key = 'element_' . $caching['key'];
$contents = Cache::read($key, $caching['config']);
if ($contents !== false) {
return $contents;
}
}
$paths = $this->_paths($plugin);
$file = $this->_getElementFilename($name, $plugin);
foreach ($paths as $path) {
if (file_exists($path . 'elements' . DS . $name . $this->ext)) {
$file = $path . 'elements' . DS . $name . $this->ext;
break;
if ($file) {
if (!$this->_helpersLoaded) {
$this->loadHelpers();
}
}
if (is_file($file)) {
$element = $this->_render($file, array_merge($this->viewVars, $params), $loadHelpers);
if (isset($params['cache']) && isset($cacheFile) && isset($expires)) {
cache('views' . DS . $cacheFile, $element, $expires);
if ($callbacks) {
$this->Helpers->trigger('beforeRender', array($file));
}
$element = $this->_render($file, array_merge($this->viewVars, $params));
if ($callbacks) {
$this->Helpers->trigger('afterRender', array($file, $element));
}
if (isset($params['cache'])) {
Cache::write($key, $element, $caching['config']);
}
return $element;
}
$file = $paths[0] . 'elements' . DS . $name . $this->ext;
$file = 'elements' . DS . $name . $this->ext;
if (Configure::read('debug') > 0) {
return "Not Found: " . $file;
return "Element Not Found: " . $file;
}
}
@ -372,39 +390,32 @@ class View extends Object {
if ($this->hasRendered) {
return true;
}
$out = null;
if (!$this->_helpersLoaded) {
$this->loadHelpers();
}
$this->output = null;
if ($file != null) {
$action = $file;
}
if ($action !== false && $viewFileName = $this->_getViewFileName($action)) {
$out = $this->_render($viewFileName, $this->viewVars);
$this->Helpers->trigger('beforeRender', array($viewFileName));
$this->output = $this->_render($viewFileName);
$this->Helpers->trigger('afterRender', array($viewFileName));
}
if ($layout === null) {
$layout = $this->layout;
}
if ($out !== false) {
if ($layout && $this->autoLayout) {
$out = $this->renderLayout($out, $layout);
$isCached = (
isset($this->Helpers->Cache) ||
Configure::read('Cache.check') === true
);
if ($isCached) {
$replace = array('<cake:nocache>', '</cake:nocache>');
$out = str_replace($replace, '', $out);
}
}
$this->hasRendered = true;
} else {
$out = $this->_render($viewFileName, $this->viewVars);
trigger_error(sprintf(__("Error in view %s, got: <blockquote>%s</blockquote>"), $viewFileName, $out), E_USER_ERROR);
if ($this->output === false) {
throw new RuntimeException(sprintf(__("Error in view %s, got no content."), $viewFileName));
}
return $out;
if ($layout && $this->autoLayout) {
$this->output = $this->renderLayout($this->output, $layout);
}
$this->hasRendered = true;
return $this->output;
}
/**
@ -423,35 +434,27 @@ class View extends Object {
if (empty($layoutFileName)) {
return $this->output;
}
if (!$this->_helpersLoaded) {
$this->loadHelpers();
}
$this->Helpers->trigger('beforeLayout', array($layoutFileName));
$dataForLayout = array_merge($this->viewVars, array(
$this->viewVars = array_merge($this->viewVars, array(
'content_for_layout' => $content_for_layout,
'scripts_for_layout' => implode("\n\t", $this->_scripts),
));
if (!isset($dataForLayout['title_for_layout'])) {
$dataForLayout['title_for_layout'] = Inflector::humanize($this->viewPath);
}
$attached = $this->Helpers->attached();
if (empty($attached) && !empty($this->helpers)) {
$loadHelpers = true;
} else {
$loadHelpers = false;
$dataForLayout = array_merge($dataForLayout);
if (!isset($this->viewVars['title_for_layout'])) {
$this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath);
}
$this->Helpers->trigger('beforeLayout', array(&$this));
$this->output = $this->_render($layoutFileName, $dataForLayout, $loadHelpers, true);
$this->output = $this->_render($layoutFileName);
if ($this->output === false) {
$this->output = $this->_render($layoutFileName, $data_for_layout);
trigger_error(sprintf(__("Error in layout %s, got: <blockquote>%s</blockquote>"), $layoutFileName, $this->output), E_USER_ERROR);
return false;
throw new RuntimeException(sprintf(__("Error in layout %s, got no content."), $layoutFileName));
}
$this->Helpers->trigger('afterLayout', array(&$this));
$this->Helpers->trigger('afterLayout', array($layoutFileName));
return $this->output;
}
@ -601,21 +604,6 @@ class View extends Object {
$this->viewVars = $data + $this->viewVars;
}
/**
* Displays an error page to the user. Uses layouts/error.ctp to render the page.
*
* @param integer $code HTTP Error code (for instance: 404)
* @param string $name Name of the error (for instance: Not Found)
* @param string $message Error message as a web page
*/
public function error($code, $name, $message) {
header ("HTTP/1.1 {$code} {$name}");
print ($this->_render(
$this->_getLayoutFileName('error'),
array('code' => $code, 'name' => $name, 'message' => $message)
));
}
/**
* Magic accessor for helpers. Provides access to attributes that were deprecated.
*
@ -650,6 +638,7 @@ class View extends Object {
foreach ($helpers as $name => $properties) {
$this->Helpers->load($properties['class'], $properties['settings'], true);
}
$this->_helpersLoaded = true;
}
/**
@ -662,12 +651,9 @@ class View extends Object {
* @param boolean $cached Whether or not to trigger the creation of a cache file.
* @return string Rendered output
*/
protected function _render($___viewFn, $___dataForView, $loadHelpers = true, $cached = false) {
$attached = $this->Helpers->attached();
if (count($attached) === 0 && $loadHelpers === true) {
$this->loadHelpers();
$this->Helpers->trigger('beforeRender', array(&$this));
unset($attached);
protected function _render($___viewFn, $___dataForView = array(), $loadHelpers = true, $cached = false) {
if (empty($___dataForView)) {
$___dataForView = $this->viewVars;
}
extract($___dataForView, EXTR_SKIP);
@ -675,41 +661,19 @@ class View extends Object {
include $___viewFn;
if ($loadHelpers === true) {
$this->Helpers->trigger('afterRender', array(&$this));
}
$out = ob_get_clean();
$caching = (
isset($this->Helpers->Cache) &&
(($this->cacheAction != false)) && (Configure::read('Cache.check') === true)
);
if ($caching) {
if (isset($this->Helpers->Cache)) {
$cache =& $this->Helpers->Cache;
$cache->base = $this->request->base;
$cache->here = $this->request->here;
$cache->helpers = $this->helpers;
$cache->action = $this->request->action;
$cache->controllerName = $this->name;
$cache->layout = $this->layout;
$cache->cacheAction = $this->cacheAction;
$cache->cache($___viewFn, $out, $cached);
}
}
return $out;
return ob_get_clean();
}
/**
* Loads a helper. Delegates to the HelperCollection to load the helper
* Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
*
* @param string $helperName Name of the helper to load.
* @param array $settings Settings for the helper
* @return Helper a constructed helper object.
* @see HelperCollection::load()
*/
public function loadHelper($helperName, $settings = array(), $attach = true) {
return $this->Helpers->load($helperName, $settings, $attach);
public function loadHelper($helperName, $settings = array()) {
return $this->Helpers->load($helperName, $settings);
}
/**
@ -747,7 +711,7 @@ class View extends Object {
$name = $this->viewPath . DS . $subDir . $name;
}
}
$paths = $this->_paths(Inflector::underscore($this->plugin));
$paths = $this->_paths($this->plugin);
$exts = array($this->ext);
if ($this->ext !== '.ctp') {
@ -790,7 +754,7 @@ class View extends Object {
if (!is_null($this->layoutPath)) {
$subDir = $this->layoutPath . DS;
}
$paths = $this->_paths(Inflector::underscore($this->plugin));
$paths = $this->_paths($this->plugin);
$file = 'layouts' . DS . $subDir . $name;
$exts = array($this->ext);
@ -807,6 +771,23 @@ class View extends Object {
throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
}
/**
* Finds an element filename, returns false on failure.
*
* @param string $name The name of the element to find.
* @param string $plugin The plugin name the element is in.
* @return mixed Either a string to the element filename or false when one can't be found.
*/
protected function _getElementFileName($name, $plugin = null) {
$paths = $this->_paths($plugin);
foreach ($paths as $path) {
if (file_exists($path . 'elements' . DS . $name . $this->ext)) {
return $path . 'elements' . DS . $name . $this->ext;
}
}
return false;
}
/**
* Return all possible paths to find view files in order
*

View file

@ -27,14 +27,36 @@ require_once CONSOLE_LIBS . 'console_error_handler.php';
class ConsoleErrorHandlerTest extends CakeTestCase {
/**
* Factory method for error handlers with stderr() mocked out.
* setup, create mocks
*
* @return Mock object
*/
function getErrorHandler($exception) {
$error = new ConsoleErrorHandler($exception);
$error->stderr = $this->getMock('ConsoleOutput', array(), array(), '', false);
return $error;
function setUp() {
parent::setUp();
ConsoleErrorHandler::$stderr = $this->getMock('ConsoleOutput', array(), array(), '', false);
}
/**
* teardown
*
* @return void
*/
function tearDown() {
parent::tearDown();
ConsoleErrorHandler::$stderr = null;
}
/**
* test that the console error handler can deal with CakeExceptions.
*
* @return void
*/
function testHandleError() {
$content = '<error>Notice Error:</error> This is a notice error in [/some/file, line 275]';
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($content);
ConsoleErrorHandler::handleError(E_NOTICE, 'This is a notice error', '/some/file', 275);
}
/**
@ -44,12 +66,10 @@ class ConsoleErrorHandlerTest extends CakeTestCase {
*/
function testCakeErrors() {
$exception = new MissingActionException('Missing action');
$error = $this->getErrorHandler($exception);
$error->stderr->expects($this->once())->method('write')
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('Missing action'));
$error->render();
ConsoleErrorHandler::handleException($exception);
}
/**
@ -59,12 +79,11 @@ class ConsoleErrorHandlerTest extends CakeTestCase {
*/
function testNonCakeExceptions() {
$exception = new InvalidArgumentException('Too many parameters.');
$error = $this->getErrorHandler($exception);
$error->stderr->expects($this->once())->method('write')
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('Too many parameters.'));
$error->render();
ConsoleErrorHandler::handleException($exception);
}
/**
@ -74,12 +93,11 @@ class ConsoleErrorHandlerTest extends CakeTestCase {
*/
function testError404Exception() {
$exception = new NotFoundException('dont use me in cli.');
$error = $this->getErrorHandler($exception);
$error->stderr->expects($this->once())->method('write')
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('dont use me in cli.'));
$error->render();
ConsoleErrorHandler::handleException($exception);
}
/**
@ -89,23 +107,11 @@ class ConsoleErrorHandlerTest extends CakeTestCase {
*/
function testError500Exception() {
$exception = new InternalErrorException('dont use me in cli.');
$error = $this->getErrorHandler($exception);
$error->stderr->expects($this->once())->method('write')
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('dont use me in cli.'));
$error->render();
ConsoleErrorHandler::handleException($exception);
}
/**
* test that ConsoleErrorHandler has a stderr file handle.
*
* @return void
*/
function testStdErrFilehandle() {
$exception = new InternalErrorException('dont use me in cli.');
$error = new ConsoleErrorHandler($exception);
$this->assertType('ConsoleOutput', $error->stderr, 'No handle.');
}
}

View file

@ -79,6 +79,18 @@ class ConsoleOptionParserTest extends CakeTestCase {
$this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out');
}
/**
* test addOption with an object.
*
* @return void
*/
function testAddOptionObject() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption(new ConsoleInputOption('test', 't'));
$result = $parser->parse(array('--test=value'));
$this->assertEquals(array('test' => 'value', 'help' => false), $result[0], 'Long parameter did not parse out');
}
/**
* test adding an option and using the long value for parsing.
*
@ -255,6 +267,19 @@ class ConsoleOptionParserTest extends CakeTestCase {
$this->assertEquals($parser, $result, 'Should returnn this');
}
/**
* test addOption with an object.
*
* @return void
*/
function testAddArgumentObject() {
$parser = new ConsoleOptionParser('test', false);
$parser->addArgument(new ConsoleInputArgument('test'));
$result = $parser->arguments();
$this->assertEquals(1, count($result));
$this->assertEquals('test', $result[0]->name());
}
/**
* test overwriting positional arguments.
*
@ -350,6 +375,19 @@ class ConsoleOptionParserTest extends CakeTestCase {
$this->assertEquals($parser, $result, 'Adding a subcommand is not chainable');
}
/**
* test addSubcommand with an object.
*
* @return void
*/
function testAddSubcommandObject() {
$parser = new ConsoleOptionParser('test', false);
$parser->addSubcommand(new ConsoleInputSubcommand('test'));
$result = $parser->subcommands();
$this->assertEquals(1, count($result));
$this->assertEquals('test', $result['test']->name());
}
/**
* test adding multiple subcommands
*

View file

@ -220,7 +220,7 @@ class SchemaShellTest extends CakeTestCase {
$this->Shell->startup();
$this->Shell->dump();
$this->file =& new File(TMP . 'tests' . DS . 'i18n.sql');
$this->file = new File(TMP . 'tests' . DS . 'i18n.sql');
$contents = $this->file->read();
$this->assertPattern('/DROP TABLE/', $contents);
$this->assertPattern('/CREATE TABLE `i18n`/', $contents);
@ -250,7 +250,7 @@ class SchemaShellTest extends CakeTestCase {
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->dump();
$this->file =& new File(TMP . 'tests' . DS . 'dump_test.sql');
$this->file = new File(TMP . 'tests' . DS . 'dump_test.sql');
$contents = $this->file->read();
$this->assertPattern('/CREATE TABLE `test_plugin_acos`/', $contents);

View file

@ -69,6 +69,20 @@ class TestShell extends Shell {
protected function no_access() {
}
public function mergeVars($properties, $class, $normalize = true) {
return $this->_mergeVars($properties, $class, $normalize);
}
}
/**
* Class for testing merging vars
*
* @package cake.tests.cases.console
*/
class TestMergeShell extends Shell {
var $tasks = array('DbConfig', 'Fixture');
var $uses = array('Comment');
}
/**
@ -119,7 +133,7 @@ class ShellTest extends CakeTestCase {
$output = $this->getMock('ConsoleOutput', array(), array(), '', false);
$error = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell =& new TestShell($output, $error, $in);
$this->Shell = new TestShell($output, $error, $in);
}
/**
@ -134,6 +148,25 @@ class ShellTest extends CakeTestCase {
$this->assertType('ConsoleOutput', $this->Shell->stderr);
}
/**
* test merging vars
*
* @return void
*/
function testMergeVars() {
$this->Shell->tasks = array('DbConfig' => array('one', 'two'));
$this->Shell->uses = array('Posts');
$this->Shell->mergeVars(array('tasks'), 'TestMergeShell');
$this->Shell->mergeVars(array('uses'), 'TestMergeShell', false);
$expected = array('DbConfig' => null, 'Fixture' => null, 'DbConfig' => array('one', 'two'));
$this->assertEquals($expected, $this->Shell->tasks);
$expected = array('Fixture' => null, 'DbConfig' => array('one', 'two'));
$this->assertEquals($expected, Set::normalize($this->Shell->tasks), 'Normalized results are wrong.');
$this->assertEquals(array('Comment', 'Posts'), $this->Shell->uses, 'Merged models are wrong.');
}
/**
* testInitialize method
*

View file

@ -304,11 +304,11 @@ class ControllerTaskTest extends CakeTestCase {
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'controllers' . DS . 'articles_controller.php';
$this->Task->expects($this->at(0))->method('createFile')->with(
$this->Task->expects($this->at(1))->method('createFile')->with(
$path,
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->expects($this->at(1))->method('createFile')->with(
$this->Task->expects($this->at(3))->method('createFile')->with(
$path,
new PHPUnit_Framework_Constraint_PCREMatch('/ArticlesController extends ControllerTestAppController/')
);
@ -344,8 +344,8 @@ class ControllerTaskTest extends CakeTestCase {
$this->assertContains("\$this->set('bakeArticle', \$this->BakeArticle->read(null, \$id)", $result);
$this->assertContains('function add()', $result);
$this->assertContains('if (!empty($this->data))', $result);
$this->assertContains('if ($this->BakeArticle->save($this->data))', $result);
$this->assertContains("if (\$this->request->is('post'))", $result);
$this->assertContains('if ($this->BakeArticle->save($this->request->data))', $result);
$this->assertContains("\$this->Session->setFlash(__('The bake article has been saved'));", $result);
$this->assertContains('function edit($id = null)', $result);
@ -386,8 +386,8 @@ class ControllerTaskTest extends CakeTestCase {
$this->assertContains("\$this->set('bakeArticle', \$this->BakeArticle->read(null, \$id)", $result);
$this->assertContains('function add()', $result);
$this->assertContains('if (!empty($this->data))', $result);
$this->assertContains('if ($this->BakeArticle->save($this->data))', $result);
$this->assertContains("if (\$this->request->is('post'))", $result);
$this->assertContains('if ($this->BakeArticle->save($this->request->data))', $result);
$this->assertContains("\$this->flash(__('The bake article has been saved.'), array('action' => 'index'))", $result);

View file

@ -42,7 +42,10 @@ class ModelTaskTest extends CakeTestCase {
* @var array
* @access public
*/
public $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag', 'core.category_thread');
public $fixtures = array(
'core.bake_article', 'core.bake_comment', 'core.bake_articles_bake_tag',
'core.bake_tag', 'core.category_thread'
);
/**
* setUp method
@ -116,25 +119,25 @@ class ModelTaskTest extends CakeTestCase {
}
$this->_useMockedOut();
$this->Task->expects($this->at(1))->method('out')->with('1. Article');
$this->Task->expects($this->at(2))->method('out')->with('2. ArticlesTag');
$this->Task->expects($this->at(3))->method('out')->with('3. CategoryThread');
$this->Task->expects($this->at(4))->method('out')->with('4. Comment');
$this->Task->expects($this->at(5))->method('out')->with('5. Tag');
$this->Task->expects($this->at(1))->method('out')->with('1. BakeArticle');
$this->Task->expects($this->at(2))->method('out')->with('2. BakeArticlesBakeTag');
$this->Task->expects($this->at(3))->method('out')->with('3. BakeComment');
$this->Task->expects($this->at(4))->method('out')->with('4. BakeTag');
$this->Task->expects($this->at(5))->method('out')->with('5. CategoryThread');
$this->Task->expects($this->at(7))->method('out')->with('1. Article');
$this->Task->expects($this->at(8))->method('out')->with('2. ArticlesTag');
$this->Task->expects($this->at(9))->method('out')->with('3. CategoryThread');
$this->Task->expects($this->at(10))->method('out')->with('4. Comment');
$this->Task->expects($this->at(11))->method('out')->with('5. Tag');
$this->Task->expects($this->at(7))->method('out')->with('1. BakeArticle');
$this->Task->expects($this->at(8))->method('out')->with('2. BakeArticlesBakeTag');
$this->Task->expects($this->at(9))->method('out')->with('3. BakeComment');
$this->Task->expects($this->at(10))->method('out')->with('4. BakeTag');
$this->Task->expects($this->at(11))->method('out')->with('5. CategoryThread');
$result = $this->Task->listAll('test');
$expected = array('articles', 'articles_tags', 'category_threads', 'comments', 'tags');
$expected = array('bake_articles', 'bake_articles_bake_tags', 'bake_comments', 'bake_tags', 'category_threads');
$this->assertEqual($result, $expected);
$this->Task->connection = 'test';
$result = $this->Task->listAll();
$expected = array('articles', 'articles_tags', 'category_threads', 'comments', 'tags');
$expected = array('bake_articles', 'bake_articles_bake_tags', 'bake_comments', 'bake_tags', 'category_threads');
$this->assertEqual($result, $expected);
}
@ -155,20 +158,14 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
function testGetNameValidOption() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$listing = $this->Task->listAll('test');
$this->Task->expects($this->any())->method('in')->will($this->onConsecutiveCalls(1, 4));
$result = $this->Task->getName('test');
$expected = 'Article';
$this->assertEqual($result, $expected);
$this->assertEquals(Inflector::classify($listing[0]), $result);
$result = $this->Task->getName('test');
$expected = 'Comment';
$this->assertEqual($result, $expected);
$this->assertEquals(Inflector::classify($listing[3]), $result);
}
/**
@ -190,8 +187,8 @@ class ModelTaskTest extends CakeTestCase {
*/
public function testGetTableName() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$result = $this->Task->getTable('Article', 'test');
$expected = 'articles';
$result = $this->Task->getTable('BakeArticle', 'test');
$expected = 'bake_articles';
$this->assertEqual($result, $expected);
}
@ -202,7 +199,7 @@ class ModelTaskTest extends CakeTestCase {
*/
function testGetTableNameCustom() {
$this->Task->expects($this->any())->method('in')->will($this->onConsecutiveCalls('n', 'my_table'));
$result = $this->Task->getTable('Article', 'test');
$result = $this->Task->getTable('BakeArticle', 'test');
$expected = 'my_table';
$this->assertEqual($result, $expected);
}
@ -419,19 +416,19 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
public function testBelongsToGeneration() {
$model = new Model(array('ds' => 'test', 'name' => 'Comment'));
$model = new Model(array('ds' => 'test', 'name' => 'BakeComment'));
$result = $this->Task->findBelongsTo($model, array());
$expected = array(
'belongsTo' => array(
array(
'alias' => 'Article',
'className' => 'Article',
'foreignKey' => 'article_id',
'alias' => 'BakeArticle',
'className' => 'BakeArticle',
'foreignKey' => 'bake_article_id',
),
array(
'alias' => 'User',
'className' => 'User',
'foreignKey' => 'user_id',
'alias' => 'BakeUser',
'className' => 'BakeUser',
'foreignKey' => 'bake_user_id',
),
)
);
@ -457,23 +454,23 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
public function testHasManyHasOneGeneration() {
$model = new Model(array('ds' => 'test', 'name' => 'Article'));
$model = new Model(array('ds' => 'test', 'name' => 'BakeArticle'));
$this->Task->connection = 'test';
$this->Task->listAll();
$result = $this->Task->findHasOneAndMany($model, array());
$expected = array(
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
'alias' => 'BakeComment',
'className' => 'BakeComment',
'foreignKey' => 'bake_article_id',
),
),
'hasOne' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
'alias' => 'BakeComment',
'className' => 'BakeComment',
'foreignKey' => 'bake_article_id',
),
),
);
@ -506,23 +503,18 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
public function testHasAndBelongsToManyGeneration() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$model = new Model(array('ds' => 'test', 'name' => 'Article'));
$model = new Model(array('ds' => 'test', 'name' => 'BakeArticle'));
$this->Task->connection = 'test';
$this->Task->listAll();
$result = $this->Task->findHasAndBelongsToMany($model, array());
$expected = array(
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
'alias' => 'BakeTag',
'className' => 'BakeTag',
'foreignKey' => 'bake_article_id',
'joinTable' => 'bake_articles_bake_tags',
'associationForeignKey' => 'bake_tag_id',
),
),
);
@ -537,23 +529,23 @@ class ModelTaskTest extends CakeTestCase {
public function testDoAssociationsNonInteractive() {
$this->Task->connection = 'test';
$this->Task->interactive = false;
$model = new Model(array('ds' => 'test', 'name' => 'Article'));
$model = new Model(array('ds' => 'test', 'name' => 'BakeArticle'));
$result = $this->Task->doAssociations($model);
$expected = array(
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
'alias' => 'BakeComment',
'className' => 'BakeComment',
'foreignKey' => 'bake_article_id',
),
),
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
'alias' => 'BakeTag',
'className' => 'BakeTag',
'foreignKey' => 'bake_article_id',
'joinTable' => 'bake_articles_bake_tags',
'associationForeignKey' => 'bake_tag_id',
),
),
);
@ -567,8 +559,8 @@ class ModelTaskTest extends CakeTestCase {
public function testBakeFixture() {
$this->Task->plugin = 'test_plugin';
$this->Task->interactive = true;
$this->Task->Fixture->expects($this->at(0))->method('bake')->with('Article', 'articles');
$this->Task->bakeFixture('Article', 'articles');
$this->Task->Fixture->expects($this->at(0))->method('bake')->with('BakeArticle', 'bake_articles');
$this->Task->bakeFixture('BakeArticle', 'bake_articles');
$this->assertEqual($this->Task->plugin, $this->Task->Fixture->plugin);
$this->assertEqual($this->Task->connection, $this->Task->Fixture->connection);
@ -583,8 +575,8 @@ class ModelTaskTest extends CakeTestCase {
public function testBakeTest() {
$this->Task->plugin = 'test_plugin';
$this->Task->interactive = true;
$this->Task->Test->expects($this->at(0))->method('bake')->with('Model', 'Article');
$this->Task->bakeTest('Article');
$this->Task->Test->expects($this->at(0))->method('bake')->with('Model', 'BakeArticle');
$this->Task->bakeTest('BakeArticle');
$this->assertEqual($this->Task->plugin, $this->Task->Test->plugin);
$this->assertEqual($this->Task->connection, $this->Task->Test->connection);
@ -676,9 +668,9 @@ class ModelTaskTest extends CakeTestCase {
'time' => 'time'
)
);
$result = $this->Task->bake('Article', compact('validate'));
$this->assertPattern('/class Article extends AppModel \{/', $result);
$this->assertPattern('/\$name \= \'Article\'/', $result);
$result = $this->Task->bake('BakeArticle', compact('validate'));
$this->assertPattern('/class BakeArticle extends AppModel \{/', $result);
$this->assertPattern('/\$name \= \'BakeArticle\'/', $result);
$this->assertPattern('/\$validate \= array\(/', $result);
$expected = <<< STRINGEND
array(
@ -708,9 +700,9 @@ STRINGEND;
'foreignKey' => 'something_else_id',
),
array(
'alias' => 'User',
'className' => 'User',
'foreignKey' => 'user_id',
'alias' => 'BakeUser',
'className' => 'BakeUser',
'foreignKey' => 'bake_user_id',
),
),
'hasOne' => array(
@ -722,30 +714,30 @@ STRINGEND;
),
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'alias' => 'BakeComment',
'className' => 'BakeComment',
'foreignKey' => 'parent_id',
),
),
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
'alias' => 'BakeTag',
'className' => 'BakeTag',
'foreignKey' => 'bake_article_id',
'joinTable' => 'bake_articles_bake_tags',
'associationForeignKey' => 'bake_tag_id',
),
)
);
$result = $this->Task->bake('Article', compact('associations'));
$result = $this->Task->bake('BakeArticle', compact('associations'));
$this->assertPattern('/\$hasAndBelongsToMany \= array\(/', $result);
$this->assertPattern('/\$hasMany \= array\(/', $result);
$this->assertPattern('/\$belongsTo \= array\(/', $result);
$this->assertPattern('/\$hasOne \= array\(/', $result);
$this->assertPattern('/Tag/', $result);
$this->assertPattern('/BakeTag/', $result);
$this->assertPattern('/OtherModel/', $result);
$this->assertPattern('/SomethingElse/', $result);
$this->assertPattern('/Comment/', $result);
$this->assertPattern('/BakeComment/', $result);
}
/**
@ -756,11 +748,11 @@ STRINGEND;
public function testBakeWithPlugin() {
$this->Task->plugin = 'controllerTest';
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'models' . DS . 'article.php';
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'models' . DS . 'bake_article.php';
$this->Task->expects($this->once())->method('createFile')
->with($path, new PHPUnit_Framework_Constraint_PCREMatch('/Article extends ControllerTestAppModel/'));
->with($path, new PHPUnit_Framework_Constraint_PCREMatch('/BakeArticle extends ControllerTestAppModel/'));
$this->Task->bake('Article', array(), array());
$this->Task->bake('BakeArticle', array(), array());
$this->assertEqual(count(ClassRegistry::keys()), 0);
$this->assertEqual(count(ClassRegistry::mapKeys()), 0);
@ -774,12 +766,12 @@ STRINGEND;
public function testExecuteWithNamedModel() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$filename = '/my/path/article.php';
$this->Task->args = array('bake_article');
$filename = '/my/path/bake_article.php';
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1));
$this->Task->expects($this->once())->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article extends AppModel/'));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeArticle extends AppModel/'));
$this->Task->execute();
@ -794,7 +786,7 @@ STRINGEND;
*/
static function nameVariations() {
return array(
array('Articles'), array('Article'), array('article'), array('articles')
array('BakeArticles'), array('BakeArticle'), array('bake_article'), array('bake_articles')
);
}
@ -810,10 +802,10 @@ STRINGEND;
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1));
$this->Task->args = array($name);
$filename = '/my/path/article.php';
$filename = '/my/path/bake_article.php';
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article extends AppModel/'));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeArticle extends AppModel/'));
$this->Task->execute();
}
@ -825,12 +817,12 @@ STRINGEND;
public function testExecuteWithNamedModelHasManyCreated() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$filename = '/my/path/article.php';
$this->Task->args = array('bake_article');
$filename = '/my/path/bake_article.php';
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1));
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch("/'Comment' \=\> array\(/"));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch("/'BakeComment' \=\> array\(/"));
$this->Task->execute();
}
@ -854,26 +846,26 @@ STRINGEND;
$this->Task->Fixture->expects($this->exactly(5))->method('bake');
$this->Task->Test->expects($this->exactly(5))->method('bake');
$filename = '/my/path/article.php';
$filename = '/my/path/bake_article.php';
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article/'));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeArticle/'));
$filename = '/my/path/articles_tag.php';
$filename = '/my/path/bake_articles_bake_tag.php';
$this->Task->expects($this->at(2))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticlesTag/'));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeArticlesBakeTag/'));
$filename = '/my/path/category_thread.php';
$filename = '/my/path/bake_comment.php';
$this->Task->expects($this->at(3))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeComment/'));
$filename = '/my/path/bake_tag.php';
$this->Task->expects($this->at(4))
->method('createFile')->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeTag/'));
$filename = '/my/path/category_thread.php';
$this->Task->expects($this->at(5))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class CategoryThread/'));
$filename = '/my/path/comment.php';
$this->Task->expects($this->at(4))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Comment/'));
$filename = '/my/path/tag.php';
$this->Task->expects($this->at(5))
->method('createFile')->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Tag/'));
$this->Task->execute();
$this->assertEqual(count(ClassRegistry::keys()), 0);
@ -895,26 +887,26 @@ STRINGEND;
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true));
$this->Task->skipTables = array('tags');
$this->Task->skipTables = array('bake_tags');
$this->Task->Fixture->expects($this->exactly(4))->method('bake');
$this->Task->Test->expects($this->exactly(4))->method('bake');
$filename = '/my/path/article.php';
$filename = '/my/path/bake_article.php';
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article/'));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeArticle/'));
$filename = '/my/path/articles_tag.php';
$filename = '/my/path/bake_articles_bake_tag.php';
$this->Task->expects($this->at(2))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticlesTag/'));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeArticlesBakeTag/'));
$filename = '/my/path/bake_comment.php';
$this->Task->expects($this->at(3))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeComment/'));
$filename = '/my/path/category_thread.php';
$this->Task->expects($this->at(3))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class CategoryThread/'));
$filename = '/my/path/comment.php';
$this->Task->expects($this->at(4))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Comment/'));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class CategoryThread/'));
$this->Task->execute();
}
@ -950,10 +942,10 @@ STRINGEND;
$this->Task->Test->expects($this->once())->method('bake');
$this->Task->Fixture->expects($this->once())->method('bake');
$filename = '/my/path/article.php';
$filename = '/my/path/bake_article.php';
$this->Task->expects($this->once())->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article/'));
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class BakeArticle/'));
$this->Task->execute();

View file

@ -363,7 +363,7 @@ class TestTaskTest extends CakeTestCase {
));
$keys = ClassRegistry::keys();
$this->assertTrue(in_array('test_task_comment', $keys));
$object =& $this->Task->buildTestSubject('Model', 'TestTaskComment');
$object = $this->Task->buildTestSubject('Model', 'TestTaskComment');
$keys = ClassRegistry::keys();
$this->assertFalse(in_array('random', $keys));
@ -444,7 +444,7 @@ class TestTaskTest extends CakeTestCase {
$this->assertContains('class TestTaskArticleTestCase extends CakeTestCase', $result);
$this->assertContains('function startTest()', $result);
$this->assertContains("\$this->TestTaskArticle =& ClassRegistry::init('TestTaskArticle')", $result);
$this->assertContains("\$this->TestTaskArticle = ClassRegistry::init('TestTaskArticle')", $result);
$this->assertContains('function endTest()', $result);
$this->assertContains('unset($this->TestTaskArticle)', $result);
@ -479,7 +479,7 @@ class TestTaskTest extends CakeTestCase {
$this->assertContains('function redirect($url, $status = null, $exit = true)', $result);
$this->assertContains('function startTest()', $result);
$this->assertContains("\$this->TestTaskComments =& new TestTestTaskCommentsController()", $result);
$this->assertContains("\$this->TestTaskComments = new TestTestTaskCommentsController()", $result);
$this->assertContains("\$this->TestTaskComments->constructClasses()", $result);
$this->assertContains('function endTest()', $result);

View file

@ -41,6 +41,7 @@ class TestSuiteShellTest extends CakeTestCase {
array('in', 'out', 'hr', 'help', 'error', 'err', '_stop', 'initialize', 'run', 'clear'),
array($out, $out, $in)
);
$this->Shell->OptionParser = $this->getMock('ConsoleOptionParser', array(), array(null, false));
}
/**
@ -61,7 +62,7 @@ class TestSuiteShellTest extends CakeTestCase {
$this->Shell->startup();
$this->Shell->args = array('unexistant-category');
$this->Shell->expects($this->at(0))->method('out')->with(__("No test cases available \n\n"));
$this->Shell->expects($this->once())->method('help');
$this->Shell->OptionParser->expects($this->once())->method('help');
$this->Shell->available();
}

View file

@ -37,6 +37,7 @@ class AllConfigureTest extends PHPUnit_Framework_TestSuite {
$suite = new PHPUnit_Framework_TestSuite('All Configure, App and ClassRegistry related tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'configure.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'app.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'class_registry.test.php');
return $suite;
}

View file

@ -0,0 +1,45 @@
<?php
/**
* AllErrorTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllErrorTest class
*
* This test group will run error handling related tests.
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllErrorTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Error handling tests');
$libs = CORE_TEST_CASES . DS . 'libs' . DS;
$suite->addTestFile($libs . 'error' . DS . 'error_handler.test.php');
$suite->addTestFile($libs . 'error' . DS . 'exception_renderer.test.php');
return $suite;
}
}

View file

@ -39,7 +39,6 @@ class AllLibsTest extends PHPUnit_Framework_TestSuite {
$suite->addTestFile(CORE_TEST_CASES . DS . 'basics.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cake_session.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'debugger.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'error_handler.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'file.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'folder.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'inflector.test.php');

View file

@ -34,14 +34,15 @@ class AllRoutingTest extends PHPUnit_Framework_TestSuite {
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Router and Dispatcher class tests');
$suite = new CakeTestSuite('All Router and Dispatcher class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'dispatcher.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'router.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'route' . DS . 'cake_route.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'route' . DS . 'plugin_short_route.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cake_response.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cake_request.test.php');
$libs = CORE_TEST_CASES . DS . 'libs' . DS;
$suite->addTestFile($libs . 'dispatcher.test.php');
$suite->addTestFile($libs . 'router.test.php');
$suite->addTestDirectory($libs . 'route' . DS);
$suite->addTestFile($libs . 'cake_response.test.php');
$suite->addTestFile($libs . 'cake_request.test.php');
return $suite;
}
}

View file

@ -48,6 +48,7 @@ class AllTests extends PHPUnit_Framework_TestSuite {
$suite->addTestFile($path . 'all_configure.test.php');
$suite->addTestFile($path . 'all_controllers.test.php');
$suite->addTestFile($path . 'all_database.test.php');
$suite->addTestFile($path . 'all_error.test.php');
$suite->addTestFile($path . 'all_helpers.test.php');
$suite->addTestFile($path . 'all_libs.test.php');
$suite->addTestFile($path . 'all_localization.test.php');

View file

@ -0,0 +1,531 @@
<?php
/**
* AppImportTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class AppImportTest extends CakeTestCase {
/**
* testBuild method
*
* @access public
* @return void
*/
function testBuild() {
$old = App::path('models');
$expected = array(
APP . 'models' . DS,
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $old);
App::build(array('models' => array('/path/to/models/')));
$new = App::path('models');
$expected = array(
'/path/to/models/',
APP . 'models' . DS,
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $new);
App::build(); //reset defaults
$defaults = App::path('models');
$this->assertEqual($old, $defaults);
}
/**
* testBuildWithReset method
*
* @access public
* @return void
*/
function testBuildWithReset() {
$old = App::path('models');
$expected = array(
APP . 'models' . DS,
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $old);
App::build(array('models' => array('/path/to/models/')), true);
$new = App::path('models');
$expected = array(
'/path/to/models/'
);
$this->assertEqual($expected, $new);
App::build(); //reset defaults
$defaults = App::path('models');
$this->assertEqual($old, $defaults);
}
/**
* testCore method
*
* @access public
* @return void
*/
function testCore() {
$model = App::core('models');
$this->assertEqual(array(ROOT . DS . LIBS . 'model' . DS), $model);
$view = App::core('views');
$this->assertEqual(array(ROOT . DS . LIBS . 'view' . DS), $view);
$controller = App::core('controllers');
$this->assertEqual(array(ROOT . DS . LIBS . 'controller' . DS), $controller);
}
/**
* testListObjects method
*
* @access public
* @return void
*/
function testListObjects() {
$result = App::objects('class', TEST_CAKE_CORE_INCLUDE_PATH . 'libs', false);
$this->assertTrue(in_array('Xml', $result));
$this->assertTrue(in_array('Cache', $result));
$this->assertTrue(in_array('HttpSocket', $result));
$result = App::objects('behavior', null, false);
$this->assertTrue(in_array('Tree', $result));
$result = App::objects('controller', null, false);
$this->assertTrue(in_array('Pages', $result));
$result = App::objects('component', null, false);
$this->assertTrue(in_array('Auth', $result));
$result = App::objects('view', null, false);
$this->assertTrue(in_array('Media', $result));
$result = App::objects('helper', null, false);
$this->assertTrue(in_array('Html', $result));
$result = App::objects('model', null, false);
$notExpected = array('AppModel', 'ModelBehavior', 'ConnectionManager', 'DbAcl', 'Model', 'CakeSchema');
foreach ($notExpected as $class) {
$this->assertFalse(in_array($class, $result));
}
$result = App::objects('file');
$this->assertFalse($result);
$result = App::objects('file', 'non_existing_configure');
$expected = array();
$this->assertEqual($result, $expected);
$result = App::objects('NonExistingType');
$this->assertFalse($result);
App::build(array(
'plugins' => array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS
)
));
$result = App::objects('plugin', null, false);
$this->assertTrue(in_array('Cache', $result));
$this->assertTrue(in_array('Log', $result));
App::build();
}
/**
* test that pluginPath can find paths for plugins.
*
* @return void
*/
function testPluginPath() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$path = App::pluginPath('test_plugin');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' . DS;
$this->assertEqual($path, $expected);
$path = App::pluginPath('TestPlugin');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' . DS;
$this->assertEqual($path, $expected);
$path = App::pluginPath('TestPluginTwo');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin_two' . DS;
$this->assertEqual($path, $expected);
App::build();
}
/**
* test that pluginPath can find paths for plugins.
*
* @return void
*/
function testThemePath() {
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS)
));
$path = App::themePath('test_theme');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'themed' . DS . 'test_theme' . DS;
$this->assertEqual($path, $expected);
$path = App::themePath('TestTheme');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'themed' . DS . 'test_theme' . DS;
$this->assertEqual($path, $expected);
App::build();
}
/**
* testClassLoading method
*
* @access public
* @return void
*/
function testClassLoading() {
$file = App::import();
$this->assertTrue($file);
$file = App::import('Model', 'Model', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('Model'));
$file = App::import('Controller', 'Controller', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('Controller'));
$file = App::import('Component', 'Component', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('Component'));
$file = App::import('Shell', 'Shell', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('Shell'));
$file = App::import('Lib', 'cache/Apc');
$this->assertTrue($file);
$this->assertTrue(class_exists('ApcEngine'));
$file = App::import('Model', 'SomeRandomModelThatDoesNotExist', false);
$this->assertFalse($file);
$file = App::import('Model', 'AppModel', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('AppModel'));
$file = App::import('WrongType', null, true, array(), '');
$this->assertTrue($file);
$file = App::import('Model', 'NonExistingPlugin.NonExistingModel', false);
$this->assertFalse($file);
$file = App::import('Core', 'NonExistingPlugin.NonExistingModel', false);
$this->assertFalse($file);
$file = App::import('Model', array('NonExistingPlugin.NonExistingModel'), false);
$this->assertFalse($file);
$file = App::import('Core', array('NonExistingPlugin.NonExistingModel'), false);
$this->assertFalse($file);
$file = App::import('Core', array('NonExistingPlugin.NonExistingModel.AnotherChild'), false);
$this->assertFalse($file);
if (!class_exists('AppController')) {
$classes = array_flip(get_declared_classes());
$this->assertFalse(isset($classes['PagesController']));
$this->assertFalse(isset($classes['AppController']));
$file = App::import('Controller', 'Pages');
$this->assertTrue($file);
$this->assertTrue(class_exists('PagesController'));
$classes = array_flip(get_declared_classes());
$this->assertTrue(isset($classes['PagesController']));
$this->assertTrue(isset($classes['AppController']));
$file = App::import('Behavior', 'Containable');
$this->assertTrue($file);
$this->assertTrue(class_exists('ContainableBehavior'));
$file = App::import('Component', 'RequestHandler');
$this->assertTrue($file);
$this->assertTrue(class_exists('RequestHandlerComponent'));
$file = App::import('Helper', 'Form');
$this->assertTrue($file);
$this->assertTrue(class_exists('FormHelper'));
$file = App::import('Model', 'NonExistingModel');
$this->assertFalse($file);
$file = App::import('Datasource', 'DboSource');
$this->assertTrue($file);
$this->assertTrue(class_exists('DboSource'));
}
App::build();
}
/**
* test import() with plugins
*
* @return void
*/
function testPluginImporting() {
App::build(array(
'libs' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$result = App::import('Controller', 'TestPlugin.Tests');
$this->assertTrue($result);
$this->assertTrue(class_exists('TestPluginAppController'));
$this->assertTrue(class_exists('TestsController'));
$result = App::import('Lib', 'TestPlugin.TestPluginLibrary');
$this->assertTrue($result);
$this->assertTrue(class_exists('TestPluginLibrary'));
$result = App::import('Lib', 'Library');
$this->assertTrue($result);
$this->assertTrue(class_exists('Library'));
$result = App::import('Helper', 'TestPlugin.OtherHelper');
$this->assertTrue($result);
$this->assertTrue(class_exists('OtherHelperHelper'));
$result = App::import('Helper', 'TestPlugin.TestPluginApp');
$this->assertTrue($result);
$this->assertTrue(class_exists('TestPluginAppHelper'));
$result = App::import('Datasource', 'TestPlugin.TestSource');
$this->assertTrue($result);
$this->assertTrue(class_exists('TestSource'));
App::build();
}
/**
* test that building helper paths actually works.
*
* @return void
* @link http://cakephp.lighthouseapp.com/projects/42648/tickets/410
*/
function testImportingHelpersFromAlternatePaths() {
App::build();
$this->assertFalse(class_exists('BananaHelper'), 'BananaHelper exists, cannot test importing it.');
App::import('Helper', 'Banana');
$this->assertFalse(class_exists('BananaHelper'), 'BananaHelper was not found because the path does not exist.');
App::build(array(
'helpers' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'helpers' . DS)
));
App::build(array('vendors' => array(TEST_CAKE_CORE_INCLUDE_PATH)));
$this->assertFalse(class_exists('BananaHelper'), 'BananaHelper exists, cannot test importing it.');
App::import('Helper', 'Banana');
$this->assertTrue(class_exists('BananaHelper'), 'BananaHelper was not loaded.');
App::build();
}
/**
* testFileLoading method
*
* @access public
* @return void
*/
function testFileLoading () {
$file = App::import('File', 'RealFile', false, array(), TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php');
$this->assertTrue($file);
$file = App::import('File', 'NoFile', false, array(), TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'cake' . DS . 'config.php');
$this->assertFalse($file);
}
/**
* testFileLoadingWithArray method
*
* @access public
* @return void
*/
function testFileLoadingWithArray() {
$type = array('type' => 'File', 'name' => 'SomeName', 'parent' => false,
'file' => TEST_CAKE_CORE_INCLUDE_PATH . DS . 'config' . DS . 'config.php');
$file = App::import($type);
$this->assertTrue($file);
$type = array('type' => 'File', 'name' => 'NoFile', 'parent' => false,
'file' => TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'cake' . DS . 'config.php');
$file = App::import($type);
$this->assertFalse($file);
}
/**
* testFileLoadingReturnValue method
*
* @access public
* @return void
*/
function testFileLoadingReturnValue () {
$file = App::import('File', 'Name', false, array(), TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php', true);
$this->assertTrue(!empty($file));
$this->assertTrue(isset($file['Cake.version']));
$type = array('type' => 'File', 'name' => 'OtherName', 'parent' => false,
'file' => TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php', 'return' => true);
$file = App::import($type);
$this->assertTrue(!empty($file));
$this->assertTrue(isset($file['Cake.version']));
}
/**
* testLoadingWithSearch method
*
* @access public
* @return void
*/
function testLoadingWithSearch () {
$file = App::import('File', 'NewName', false, array(TEST_CAKE_CORE_INCLUDE_PATH ), 'config.php');
$this->assertTrue($file);
$file = App::import('File', 'AnotherNewName', false, array(LIBS), 'config.php');
$this->assertFalse($file);
}
/**
* testLoadingWithSearchArray method
*
* @access public
* @return void
*/
function testLoadingWithSearchArray () {
$type = array('type' => 'File', 'name' => 'RandomName', 'parent' => false, 'file' => 'config.php', 'search' => array(TEST_CAKE_CORE_INCLUDE_PATH ));
$file = App::import($type);
$this->assertTrue($file);
$type = array('type' => 'File', 'name' => 'AnotherRandomName', 'parent' => false, 'file' => 'config.php', 'search' => array(LIBS));
$file = App::import($type);
$this->assertFalse($file);
}
/**
* testMultipleLoading method
*
* @access public
* @return void
*/
function testMultipleLoading() {
if (class_exists('I18n', false) || class_exists('CakeSocket', false)) {
$this->markTestSkipped('Cannot test loading of classes that exist.');
}
$toLoad = array('I18n', 'CakeSocket');
$classes = array_flip(get_declared_classes());
$this->assertFalse(isset($classes['i18n']));
$this->assertFalse(isset($classes['CakeSocket']));
$load = App::import($toLoad);
$this->assertTrue($load);
$classes = array_flip(get_declared_classes());
$this->assertTrue(isset($classes['I18n']));
$load = App::import(array('I18n', 'SomeNotFoundClass', 'CakeSocket'));
$this->assertFalse($load);
$load = App::import($toLoad);
$this->assertTrue($load);
}
/**
* This test only works if you have plugins/my_plugin set up.
* plugins/my_plugin/models/my_plugin.php and other_model.php
*/
/*
function testMultipleLoadingByType() {
$classes = array_flip(get_declared_classes());
$this->assertFalse(isset($classes['OtherPlugin']));
$this->assertFalse(isset($classes['MyPlugin']));
$load = App::import('Model', array('MyPlugin.OtherPlugin', 'MyPlugin.MyPlugin'));
$this->assertTrue($load);
$classes = array_flip(get_declared_classes());
$this->assertTrue(isset($classes['OtherPlugin']));
$this->assertTrue(isset($classes['MyPlugin']));
}
*/
function testLoadingVendor() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'vendors' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors'. DS),
), true);
ob_start();
$result = App::import('Vendor', 'TestPlugin.TestPluginAsset', array('ext' => 'css'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'this is the test plugin asset css file');
ob_start();
$result = App::import('Vendor', 'TestAsset', array('ext' => 'css'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'this is the test asset css file');
$result = App::import('Vendor', 'TestPlugin.SamplePlugin');
$this->assertTrue($result);
$this->assertTrue(class_exists('SamplePluginClassTestName'));
$result = App::import('Vendor', 'ConfigureTestVendorSample');
$this->assertTrue($result);
$this->assertTrue(class_exists('ConfigureTestVendorSample'));
ob_start();
$result = App::import('Vendor', 'SomeName', array('file' => 'some.name.php'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is a file with dot in file name');
ob_start();
$result = App::import('Vendor', 'TestHello', array('file' => 'Test'.DS.'hello.php'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is the hello.php file in Test directory');
ob_start();
$result = App::import('Vendor', 'MyTest', array('file' => 'Test'.DS.'MyTest.php'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is the MyTest.php file');
ob_start();
$result = App::import('Vendor', 'Welcome');
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is the welcome.php file in vendors directory');
ob_start();
$result = App::import('Vendor', 'TestPlugin.Welcome');
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is the welcome.php file in test_plugin/vendors directory');
}
}

View file

@ -280,12 +280,12 @@ class FileEngineTest extends CakeTestCase {
* @return void
*/
function testClearWithPrefixes() {
$FileOne =& new FileEngine();
$FileOne = new FileEngine();
$FileOne->init(array(
'prefix' => 'prefix_one_',
'duration' => DAY
));
$FileTwo =& new FileEngine();
$FileTwo = new FileEngine();
$FileTwo->init(array(
'prefix' => 'prefix_two_',
'duration' => DAY

View file

@ -101,7 +101,7 @@ class MemcacheEngineTest extends CakeTestCase {
function testMultipleServers() {
$servers = array('127.0.0.1:11211', '127.0.0.1:11222');
$available = true;
$Memcache =& new Memcache();
$Memcache = new Memcache();
foreach($servers as $server) {
list($host, $port) = explode(':', $server);
@ -113,7 +113,7 @@ class MemcacheEngineTest extends CakeTestCase {
if ($this->skipIf(!$available, '%s Need memcache servers at ' . implode(', ', $servers) . ' to run this test')) {
return;
}
$Memcache =& new MemcacheEngine();
$Memcache = new MemcacheEngine();
$Memcache->init(array('engine' => 'Memcache', 'servers' => $servers));
$servers = array_keys($Memcache->__Memcache->getExtendedStats());
@ -129,7 +129,7 @@ class MemcacheEngineTest extends CakeTestCase {
* @return void
*/
function testConnect() {
$Memcache =& new MemcacheEngine();
$Memcache = new MemcacheEngine();
$Memcache->init(Cache::settings('memcache'));
$result = $Memcache->connect('127.0.0.1');
$this->assertTrue($result);
@ -141,7 +141,7 @@ class MemcacheEngineTest extends CakeTestCase {
* @return void
*/
function testConnectIpv6() {
$Memcache =& new MemcacheEngine();
$Memcache = new MemcacheEngine();
$result = $Memcache->init(array(
'prefix' => 'cake_',
'duration' => 200,
@ -159,7 +159,7 @@ class MemcacheEngineTest extends CakeTestCase {
* @return void
*/
function testParseServerStringNonLatin() {
$Memcache =& new TestMemcacheEngine();
$Memcache = new TestMemcacheEngine();
$result = $Memcache->parseServerString('schülervz.net:13211');
$this->assertEqual($result, array('schülervz.net', '13211'));

View file

@ -116,7 +116,9 @@ class CakeLogTest extends CakeTestCase {
$result = CakeLog::configured();
$this->assertEqual($result, array('file'));
@unlink(LOGS . 'error.log');
if (file_exists(LOGS . 'error.log')) {
@unlink(LOGS . 'error.log');
}
CakeLog::write(LOG_WARNING, 'Test warning');
$this->assertTrue(file_exists(LOGS . 'error.log'));
@ -164,25 +166,4 @@ class CakeLogTest extends CakeTestCase {
unlink(LOGS . 'error.log');
}
/**
* Test logging with the error handler.
*
* @return void
*/
function testLoggingWithErrorHandling() {
@unlink(LOGS . 'debug.log');
Configure::write('log', E_ALL & ~E_DEPRECATED);
Configure::write('debug', 0);
set_error_handler(array('CakeLog', 'handleError'));
$out .= '';
$result = file(LOGS . 'debug.log');
$this->assertEqual(count($result), 1);
$this->assertPattern(
'/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} Notice: Notice \(8\): Undefined variable:\s+out in \[.+ line \d+\]$/',
$result[0]
);
@unlink(LOGS . 'debug.log');
}
}

View file

@ -967,7 +967,7 @@ class CakeRequestTestCase extends CakeTestCase {
* @return void
*/
public function testEnvironmentDetection() {
$dispatcher =& new Dispatcher();
$dispatcher = new Dispatcher();
$environments = array(
'IIS' => array(
@ -1338,6 +1338,27 @@ class CakeRequestTestCase extends CakeTestCase {
$this->assertSame('', $request->data['Post']['empty']);
}
/**
* test accept language
*
* @return void
*/
function testAcceptLanguage() {
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'inexistent,en-ca';
$result = CakeRequest::acceptLanguage();
$this->assertEquals(array('inexistent', 'en-ca'), $result, 'Languages do not match');
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'es_mx;en_ca';
$result = CakeRequest::acceptLanguage();
$this->assertEquals(array('es-mx', 'en-ca'), $result, 'Languages do not match');
$result = CakeRequest::acceptLanguage('en-ca');
$this->assertTrue($result);
$result = CakeRequest::acceptLanguage('en-us');
$this->assertFalse($result);
}
/**
* backupEnvironment method
*

View file

@ -60,7 +60,6 @@ class CakeTestCaseTest extends CakeTestCase {
*/
function tearDown() {
Configure::write('debug', $this->_debug);
unset($this->Case);
unset($this->Result);
unset($this->Reporter);
}
@ -77,6 +76,30 @@ class CakeTestCaseTest extends CakeTestCase {
$this->assertEquals(0, $result->errorCount());
$this->assertTrue($result->wasSuccessful());
$this->assertEquals(0, $result->failureCount());
$input = '<a href="/test.html" class="active">My link</a>';
$pattern = array(
'a' => array('href' => '/test.html', 'class' => 'active'),
'My link',
'/a'
);
$this->assertTrue($test->assertTags($input, $pattern), 'Double quoted attributes %s');
$input = "<a href='/test.html' class='active'>My link</a>";
$pattern = array(
'a' => array('href' => '/test.html', 'class' => 'active'),
'My link',
'/a'
);
$this->assertTrue($test->assertTags($input, $pattern), 'Single quoted attributes %s');
$input = "<a href='/test.html' class='active'>My link</a>";
$pattern = array(
'a' => array('href' => 'preg:/.*\.html/', 'class' => 'active'),
'My link',
'/a'
);
$this->assertTrue($test->assertTags($input, $pattern), 'Single quoted attributes %s');
}
/**
@ -181,6 +204,7 @@ class CakeTestCaseTest extends CakeTestCase {
$manager->expects($this->once())->method('unload');
$result = $test->run();
$this->assertEquals(1, $result->errorCount());
}
/**
* testSkipIf

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