Merge remote branch 'origin/2.0' into 2.0-class-loading

Conflicts:
	cake/tests/cases/libs/controller_test_case.test.php
	lib/Cake/Controller/ComponentCollection.php
	lib/Cake/Model/ConnectionManager.php
	lib/Cake/TestSuite/Fixture/CakeTestFixture.php
	lib/Cake/View/pages/home.ctp
This commit is contained in:
José Lorenzo Rodríguez 2011-01-22 01:00:15 -04:30
commit d9c99b5ef6
59 changed files with 849 additions and 192 deletions

View file

@ -72,7 +72,7 @@ if (!include(CORE_PATH . 'Cake' . DS . 'bootstrap.php')) {
} }
if (Configure::read('debug') < 1) { if (Configure::read('debug') < 1) {
die(__('Debug setting does not allow access to this url.', true)); die(__('Debug setting does not allow access to this url.'));
} }
require_once CAKE_TESTS_LIB . 'CakeTestSuiteDispatcher.php'; require_once CAKE_TESTS_LIB . 'CakeTestSuiteDispatcher.php';

View file

@ -0,0 +1,29 @@
<?php
/**
*
* 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.libs.view.templates.errors
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<h2><?php echo __('Missing Datasource Configuration'); ?></h2>
<p class="error">
<strong><?php echo __('Error'); ?>: </strong>
<?php echo __('The datasource configuration %1$s was not found in databases.php.', '<em>' . $config . '</em>'); ?>
</p>
<p class="notice">
<strong><?php echo __('Notice'); ?>: </strong>
<?php echo __('If you want to customize this error message, create %s', APP_DIR . DS . 'views' . DS . 'errors' . DS . 'missing_datasource_config.ctp'); ?>
</p>
<?php echo $this->element('exception_stack_trace'); ?>

View file

@ -0,0 +1,29 @@
<?php
/**
*
* 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.libs.view.templates.errors
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<h2><?php echo __('Missing Datasource Class'); ?></h2>
<p class="error">
<strong><?php echo __('Error'); ?>: </strong>
<?php echo __('Datasource class %1$s was not found.', '<em>' . $class . '</em>'); ?>
</p>
<p class="notice">
<strong><?php echo __('Notice'); ?>: </strong>
<?php echo __('If you want to customize this error message, create %s', APP_DIR . DS . 'views' . DS . 'errors' . DS . 'missing_datasource_file.ctp'); ?>
</p>
<?php echo $this->element('exception_stack_trace'); ?>

View file

@ -18,17 +18,21 @@
* @since CakePHP v 2.0 * @since CakePHP v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php) * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/ */
App::import('Controller', 'Controller', false);
App::import('Core', array('AppModel', 'Model')); App::uses('Controller', 'Controller');
require_once LIBS . 'tests' . DS . 'lib' . DS . 'reporter' . DS . 'cake_html_reporter.php'; App::uses('Model', 'Model');
App::uses('AppModel', 'Model');
App::uses('CakeHtmlReporter', 'TestSuite/Reporter');
require_once dirname(__FILE__) . DS . 'model' . DS . 'models.php'; require_once dirname(__FILE__) . DS . 'model' . DS . 'models.php';
/** /**
* AppController class * AppController class
* *
* @package cake.tests.cases.libs.controller * @package cake.tests.cases.libs.controller
*/ */
if (!class_exists('AppController')) { if (!class_exists('AppController', false)) {
/** /**
* AppController class * AppController class
* *
@ -188,6 +192,25 @@ class ControllerTestCaseTest extends CakeTestCase {
$this->assertEquals($Posts->Auth->Session->write('something'), 'written!'); $this->assertEquals($Posts->Auth->Session->write('something'), 'written!');
} }
/**
* Tests ControllerTestCase::generate() using classes from plugins
*/
function testGenerateWithPlugin() {
$Tests = $this->Case->generate('TestPlugin.Tests', array(
'models' => array(
'TestPlugin.TestPluginComment'
),
'components' => array(
'TestPlugin.PluginsComponent'
)
));
$this->assertEquals($Tests->name, 'Tests');
$this->assertInstanceOf('PluginsComponentComponent', $Tests->PluginsComponent);
$result = ClassRegistry::init('TestPlugin.TestPluginComment');
$this->assertInstanceOf('TestPluginComment', $result);
}
/** /**
* Tests testAction * Tests testAction
*/ */

View file

@ -262,8 +262,9 @@ class ControllerTestCase extends CakeTestCase {
'components' => array() 'components' => array()
), (array)$mocks); ), (array)$mocks);
$_controller = $this->getMock($controller.'Controller', $mocks['methods'], array(), '', false); list($plugin, $name) = pluginSplit($controller);
$_controller->name = $controller; $_controller = $this->getMock($name.'Controller', $mocks['methods'], array(), '', false);
$_controller->name = $name;
$_controller->__construct(); $_controller->__construct();
$config = ClassRegistry::config('Model'); $config = ClassRegistry::config('Model');
@ -275,8 +276,10 @@ class ControllerTestCase extends CakeTestCase {
if ($methods === true) { if ($methods === true) {
$methods = array(); $methods = array();
} }
ClassRegistry::init($model);
list($plugin, $name) = pluginSplit($model);
$config = array_merge((array)$config, array('name' => $model)); $config = array_merge((array)$config, array('name' => $model));
$_model = $this->getMock($model, $methods, array($config)); $_model = $this->getMock($name, $methods, array($config));
ClassRegistry::removeObject($model); ClassRegistry::removeObject($model);
ClassRegistry::addObject($model, $_model); ClassRegistry::addObject($model, $_model);
} }
@ -289,14 +292,15 @@ class ControllerTestCase extends CakeTestCase {
if ($methods === true) { if ($methods === true) {
$methods = array(); $methods = array();
} }
list($plugin, $name) = pluginSplit($component);
if (!App::import('Component', $component)) { if (!App::import('Component', $component)) {
throw new MissingComponentFileException(array( throw new MissingComponentFileException(array(
'file' => Inflector::underscore($component) . '.php', 'file' => Inflector::underscore($name) . '.php',
'class' => $componentClass 'class' => $name.'Component'
)); ));
} }
$_component = $this->getMock($component.'Component', $methods, array(), '', false); $_component = $this->getMock($name.'Component', $methods, array(), '', false);
$_controller->Components->set($component, $_component); $_controller->Components->set($name, $_component);
} }
$_controller->constructClasses(); $_controller->constructClasses();

View file

@ -33,7 +33,7 @@ class MemcacheEngine extends CacheEngine {
* @var Memcache * @var Memcache
* @access private * @access private
*/ */
private $__Memcache = null; protected $_Memcache = null;
/** /**
* Settings * Settings
@ -74,12 +74,12 @@ class MemcacheEngine extends CacheEngine {
if (!is_array($this->settings['servers'])) { if (!is_array($this->settings['servers'])) {
$this->settings['servers'] = array($this->settings['servers']); $this->settings['servers'] = array($this->settings['servers']);
} }
if (!isset($this->__Memcache)) { if (!isset($this->_Memcache)) {
$return = false; $return = false;
$this->__Memcache = new Memcache(); $this->_Memcache = new Memcache();
foreach ($this->settings['servers'] as $server) { foreach ($this->settings['servers'] as $server) {
list($host, $port) = $this->_parseServerString($server); list($host, $port) = $this->_parseServerString($server);
if ($this->__Memcache->addServer($host, $port)) { if ($this->_Memcache->addServer($host, $port)) {
$return = true; $return = true;
} }
} }
@ -116,8 +116,7 @@ class MemcacheEngine extends CacheEngine {
/** /**
* Write data for key into cache. When using memcache as your cache engine * Write data for key into cache. When using memcache as your cache engine
* remember that the Memcache pecl extension does not support cache expiry times greater * remember that the Memcache pecl extension does not support cache expiry times greater
* than 30 days in the future. If you wish to create cache entries that do not expire, set the duration * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
* to `0` in your cache configuration.
* *
* @param string $key Identifier for the data * @param string $key Identifier for the data
* @param mixed $value Data to be cached * @param mixed $value Data to be cached
@ -126,7 +125,10 @@ class MemcacheEngine extends CacheEngine {
* @see http://php.net/manual/en/memcache.set.php * @see http://php.net/manual/en/memcache.set.php
*/ */
public function write($key, $value, $duration) { public function write($key, $value, $duration) {
return $this->__Memcache->set($key, $value, $this->settings['compress'], $duration); if ($duration > 30 * DAY) {
$duration = 0;
}
return $this->_Memcache->set($key, $value, $this->settings['compress'], $duration);
} }
/** /**
@ -136,7 +138,7 @@ class MemcacheEngine extends CacheEngine {
* @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
*/ */
public function read($key) { public function read($key) {
return $this->__Memcache->get($key); return $this->_Memcache->get($key);
} }
/** /**
@ -154,7 +156,7 @@ class MemcacheEngine extends CacheEngine {
__('Method increment() not implemented for compressed cache in %s', __CLASS__) __('Method increment() not implemented for compressed cache in %s', __CLASS__)
); );
} }
return $this->__Memcache->increment($key, $offset); return $this->_Memcache->increment($key, $offset);
} }
/** /**
@ -172,7 +174,7 @@ class MemcacheEngine extends CacheEngine {
__('Method decrement() not implemented for compressed cache in %s', __CLASS__) __('Method decrement() not implemented for compressed cache in %s', __CLASS__)
); );
} }
return $this->__Memcache->decrement($key, $offset); return $this->_Memcache->decrement($key, $offset);
} }
/** /**
@ -182,7 +184,7 @@ class MemcacheEngine extends CacheEngine {
* @return boolean True if the value was succesfully deleted, false if it didn't exist or couldn't be removed * @return boolean True if the value was succesfully deleted, false if it didn't exist or couldn't be removed
*/ */
public function delete($key) { public function delete($key) {
return $this->__Memcache->delete($key); return $this->_Memcache->delete($key);
} }
/** /**
@ -191,7 +193,7 @@ class MemcacheEngine extends CacheEngine {
* @return boolean True if the cache was succesfully cleared, false otherwise * @return boolean True if the cache was succesfully cleared, false otherwise
*/ */
public function clear($check) { public function clear($check) {
return $this->__Memcache->flush(); return $this->_Memcache->flush();
} }
/** /**
@ -202,8 +204,8 @@ class MemcacheEngine extends CacheEngine {
* @return boolean True if memcache server was connected * @return boolean True if memcache server was connected
*/ */
public function connect($host, $port = 11211) { public function connect($host, $port = 11211) {
if ($this->__Memcache->getServerStatus($host, $port) === 0) { if ($this->_Memcache->getServerStatus($host, $port) === 0) {
if ($this->__Memcache->connect($host, $port)) { if ($this->_Memcache->connect($host, $port)) {
return true; return true;
} }
return false; return false;

View file

@ -104,7 +104,7 @@ class DbConfigTask extends Shell {
} }
} }
$driver = $this->in('Driver:', array('db2', 'firebird', 'mssql', 'mysql', 'odbc', 'oracle', 'postgres', 'sqlite', 'sybase'), 'mysql'); $driver = $this->in('Driver:', array('mssql', 'mysql', 'oracle', 'postgres', 'sqlite'), 'mysql');
$persistent = $this->in('Persistent Connection?', array('y', 'n'), 'n'); $persistent = $this->in('Persistent Connection?', array('y', 'n'), 'n');
if (strtolower($persistent) == 'n') { if (strtolower($persistent) == 'n') {

View file

@ -48,11 +48,10 @@ class TaskCollection extends ObjectCollection {
* *
* @param string $task Task name to load * @param string $task Task name to load
* @param array $settings Settings for the task. * @param array $settings Settings for the task.
* @param boolean $enable Whether or not this task should be enabled by default
* @return Task A task object, Either the existing loaded task or a new one. * @return Task A task object, Either the existing loaded task or a new one.
* @throws MissingTaskFileException, MissingTaskClassException when the task could not be found * @throws MissingTaskFileException, MissingTaskClassException when the task could not be found
*/ */
public function load($task, $settings = array(), $enable = true) { public function load($task, $settings = array()) {
list($plugin, $name) = pluginSplit($task, true); list($plugin, $name) = pluginSplit($task, true);
if (isset($this->_loaded[$name])) { if (isset($this->_loaded[$name])) {
@ -70,6 +69,7 @@ class TaskCollection extends ObjectCollection {
$this->_loaded[$name] = new $taskClass( $this->_loaded[$name] = new $taskClass(
$this->_Shell->stdout, $this->_Shell->stderr, $this->_Shell->stdin $this->_Shell->stdout, $this->_Shell->stderr, $this->_Shell->stdin
); );
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) { if ($enable === true) {
$this->_enabled[] = $name; $this->_enabled[] = $name;
} }

View file

@ -18,11 +18,22 @@
*/ */
?> ?>
/**
* <?php echo $admin ?>index method
*
* @return void
*/
public function <?php echo $admin ?>index() { public function <?php echo $admin ?>index() {
$this-><?php echo $currentModelName ?>->recursive = 0; $this-><?php echo $currentModelName ?>->recursive = 0;
$this->set('<?php echo $pluralName ?>', $this->paginate()); $this->set('<?php echo $pluralName ?>', $this->paginate());
} }
/**
* <?php echo $admin ?>view method
*
* @param string $id
* @return void
*/
public function <?php echo $admin ?>view($id = null) { public function <?php echo $admin ?>view($id = null) {
$this-><?php echo $currentModelName; ?>->id = $id; $this-><?php echo $currentModelName; ?>->id = $id;
if (!$this-><?php echo $currentModelName; ?>->exists()) { if (!$this-><?php echo $currentModelName; ?>->exists()) {
@ -32,6 +43,11 @@
} }
<?php $compact = array(); ?> <?php $compact = array(); ?>
/**
* <?php echo $admin ?>add method
*
* @return void
*/
public function <?php echo $admin ?>add() { public function <?php echo $admin ?>add() {
if ($this->request->is('post')) { if ($this->request->is('post')) {
$this-><?php echo $currentModelName; ?>->create(); $this-><?php echo $currentModelName; ?>->create();
@ -66,6 +82,12 @@
} }
<?php $compact = array(); ?> <?php $compact = array(); ?>
/**
* <?php echo $admin ?>edit method
*
* @param string $id
* @return void
*/
public function <?php echo $admin; ?>edit($id = null) { public function <?php echo $admin; ?>edit($id = null) {
$this-><?php echo $currentModelName; ?>->id = $id; $this-><?php echo $currentModelName; ?>->id = $id;
if (!$this-><?php echo $currentModelName; ?>->exists()) { if (!$this-><?php echo $currentModelName; ?>->exists()) {
@ -104,6 +126,12 @@
?> ?>
} }
/**
* <?php echo $admin ?>delete method
*
* @param string $id
* @return void
*/
public function <?php echo $admin; ?>delete($id = null) { public function <?php echo $admin; ?>delete($id = null) {
if (!$this->request->is('post')) { if (!$this->request->is('post')) {
throw new MethodNotAllowedException(); throw new MethodNotAllowedException();

View file

@ -21,14 +21,23 @@
echo "<?php\n"; echo "<?php\n";
?> ?>
/**
* <?php echo $controllerName; ?> Controller
*
*/
class <?php echo $controllerName; ?>Controller extends <?php echo $plugin; ?>AppController { class <?php echo $controllerName; ?>Controller extends <?php echo $plugin; ?>AppController {
public $name = '<?php echo $controllerName; ?>';
<?php if ($isScaffold): ?> <?php if ($isScaffold): ?>
/**
* Scaffold
*
* @var mixed
*/
public $scaffold; public $scaffold;
<?php else: ?> <?php else: ?>
<?php <?php
if (count($helpers)): if (count($helpers)):
echo "/**\n * Helpers\n *\n * @var array\n */\n";
echo "\tvar \$helpers = array("; echo "\tvar \$helpers = array(";
for ($i = 0, $len = count($helpers); $i < $len; $i++): for ($i = 0, $len = count($helpers); $i < $len; $i++):
if ($i != $len - 1): if ($i != $len - 1):
@ -41,6 +50,7 @@ if (count($helpers)):
endif; endif;
if (count($components)): if (count($components)):
echo "/**\n * Components\n *\n * @var array\n */\n";
echo "\tpublic \$components = array("; echo "\tpublic \$components = array(";
for ($i = 0, $len = count($components); $i < $len; $i++): for ($i = 0, $len = count($components); $i < $len; $i++):
if ($i != $len - 1): if ($i != $len - 1):

View file

@ -20,21 +20,45 @@
*/ */
?> ?>
<?php echo '<?php' . "\n"; ?> <?php echo '<?php' . "\n"; ?>
/* <?php echo $model; ?> Fixture generated on: <?php echo date('Y-m-d H:m:s') . " : ". time(); ?> */ /* <?php echo $model; ?> Fixture generated on: <?php echo date('Y-m-d H:i:s') . " : ". time(); ?> */
/**
* <?php echo $model; ?>Fixture
*
*/
class <?php echo $model; ?>Fixture extends CakeTestFixture { class <?php echo $model; ?>Fixture extends CakeTestFixture {
public $name = '<?php echo $model; ?>';
<?php if ($table): ?> <?php if ($table): ?>
/**
* Table name
*
* @var string
*/
public $table = '<?php echo $table; ?>'; public $table = '<?php echo $table; ?>';
<?php endif; ?> <?php endif; ?>
<?php if ($import): ?> <?php if ($import): ?>
/**
* Import
*
* @var array
*/
public $import = <?php echo $import; ?>; public $import = <?php echo $import; ?>;
<?php endif; ?> <?php endif; ?>
<?php if ($schema): ?> <?php if ($schema): ?>
/**
* Fields
*
* @var array
*/
public $fields = <?php echo $schema; ?>; public $fields = <?php echo $schema; ?>;
<?php endif;?> <?php endif;?>
<?php if ($records): ?> <?php if ($records): ?>
/**
* Records
*
* @var array
*/
public $records = <?php echo $records; ?>; public $records = <?php echo $records; ?>;
<?php endif;?> <?php endif;?>
} }

View file

@ -20,23 +20,43 @@
*/ */
echo "<?php\n"; ?> echo "<?php\n"; ?>
/**
* <?php echo $name ?> Model
*
*/
class <?php echo $name ?> extends <?php echo $plugin; ?>AppModel { class <?php echo $name ?> extends <?php echo $plugin; ?>AppModel {
public $name = '<?php echo $name; ?>';
<?php if ($useDbConfig != 'default'): ?> <?php if ($useDbConfig != 'default'): ?>
/**
* Use database config
*
* @var string
*/
public $useDbConfig = '<?php echo $useDbConfig; ?>'; public $useDbConfig = '<?php echo $useDbConfig; ?>';
<?php endif;?> <?php endif;?>
<?php if ($useTable && $useTable !== Inflector::tableize($name)): <?php if ($useTable && $useTable !== Inflector::tableize($name)):
$table = "'$useTable'"; $table = "'$useTable'";
echo "/**\n * Use table\n *\n * @var mixed False or table name\n */\n";
echo "\tpublic \$useTable = $table;\n"; echo "\tpublic \$useTable = $table;\n";
endif; endif;
if ($primaryKey !== 'id'): ?> if ($primaryKey !== 'id'): ?>
/**
* Primary key field
*
* @var string
*/
public $primaryKey = '<?php echo $primaryKey; ?>'; public $primaryKey = '<?php echo $primaryKey; ?>';
<?php endif; <?php endif;
if ($displayField): ?> if ($displayField): ?>
/**
* Display field
*
* @var string
*/
public $displayField = '<?php echo $displayField; ?>'; public $displayField = '<?php echo $displayField; ?>';
<?php endif; <?php endif;
if (!empty($validate)): if (!empty($validate)):
echo "/**\n * Validation rules\n *\n * @var array\n */\n";
echo "\tpublic \$validate = array(\n"; echo "\tpublic \$validate = array(\n";
foreach ($validate as $field => $validations): foreach ($validate as $field => $validations):
echo "\t\t'$field' => array(\n"; echo "\t\t'$field' => array(\n";
@ -58,6 +78,7 @@ endif;
foreach ($associations as $assoc): foreach ($associations as $assoc):
if (!empty($assoc)): if (!empty($assoc)):
?> ?>
//The Associations below have been created with all possible keys, those that are not needed can be removed //The Associations below have been created with all possible keys, those that are not needed can be removed
<?php <?php
break; break;
@ -67,6 +88,7 @@ endforeach;
foreach (array('hasOne', 'belongsTo') as $assocType): foreach (array('hasOne', 'belongsTo') as $assocType):
if (!empty($associations[$assocType])): if (!empty($associations[$assocType])):
$typeCount = count($associations[$assocType]); $typeCount = count($associations[$assocType]);
echo "\n/**\n * $assocType associations\n *\n * @var array\n */";
echo "\n\tpublic \$$assocType = array("; echo "\n\tpublic \$$assocType = array(";
foreach ($associations[$assocType] as $i => $relation): foreach ($associations[$assocType] as $i => $relation):
$out = "\n\t\t'{$relation['alias']}' => array(\n"; $out = "\n\t\t'{$relation['alias']}' => array(\n";
@ -87,6 +109,7 @@ endforeach;
if (!empty($associations['hasMany'])): if (!empty($associations['hasMany'])):
$belongsToCount = count($associations['hasMany']); $belongsToCount = count($associations['hasMany']);
echo "\n/**\n * hasMany associations\n *\n * @var array\n */";
echo "\n\tpublic \$hasMany = array("; echo "\n\tpublic \$hasMany = array(";
foreach ($associations['hasMany'] as $i => $relation): foreach ($associations['hasMany'] as $i => $relation):
$out = "\n\t\t'{$relation['alias']}' => array(\n"; $out = "\n\t\t'{$relation['alias']}' => array(\n";
@ -112,6 +135,7 @@ endif;
if (!empty($associations['hasAndBelongsToMany'])): if (!empty($associations['hasAndBelongsToMany'])):
$habtmCount = count($associations['hasAndBelongsToMany']); $habtmCount = count($associations['hasAndBelongsToMany']);
echo "\n/**\n * hasAndBelongsToMany associations\n *\n * @var array\n */";
echo "\n\tpublic \$hasAndBelongsToMany = array("; echo "\n\tpublic \$hasAndBelongsToMany = array(";
foreach ($associations['hasAndBelongsToMany'] as $i => $relation): foreach ($associations['hasAndBelongsToMany'] as $i => $relation):
$out = "\n\t\t'{$relation['alias']}' => array(\n"; $out = "\n\t\t'{$relation['alias']}' => array(\n";

View file

@ -18,35 +18,80 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php) * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/ */
echo "<?php\n"; echo "<?php\n";
echo "/* ". $className ." Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n"; echo "/* ". $className ." Test cases generated on: " . date('Y-m-d H:i:s') . " : ". time() . "*/\n";
?> ?>
App::import('<?php echo $type; ?>', '<?php echo $plugin . $className;?>'); App::import('<?php echo $type; ?>', '<?php echo $plugin . $className;?>');
<?php if ($mock and strtolower($type) == 'controller'): ?> <?php if ($mock and strtolower($type) == 'controller'): ?>
/**
* Test<?php echo $fullClassName; ?>
*
*/
class Test<?php echo $fullClassName; ?> extends <?php echo $fullClassName; ?> { class Test<?php echo $fullClassName; ?> extends <?php echo $fullClassName; ?> {
/**
* Auto render
*
* @var boolean
*/
public $autoRender = false; public $autoRender = false;
/**
* Redirect action
*
* @param mixed $url
* @param mixed $status
* @param boolean $exit
* @return void
*/
public function redirect($url, $status = null, $exit = true) { public function redirect($url, $status = null, $exit = true) {
$this->redirectUrl = $url; $this->redirectUrl = $url;
} }
} }
<?php endif; ?> <?php endif; ?>
/**
* <?php echo $fullClassName; ?> Test Case
*
*/
class <?php echo $fullClassName; ?>TestCase extends CakeTestCase { class <?php echo $fullClassName; ?>TestCase extends CakeTestCase {
<?php if (!empty($fixtures)): ?> <?php if (!empty($fixtures)): ?>
/**
* Fixtures
*
* @var array
*/
public $fixtures = array('<?php echo join("', '", $fixtures); ?>'); public $fixtures = array('<?php echo join("', '", $fixtures); ?>');
<?php endif; ?> <?php endif; ?>
public function startTest() { /**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this-><?php echo $className . ' = ' . $construction; ?> $this-><?php echo $className . ' = ' . $construction; ?>
} }
public function endTest() { /**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this-><?php echo $className;?>); unset($this-><?php echo $className;?>);
ClassRegistry::flush(); ClassRegistry::flush();
parent::tearDown();
} }
<?php foreach ($methods as $method): ?> <?php foreach ($methods as $method): ?>
/**
* test<?php echo Inflector::classify($method); ?> method
*
* @return void
*/
public function test<?php echo Inflector::classify($method); ?>() { public function test<?php echo Inflector::classify($method); ?>() {
} }

View file

@ -72,7 +72,7 @@ if (!include(CORE_PATH . 'Cake' . DS . 'bootstrap.php')) {
} }
if (Configure::read('debug') < 1) { if (Configure::read('debug') < 1) {
die(__('Debug setting does not allow access to this url.', true)); die(__('Debug setting does not allow access to this url.'));
} }
require_once CAKE_TESTS_LIB . 'CakeTestSuiteDispatcher.php'; require_once CAKE_TESTS_LIB . 'CakeTestSuiteDispatcher.php';

View file

@ -134,6 +134,7 @@ class RequestHandlerComponent extends Component {
} }
} }
} }
$this->params = $controller->params;
$this->_set($settings); $this->_set($settings);
} }
@ -585,7 +586,9 @@ class RequestHandlerComponent extends Component {
} }
if ($cType != null) { if ($cType != null) {
if (empty($this->request->params['requested'])) {
$this->response->type($cType); $this->response->type($cType);
}
if (!empty($options['charset'])) { if (!empty($options['charset'])) {
$this->response->charset($options['charset']); $this->response->charset($options['charset']);

View file

@ -59,32 +59,47 @@ class ComponentCollection extends ObjectCollection {
* You can use `$settings['enabled'] = false` to disable callbacks on a component when loading it. * 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. * Callbacks default to on. Disabled component methods work as normal, only callbacks are disabled.
* *
* You can alias your component as an existing component by setting the 'className' key, i.e.,
* {{{
* public $components = array(
* 'Email' => array(
* 'className' => 'AliasedEmail'
* );
* );
* }}}
* All calls to the `Email` component would use `AliasedEmail` instead.
*
* @param string $component Component name to load * @param string $component Component name to load
* @param array $settings Settings for the component. * @param array $settings Settings for the component.
* @return Component A component object, Either the existing loaded component or a new one. * @return Component A component object, Either the existing loaded component or a new one.
* @throws MissingComponentFileException, MissingComponentClassException when the component could not be found * @throws MissingComponentFileException, MissingComponentClassException when the component could not be found
*/ */
public function load($component, $settings = array()) { public function load($component, $settings = array()) {
if (is_array($settings) && isset($settings['className'])) {
$alias = $component;
$component = $settings['className'];
}
list($plugin, $name) = pluginSplit($component); list($plugin, $name) = pluginSplit($component);
if (isset($this->_loaded[$name])) { if (!isset($alias)) {
return $this->_loaded[$name]; $alias = $name;
}
if (isset($this->_loaded[$alias])) {
return $this->_loaded[$alias];
} }
$componentClass = $name . 'Component'; $componentClass = $name . 'Component';
App::uses($componentClass, 'Controller/Component'); App::uses($componentClass, 'Controller/Component');
if (!class_exists($componentClass)) {
if (!class_exists($componentClass)) { if (!class_exists($componentClass)) {
throw new MissingComponentClassException(array( throw new MissingComponentClassException(array(
'file' => Inflector::underscore($component) . '.php', 'file' => Inflector::underscore($componentClass) . '.php',
'class' => $componentClass 'class' => $componentClass
)); ));
} }
} $this->_loaded[$alias] = new $componentClass($this, $settings);
$this->_loaded[$name] = new $componentClass($this, $settings);
$enable = isset($settings['enabled']) ? $settings['enabled'] : true; $enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) { if ($enable === true) {
$this->_enabled[] = $name; $this->_enabled[] = $alias;
} }
return $this->_loaded[$name]; return $this->_loaded[$alias];
} }
} }

View file

@ -638,15 +638,13 @@ class Controller extends Object {
if ($response === false) { if ($response === false) {
return; return;
} }
if (is_array($response)) { extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
foreach ($response as $resp) {
if (is_array($resp) && isset($resp['url'])) { $response = $this->beforeRedirect($url, $status, $exit);
extract($resp, EXTR_OVERWRITE); if ($response === false) {
} elseif ($resp !== null) { return;
$url = $resp;
}
}
} }
extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
if (function_exists('session_write_close')) { if (function_exists('session_write_close')) {
session_write_close(); session_write_close();
@ -673,6 +671,28 @@ class Controller extends Object {
} }
} }
/**
* Parse beforeRedirect Response
*
* @param mixed $response Response from beforeRedirect callback
* @param mixed $url The same value of beforeRedirect
* @param integer $status The same value of beforeRedirect
* @param boolean $exit The same value of beforeRedirect
* @return array Array with keys url, status and exit
*/
protected function _parseBeforeRedirect($response, $url, $status, $exit) {
if (is_array($response)) {
foreach ($response as $resp) {
if (is_array($resp) && isset($resp['url'])) {
extract($resp, EXTR_OVERWRITE);
} elseif ($resp !== null) {
$url = $resp;
}
}
}
return compact('url', 'status', 'exit');
}
/** /**
* Convenience and object wrapper method for CakeResponse::header(). * Convenience and object wrapper method for CakeResponse::header().
* *
@ -984,6 +1004,23 @@ class Controller extends Object {
public function beforeRender() { public function beforeRender() {
} }
/**
* The beforeRedirect method is invoked when the controller's redirect method is called but before any
* further action. If this method returns false the controller will not continue on to redirect the request.
* The $url, $status and $exit variables have same meaning as for the controller's method. You can also
* return a string which will be interpreted as the url to redirect to or return associative array with
* key 'url' and optionally 'status' and 'exit'.
*
* @param mixed $url A string or array-based URL pointing to another location within the app,
* or an absolute URL
* @param integer $status Optional HTTP status code (eg: 404)
* @param boolean $exit If true, exit() will be called after the redirect
* @return boolean
*/
public function beforeRedirect($url, $status = null, $exit = true) {
return true;
}
/** /**
* Called after the controller action is run and rendered. * Called after the controller action is run and rendered.
* *

View file

@ -370,6 +370,24 @@ class MissingShellFileException extends CakeException {
protected $_messageTemplate = "Shell file %s could not be loaded."; protected $_messageTemplate = "Shell file %s could not be loaded.";
} }
/**
* Exception class to be thrown when a database file is not found
*
* @package cake.libs
*/
class MissingDatasourceConfigException extends CakeException {
protected $_messageTemplate = 'Database connection "%s" could not be loaded.';
}
/**
* Exception class to be thrown when a database file is not found
*
* @package cake.libs
*/
class MissingDatasourceFileException extends CakeException {
protected $_messageTemplate = 'Database connection "%s" could not be loaded.';
}
/** /**
* Exception class to be thrown when a database table is not found in the datasource * Exception class to be thrown when a database table is not found in the datasource
* *

View file

@ -43,7 +43,7 @@ class AclNode extends AppModel {
* @var array * @var array
* @access public * @access public
*/ */
public $actsAs = array('Tree' => 'nested'); public $actsAs = array('Tree' => array('nested'));
/** /**
* Constructor * Constructor

View file

@ -83,13 +83,31 @@ class BehaviorCollection extends ObjectCollection {
* to load a behavior with callbacks disabled. By default callbacks are enabled. Disable behaviors * to load a behavior with callbacks disabled. By default callbacks are enabled. Disable behaviors
* can still be used as normal. * can still be used as normal.
* *
* You can alias your behavior as an existing behavior by setting the 'className' key, i.e.,
* {{{
* public $actsAs = array(
* 'Tree' => array(
* 'className' => 'AliasedTree'
* );
* );
* }}}
* All calls to the `Tree` behavior would use `AliasedTree` instead.
*
* @param string $behavior CamelCased name of the behavior to load * @param string $behavior CamelCased name of the behavior to load
* @param array $config Behavior configuration parameters * @param array $config Behavior configuration parameters
* @return boolean True on success, false on failure * @return boolean True on success, false on failure
* @throws MissingBehaviorFileException or MissingBehaviorClassException when a behavior could not be found. * @throws MissingBehaviorFileException or MissingBehaviorClassException when a behavior could not be found.
*/ */
public function load($behavior, $config = array()) { public function load($behavior, $config = array()) {
if (is_array($config) && isset($config['className'])) {
$alias = $behavior;
$behavior = $config['className'];
}
list($plugin, $name) = pluginSplit($behavior); list($plugin, $name) = pluginSplit($behavior);
if (!isset($alias)) {
$alias = $name;
}
$class = $name . 'Behavior'; $class = $name . 'Behavior';
App::uses($class, 'Model/Behavior'); App::uses($class, 'Model/Behavior');
@ -100,19 +118,19 @@ class BehaviorCollection extends ObjectCollection {
)); ));
} }
if (!isset($this->{$name})) { if (!isset($this->{$alias})) {
if (ClassRegistry::isKeySet($class)) { if (ClassRegistry::isKeySet($class)) {
$this->_loaded[$name] = ClassRegistry::getObject($class); $this->_loaded[$alias] = ClassRegistry::getObject($class);
} else { } else {
$this->_loaded[$name] = new $class(); $this->_loaded[$alias] = new $class();
ClassRegistry::addObject($class, $this->_loaded[$name]); ClassRegistry::addObject($class, $this->_loaded[$alias]);
if (!empty($plugin)) { if (!empty($plugin)) {
ClassRegistry::addObject($plugin . '.' . $class, $this->_loaded[$name]); ClassRegistry::addObject($plugin . '.' . $class, $this->_loaded[$alias]);
} }
} }
} elseif (isset($this->_loaded[$name]->settings) && isset($this->_loaded[$name]->settings[$this->modelName])) { } elseif (isset($this->_loaded[$alias]->settings) && isset($this->_loaded[$alias]->settings[$this->modelName])) {
if ($config !== null && $config !== false) { if ($config !== null && $config !== false) {
$config = array_merge($this->_loaded[$name]->settings[$this->modelName], $config); $config = array_merge($this->_loaded[$alias]->settings[$this->modelName], $config);
} else { } else {
$config = array(); $config = array();
} }
@ -120,12 +138,12 @@ class BehaviorCollection extends ObjectCollection {
if (empty($config)) { if (empty($config)) {
$config = array(); $config = array();
} }
$this->_loaded[$name]->setup(ClassRegistry::getObject($this->modelName), $config); $this->_loaded[$alias]->setup(ClassRegistry::getObject($this->modelName), $config);
foreach ($this->_loaded[$name]->mapMethods as $method => $alias) { foreach ($this->_loaded[$alias]->mapMethods as $method => $methodAlias) {
$this->_mappedMethods[$method] = array($name, $alias); $this->_mappedMethods[$method] = array($alias, $methodAlias);
} }
$methods = get_class_methods($this->_loaded[$name]); $methods = get_class_methods($this->_loaded[$alias]);
$parentMethods = array_flip(get_class_methods('ModelBehavior')); $parentMethods = array_flip(get_class_methods('ModelBehavior'));
$callbacks = array( $callbacks = array(
'setup', 'cleanup', 'beforeFind', 'afterFind', 'beforeSave', 'afterSave', 'setup', 'cleanup', 'beforeFind', 'afterFind', 'beforeSave', 'afterSave',
@ -139,16 +157,16 @@ class BehaviorCollection extends ObjectCollection {
!in_array($m, $callbacks) !in_array($m, $callbacks)
); );
if ($methodAllowed) { if ($methodAllowed) {
$this->_methods[$m] = array($name, $m); $this->_methods[$m] = array($alias, $m);
} }
} }
} }
$configDisabled = isset($config['enabled']) && $config['enabled'] === false; $configDisabled = isset($config['enabled']) && $config['enabled'] === false;
if (!in_array($name, $this->_enabled) && !$configDisabled) { if (!in_array($alias, $this->_enabled) && !$configDisabled) {
$this->enable($name); $this->enable($alias);
} elseif ($configDisabled) { } elseif ($configDisabled) {
$this->disable($name); $this->disable($alias);
} }
return true; return true;
} }

View file

@ -368,7 +368,7 @@ class CakeSchema extends Object {
$out .= "}\n"; $out .= "}\n";
$file = new SplFileObject($path . DS . $file, 'w+'); $file = new SplFileObject($path . DS . $file, 'w+');
$content = "<?php \n/* {$name} schema generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>"; $content = "<?php \n/* {$name} schema generated on: " . date('Y-m-d H:i:s') . " : ". time() . "*/\n{$out}?>";
if ($file->fwrite($content)) { if ($file->fwrite($content)) {
return $content; return $content;
} }

View file

@ -78,6 +78,8 @@ class ConnectionManager {
* *
* @param string $name The name of the DataSource, as defined in app/config/database.php * @param string $name The name of the DataSource, as defined in app/config/database.php
* @return object Instance * @return object Instance
* @throws MissingDatasourceConfigException
* @throws MissingDatasourceFileException
*/ */
public static function getDataSource($name) { public static function getDataSource($name) {
if (empty(self::$_init)) { if (empty(self::$_init)) {
@ -94,19 +96,12 @@ class ConnectionManager {
} }
if (empty(self::$_connectionsEnum[$name])) { if (empty(self::$_connectionsEnum[$name])) {
trigger_error(__("ConnectionManager::getDataSource - Non-existent data source %s", $name), E_USER_ERROR); throw new MissingDatasourceConfigException(array('config' => $name));
$null = null;
return $null;
} }
$conn = self::$_connectionsEnum[$name]; $conn = self::$_connectionsEnum[$name];
$class = $conn['classname']; $class = $conn['classname'];
if (self::loadDataSource($name) === null) {
trigger_error(__("ConnectionManager::getDataSource - Could not load class %s", $class), E_USER_ERROR);
$null = null;
return $null;
}
self::$_dataSources[$name] = new $class(self::$config->{$name}); self::$_dataSources[$name] = new $class(self::$config->{$name});
self::$_dataSources[$name]->configKeyName = $name; self::$_dataSources[$name]->configKeyName = $name;
@ -151,6 +146,7 @@ class ConnectionManager {
* or an array containing the filename (without extension) and class name of the object, * or an array containing the filename (without extension) and class name of the object,
* to be found in app/models/datasources/ or cake/libs/model/datasources/. * to be found in app/models/datasources/ or cake/libs/model/datasources/.
* @return boolean True on success, null on failure or false if the class is already loaded * @return boolean True on success, null on failure or false if the class is already loaded
* @throws MissingDatasourceFileException
*/ */
public static function loadDataSource($connName) { public static function loadDataSource($connName) {
if (empty(self::$_init)) { if (empty(self::$_init)) {
@ -177,8 +173,7 @@ class ConnectionManager {
App::uses($conn['classname'], $plugin . 'Model/Datasource' . $package); App::uses($conn['classname'], $plugin . 'Model/Datasource' . $package);
if (!class_exists($conn['classname'])) { if (!class_exists($conn['classname'])) {
trigger_error(__('ConnectionManager::loadDataSource - Unable to import DataSource class %s', $conn['classname']), E_USER_ERROR); throw new MissingDatasourceFileException(array('class' => $conn['classname'], 'plugin' => $conn['plugin']));
return null;
} }
return true; return true;
} }

View file

@ -106,6 +106,9 @@ class DatabaseSession implements CakeSessionHandlerInterface {
* @access private * @access private
*/ */
public function write($id, $data) { public function write($id, $data) {
if (!$id) {
return false;
}
$expires = time() + (Configure::read('Session.timeout') * 60); $expires = time() + (Configure::read('Session.timeout') * 60);
return ClassRegistry::getObject('Session')->save(compact('id', 'data', 'expires')); return ClassRegistry::getObject('Session')->save(compact('id', 'data', 'expires'));
} }

View file

@ -173,7 +173,7 @@ class CakeRoute {
/** /**
* Checks to see if the given URL can be parsed by this route. * Checks to see if the given URL can be parsed by this route.
* If the route can be parsed an array of parameters will be returned if not * If the route can be parsed an array of parameters will be returned; if not
* false will be returned. String urls are parsed if they match a routes regular expression. * false will be returned. String urls are parsed if they match a routes regular expression.
* *
* @param string $url The url to attempt to parse. * @param string $url The url to attempt to parse.
@ -245,8 +245,8 @@ class CakeRoute {
} }
/** /**
* Attempt to match a url array. If the url matches the route parameters + settings, then * Attempt to match a url array. If the url matches the route parameters and settings, then
* return a generated string url. If the url doesn't match the route parameters false will be returned. * return a generated string url. If the url doesn't match the route parameters, false will be returned.
* This method handles the reverse routing or conversion of url arrays into string urls. * This method handles the reverse routing or conversion of url arrays into string urls.
* *
* @param array $url An array of parameters to check matching with. * @param array $url An array of parameters to check matching with.

View file

@ -221,21 +221,25 @@ class Router {
* Shows connecting a route with custom route parameters as well as providing patterns for those parameters. * Shows connecting a route with custom route parameters as well as providing patterns for those parameters.
* Patterns for routing parameters do not need capturing groups, as one will be added for each route params. * Patterns for routing parameters do not need capturing groups, as one will be added for each route params.
* *
* $options offers two 'special' keys. `pass` and `persist` have special meaning in the $options array. * $options offers three 'special' keys. `pass`, `persist` and `routeClass` have special meaning in the $options array.
* *
* `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a * `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a
* parameter to pass will remove it from the regular route array. Ex. `'pass' => array('slug')` * parameter to pass will remove it from the regular route array. Ex. `'pass' => array('slug')`
* *
* `persist` is used to define which route parameters should be automatically included when generating * `persist` is used to define which route parameters should be automatically included when generating
* new urls. You can override peristent parameters by redifining them in a url or remove them by * new urls. You can override persistent parameters by redefining them in a url or remove them by
* setting the parameter to `false`. Ex. `'persist' => array('lang')` * setting the parameter to `false`. Ex. `'persist' => array('lang')`
* *
* `routeClass` is used to extend and change how individual routes parse requests and handle reverse routing,
* via a custom routing class. Ex. `'routeClass' => 'SlugRoute'`
*
* @param string $route A string describing the template of the route * @param string $route A string describing the template of the route
* @param array $defaults An array describing the default route parameters. These parameters will be used by default * @param array $defaults An array describing the default route parameters. These parameters will be used by default
* and can supply routing parameters that are not dynamic. See above. * and can supply routing parameters that are not dynamic. See above.
* @param array $options An array matching the named elements in the route to regular expressions which that * @param array $options An array matching the named elements in the route to regular expressions which that
* element should match. Also contains additional parameters such as which routed parameters should be * element should match. Also contains additional parameters such as which routed parameters should be
* shifted into the passed arguments. As well as supplying patterns for routing parameters. * shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a
* custom routing class.
* @see routes * @see routes
* @return array Array of routes * @return array Array of routes
* @throws RouterException * @throws RouterException
@ -731,7 +735,7 @@ class Router {
* *
* @param $which A zero-based array index representing the route to move. For example, * @param $which A zero-based array index representing the route to move. For example,
* if 3 routes have been added, the last route would be 2. * if 3 routes have been added, the last route would be 2.
* @return boolean Retuns false if no route exists at the position specified by $which. * @return boolean Returns false if no route exists at the position specified by $which.
*/ */
public static function promote($which = null) { public static function promote($which = null) {
if ($which === null) { if ($which === null) {
@ -752,7 +756,7 @@ class Router {
* Returns an URL pointing to a combination of controller and action. Param * Returns an URL pointing to a combination of controller and action. Param
* $url can be: * $url can be:
* *
* - Empty - the method will find address to actuall controller/action. * - Empty - the method will find address to actual controller/action.
* - '/' - the method will find base URL of application. * - '/' - the method will find base URL of application.
* - A combination of controller/action - the method will find url for it. * - A combination of controller/action - the method will find url for it.
* *
@ -1068,7 +1072,7 @@ class Router {
} }
/** /**
* Reverses a parsed parameter array into a string. Works similarily to Router::url(), but * Reverses a parsed parameter array into a string. Works similarly to Router::url(), but
* Since parsed URL's contain additional 'pass' and 'named' as well as 'url.url' keys. * Since parsed URL's contain additional 'pass' and 'named' as well as 'url.url' keys.
* Those keys need to be specially handled in order to reverse a params array into a string url. * Those keys need to be specially handled in order to reverse a params array into a string url.
* *
@ -1080,11 +1084,14 @@ class Router {
*/ */
public static function reverse($params) { public static function reverse($params) {
if ($params instanceof CakeRequest) { if ($params instanceof CakeRequest) {
$url = $params->query;
$params = $params->params; $params = $params->params;
} else {
$url = $params['url'];
} }
$pass = $params['pass']; $pass = $params['pass'];
$named = $params['named']; $named = $params['named'];
$url = $params['url'];
unset( unset(
$params['pass'], $params['named'], $params['paging'], $params['models'], $params['url'], $url['url'], $params['pass'], $params['named'], $params['paging'], $params['models'], $params['url'], $url['url'],
$params['autoRender'], $params['bare'], $params['requested'], $params['return'] $params['autoRender'], $params['bare'], $params['requested'], $params['return']
@ -1199,7 +1206,7 @@ class Router {
} }
/** /**
* Takes an passed params and converts it to args * Takes a passed params and converts it to args
* *
* @param array $params * @param array $params
* @return array Array containing passed and named parameters * @return array Array containing passed and named parameters
@ -1263,5 +1270,6 @@ class Router {
return compact('pass', 'named'); return compact('pass', 'named');
} }
} }
//Save the initial state //Save the initial state
Router::reload(); Router::reload();

View file

@ -83,12 +83,13 @@ class CakeTestSuite extends PHPUnit_Framework_TestSuite {
if (!$this->_fixtureManager) { if (!$this->_fixtureManager) {
return; return;
} }
$classes = array();
foreach ($this->getIterator() as $test) { foreach ($this->getIterator() as $test) {
if ($test instanceof CakeTestCase) {
$this->_fixtureManager->fixturize($test); $this->_fixtureManager->fixturize($test);
$test->fixtureManager = $this->_fixtureManager; $test->fixtureManager = $this->_fixtureManager;
} }
} }
}
/** /**
* Method that is called after all the tests of this test suite are run. * Method that is called after all the tests of this test suite are run.

View file

@ -52,6 +52,13 @@ class CakeTestFixture {
* *
*/ */
public function __construct() { public function __construct() {
if ($this->name === null) {
if (preg_match('/^(.*)Fixture$/', get_class($this), $matches)) {
$this->name = $matches[1];
} else {
$this->name = get_class($this);
}
}
$this->Schema = new CakeSchema(array('name' => 'TestSuite', 'connection' => 'test')); $this->Schema = new CakeSchema(array('name' => 'TestSuite', 'connection' => 'test'));
$this->init(); $this->init();
} }

View file

@ -222,7 +222,7 @@ abstract class ObjectCollection {
} }
/** /**
* Adds or overwrites an instatiated object to the collection * Adds or overwrites an instantiated object to the collection
* *
* @param string $name Name of the object * @param string $name Name of the object
* @param Object $object The object to use * @param Object $object The object to use

View file

@ -63,10 +63,10 @@ class Set {
* @param boolean $isArray Force to tell $var is an array when $var is empty * @param boolean $isArray Force to tell $var is an array when $var is empty
* @return mixed Either filtered array, or true/false when in callback * @return mixed Either filtered array, or true/false when in callback
*/ */
public static function filter($var, $isArray = false) { public static function filter(array $var) {
foreach ((array)$var as $k => $v) { foreach ($var as $k => $v) {
if (!empty($v) && is_array($v)) { if (is_array($v)) {
$var[$k] = array_filter($v, array('Set', '_filter')); $var[$k] = Set::filter($v);
} }
} }
return array_filter($var, array('Set', '_filter')); return array_filter($var, array('Set', '_filter'));

View file

@ -246,7 +246,7 @@ class Validation {
} }
break; break;
default: default:
self::$errors[] = __('You must define the $operator parameter for Validation::comparison()', true); self::$errors[] = __('You must define the $operator parameter for Validation::comparison()');
break; break;
} }
return false; return false;
@ -265,7 +265,7 @@ class Validation {
extract(self::_defaults($check)); extract(self::_defaults($check));
} }
if ($regex === null) { if ($regex === null) {
self::$errors[] = __('You must define a regular expression for Validation::custom()', true); self::$errors[] = __('You must define a regular expression for Validation::custom()');
return false; return false;
} }
return self::_check($check, $regex); return self::_check($check, $regex);

View file

@ -1003,7 +1003,10 @@ class FormHelper extends AppHelper {
if (empty($options['value'])) { if (empty($options['value'])) {
$options['value'] = 1; $options['value'] = 1;
} elseif (!empty($value) && $value === $options['value']) { } elseif (
(!isset($options['checked']) && !empty($value) && $value === $options['value']) ||
!empty($options['checked'])
) {
$options['checked'] = 'checked'; $options['checked'] = 'checked';
} }
if ($options['hiddenField']) { if ($options['hiddenField']) {
@ -1324,7 +1327,6 @@ class FormHelper extends AppHelper {
unset($options['confirm']); unset($options['confirm']);
} }
$url = $this->url($url);
$formName = uniqid('post_'); $formName = uniqid('post_');
$out = $this->create(false, array('url' => $url, 'name' => $formName, 'id' => $formName, 'style' => 'display:none;')); $out = $this->create(false, array('url' => $url, 'name' => $formName, 'id' => $formName, 'style' => 'display:none;'));
if (isset($options['data']) && is_array($options['data'])) { if (isset($options['data']) && is_array($options['data'])) {
@ -2023,7 +2025,7 @@ class FormHelper extends AppHelper {
return $options; return $options;
} }
$name = $this->_View->field; $name = !empty($this->_View->field) ? $this->_View->field : $this->_View->model;
if (!empty($this->_View->fieldSuffix)) { if (!empty($this->_View->fieldSuffix)) {
$name .= '[' . $this->_View->fieldSuffix . ']'; $name .= '[' . $this->_View->fieldSuffix . ']';
} }

View file

@ -95,7 +95,6 @@ class PaginatorHelper extends AppHelper {
* @throws CakeException When the AjaxProvider helper does not implement a link method. * @throws CakeException When the AjaxProvider helper does not implement a link method.
*/ */
function __construct(View $View, $settings = array()) { function __construct(View $View, $settings = array()) {
parent::__construct($View, $settings);
$ajaxProvider = isset($settings['ajax']) ? $settings['ajax'] : 'Js'; $ajaxProvider = isset($settings['ajax']) ? $settings['ajax'] : 'Js';
$this->helpers[] = $ajaxProvider; $this->helpers[] = $ajaxProvider;
$this->_ajaxHelperClass = $ajaxProvider; $this->_ajaxHelperClass = $ajaxProvider;
@ -106,6 +105,7 @@ class PaginatorHelper extends AppHelper {
__('%s does not implement a link() method, it is incompatible with PaginatorHelper'), $classname __('%s does not implement a link() method, it is incompatible with PaginatorHelper'), $classname
)); ));
} }
parent::__construct($View, $settings);
} }
/** /**

View file

@ -177,8 +177,9 @@ class TextHelper extends AppHelper {
*/ */
public function autoLinkEmails($text, $options = array()) { public function autoLinkEmails($text, $options = array()) {
$this->_linkOptions = $options; $this->_linkOptions = $options;
$atom = '[a-z0-9!#$%&\'*+\/=?^_`{|}~-]';
return preg_replace_callback( return preg_replace_callback(
'#([_A-Za-z0-9+-]+(?:\.[_A-Za-z0-9+-]+)*@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)#', '/(' . $atom . '+(?:\.' . $atom . '+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)*)/i',
array(&$this, '_linkEmails'), array(&$this, '_linkEmails'),
$text $text
); );

View file

@ -41,16 +41,33 @@ class HelperCollection extends ObjectCollection {
* can set `$settings['enabled'] = false` to disable callbacks. This alias is provided so that when * can set `$settings['enabled'] = false` to disable callbacks. This alias is provided so that when
* declaring $helpers arrays you can disable callbacks on helpers. * declaring $helpers arrays you can disable callbacks on helpers.
* *
* You can alias your helper as an existing helper by setting the 'className' key, i.e.,
* {{{
* public $components = array(
* 'Html' => array(
* 'className' => 'AliasedHtml'
* );
* );
* }}}
* All calls to the `Html` helper would use `AliasedHtml` instead.
*
* @param string $helper Helper name to load * @param string $helper Helper name to load
* @param array $settings Settings for the helper. * @param array $settings Settings for the helper.
* @return Helper A helper object, Either the existing loaded helper or a new one. * @return Helper A helper object, Either the existing loaded helper or a new one.
* @throws MissingHelperFileException, MissingHelperClassException when the helper could not be found * @throws MissingHelperFileException, MissingHelperClassException when the helper could not be found
*/ */
public function load($helper, $settings = array()) { public function load($helper, $settings = array()) {
list($plugin, $name) = pluginSplit($helper, true); if (is_array($settings) && isset($settings['className'])) {
$alias = $helper;
$helper = $settings['className'];
}
list($plugin, $name) = pluginSplit($helper);
if (!isset($alias)) {
$alias = $name;
}
if (isset($this->_loaded[$name])) { if (isset($this->_loaded[$alias])) {
return $this->_loaded[$name]; return $this->_loaded[$alias];
} }
$helperClass = $name . 'Helper'; $helperClass = $name . 'Helper';
App::uses($helperClass, $plugin . 'View/Helper'); App::uses($helperClass, $plugin . 'View/Helper');
@ -60,17 +77,17 @@ class HelperCollection extends ObjectCollection {
'file' => $helperClass . '.php' 'file' => $helperClass . '.php'
)); ));
} }
$this->_loaded[$name] = new $helperClass($this->_View, $settings); $this->_loaded[$alias] = new $helperClass($this->_View, $settings);
$vars = array('request', 'theme', 'plugin'); $vars = array('request', 'theme', 'plugin');
foreach ($vars as $var) { foreach ($vars as $var) {
$this->_loaded[$name]->{$var} = $this->_View->{$var}; $this->_loaded[$alias]->{$var} = $this->_View->{$var};
} }
$enable = isset($settings['enabled']) ? $settings['enabled'] : true; $enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) { if ($enable === true) {
$this->_enabled[] = $name; $this->_enabled[] = $alias;
} }
return $this->_loaded[$name]; return $this->_loaded[$alias];
} }
} }

View file

@ -326,6 +326,7 @@ class View extends Object {
return $contents; return $contents;
} }
} }
$file = $this->_getElementFilename($name, $plugin); $file = $this->_getElementFilename($name, $plugin);
if ($file) { if ($file) {
@ -623,7 +624,7 @@ class View extends Object {
public function loadHelpers() { public function loadHelpers() {
$helpers = HelperCollection::normalizeObjectArray($this->helpers); $helpers = HelperCollection::normalizeObjectArray($this->helpers);
foreach ($helpers as $name => $properties) { foreach ($helpers as $name => $properties) {
$this->Helpers->load($properties['class'], $properties['settings'], true); $this->Helpers->load($properties['class'], $properties['settings']);
} }
$this->_helpersLoaded = true; $this->_helpersLoaded = true;
} }
@ -698,10 +699,7 @@ class View extends Object {
} }
$paths = $this->_paths($this->plugin); $paths = $this->_paths($this->plugin);
$exts = array($this->ext); $exts = $this->_getExtensions();
if ($this->ext !== '.ctp') {
array_push($exts, '.ctp');
}
foreach ($exts as $ext) { foreach ($exts as $ext) {
foreach ($paths as $path) { foreach ($paths as $path) {
if (file_exists($path . $name . $ext)) { if (file_exists($path . $name . $ext)) {
@ -742,10 +740,7 @@ class View extends Object {
$paths = $this->_paths($this->plugin); $paths = $this->_paths($this->plugin);
$file = 'layouts' . DS . $subDir . $name; $file = 'layouts' . DS . $subDir . $name;
$exts = array($this->ext); $exts = $this->_getExtensions();
if ($this->ext !== '.ctp') {
array_push($exts, '.ctp');
}
foreach ($exts as $ext) { foreach ($exts as $ext) {
foreach ($paths as $path) { foreach ($paths as $path) {
if (file_exists($path . $file . $ext)) { if (file_exists($path . $file . $ext)) {
@ -756,6 +751,21 @@ class View extends Object {
throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext)); throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
} }
/**
* Get the extensions that view files can use.
*
* @return array Array of extensions view files use.
* @access protected
*/
function _getExtensions() {
$exts = array($this->ext);
if ($this->ext !== '.ctp') {
array_push($exts, '.ctp');
}
return $exts;
}
/** /**
* Finds an element filename, returns false on failure. * Finds an element filename, returns false on failure.
* *
@ -765,9 +775,12 @@ class View extends Object {
*/ */
protected function _getElementFileName($name, $plugin = null) { protected function _getElementFileName($name, $plugin = null) {
$paths = $this->_paths($plugin); $paths = $this->_paths($plugin);
$exts = $this->_getExtensions();
foreach ($exts as $ext) {
foreach ($paths as $path) { foreach ($paths as $path) {
if (file_exists($path . 'elements' . DS . $name . $this->ext)) { if (file_exists($path . 'elements' . DS . $name . $ext)) {
return $path . 'elements' . DS . $name . $this->ext; return $path . 'elements' . DS . $name . $ext;
}
} }
} }
return false; return false;

View file

@ -18,7 +18,7 @@
?> ?>
<h2><?php echo $name; ?></h2> <h2><?php echo $name; ?></h2>
<p class="error"> <p class="error">
<strong><?php echo __('Error', true); ?>: </strong> <strong><?php echo __('Error'); ?>: </strong>
<?php echo __('An Internal Error Has Occurred.'); ?> <?php echo __('An Internal Error Has Occurred.'); ?>
</p> </p>
<?php <?php

View file

@ -35,7 +35,7 @@
<body> <body>
<div id="container"> <div id="container">
<div id="header"> <div id="header">
<h1><?php echo $this->Html->link(__('CakePHP: the rapid development php framework', true), 'http://cakephp.org'); ?></h1> <h1><?php echo $this->Html->link(__('CakePHP: the rapid development php framework'), 'http://cakephp.org'); ?></h1>
</div> </div>
<div id="content"> <div id="content">

View file

@ -84,7 +84,11 @@ endif;
<?php <?php
if (isset($filePresent)): if (isset($filePresent)):
App::uses('ConnectionManager', 'Model'); App::uses('ConnectionManager', 'Model');
try {
$connected = ConnectionManager::getDataSource('default'); $connected = ConnectionManager::getDataSource('default');
} catch (Exception $e) {
$connected = false;
}
?> ?>
<p> <p>
<?php <?php
@ -113,7 +117,7 @@ You can also add some CSS styles for your pages at: APP/webroot/css.');
<p> <p>
<?php <?php
echo $this->Html->link( echo $this->Html->link(
sprintf('<strong>%s</strong> %s', __('New', true), __('CakePHP 1.3 Docs', true)), sprintf('<strong>%s</strong> %s', __('New'), __('CakePHP 1.3 Docs')),
'http://book.cakephp.org/view/875/x1-3-Collection', 'http://book.cakephp.org/view/875/x1-3-Collection',
array('target' => '_blank', 'escape' => false) array('target' => '_blank', 'escape' => false)
); );
@ -122,7 +126,7 @@ You can also add some CSS styles for your pages at: APP/webroot/css.');
<p> <p>
<?php <?php
echo $this->Html->link( echo $this->Html->link(
__('The 15 min Blog Tutorial', true), __('The 15 min Blog Tutorial'),
'http://book.cakephp.org/view/1528/Blog', 'http://book.cakephp.org/view/1528/Blog',
array('target' => '_blank', 'escape' => false) array('target' => '_blank', 'escape' => false)
); );

View file

@ -140,9 +140,9 @@ $otherSingularVar = Inflector::variable($_alias);
} }
echo "\t\t\t<td class=\"actions\">\n"; echo "\t\t\t<td class=\"actions\">\n";
echo "\t\t\t\t" . $this->Html->link(__('View', true), array('controller' => $_details['controller'], 'action' => 'view', ${$otherSingularVar}[$_details['primaryKey']])). "\n"; echo "\t\t\t\t" . $this->Html->link(__('View'), array('controller' => $_details['controller'], 'action' => 'view', ${$otherSingularVar}[$_details['primaryKey']])). "\n";
echo "\t\t\t\t" . $this->Html->link(__('Edit', true), array('controller' => $_details['controller'], 'action' => 'edit', ${$otherSingularVar}[$_details['primaryKey']])). "\n"; echo "\t\t\t\t" . $this->Html->link(__('Edit'), array('controller' => $_details['controller'], 'action' => 'edit', ${$otherSingularVar}[$_details['primaryKey']])). "\n";
echo "\t\t\t\t" . $this->Html->link(__('Delete', true), array('controller' => $_details['controller'], 'action' => 'delete', ${$otherSingularVar}[$_details['primaryKey']]), null, __('Are you sure you want to delete', true).' #' . ${$otherSingularVar}[$_details['primaryKey']] . '?'). "\n"; echo "\t\t\t\t" . $this->Html->link(__('Delete'), array('controller' => $_details['controller'], 'action' => 'delete', ${$otherSingularVar}[$_details['primaryKey']]), null, __('Are you sure you want to delete', true).' #' . ${$otherSingularVar}[$_details['primaryKey']] . '?'). "\n";
echo "\t\t\t</td>\n"; echo "\t\t\t</td>\n";
echo "\t\t</tr>\n"; echo "\t\t</tr>\n";
endforeach; endforeach;

View file

@ -300,10 +300,21 @@ if (!function_exists('sortByKey')) {
break; break;
case 'HTTP_BASE': case 'HTTP_BASE':
$host = env('HTTP_HOST'); $host = env('HTTP_HOST');
if (substr_count($host, '.') !== 1) { $parts = explode('.', $host);
return preg_replace('/^([^.])*/i', null, env('HTTP_HOST')); $count = count($parts);
}
if ($count === 1) {
return '.' . $host; return '.' . $host;
} elseif ($count === 2) {
return '.' . $host;
} elseif ($count === 3) {
$gTLD = array('aero', 'asia', 'biz', 'cat', 'com', 'coop', 'edu', 'gov', 'info', 'int', 'jobs', 'mil', 'mobi', 'museum', 'name', 'net', 'org', 'pro', 'tel', 'travel', 'xxx');
if (in_array($parts[1], $gTLD)) {
return '.' . $host;
}
}
array_shift($parts);
return '.' . implode('.', $parts);
break; break;
} }
return null; return null;

View file

@ -91,7 +91,13 @@ class BasicsTest extends CakeTestCase {
$__ENV = $_ENV; $__ENV = $_ENV;
$_SERVER['HTTP_HOST'] = 'localhost'; $_SERVER['HTTP_HOST'] = 'localhost';
$this->assertEqual(env('HTTP_BASE'), ''); $this->assertEqual(env('HTTP_BASE'), '.localhost');
$_SERVER['HTTP_HOST'] = 'com.ar';
$this->assertEqual(env('HTTP_BASE'), '.com.ar');
$_SERVER['HTTP_HOST'] = 'example.ar';
$this->assertEqual(env('HTTP_BASE'), '.example.ar');
$_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['HTTP_HOST'] = 'example.com';
$this->assertEqual(env('HTTP_BASE'), '.example.com'); $this->assertEqual(env('HTTP_BASE'), '.example.com');
@ -102,9 +108,21 @@ class BasicsTest extends CakeTestCase {
$_SERVER['HTTP_HOST'] = 'subdomain.example.com'; $_SERVER['HTTP_HOST'] = 'subdomain.example.com';
$this->assertEqual(env('HTTP_BASE'), '.example.com'); $this->assertEqual(env('HTTP_BASE'), '.example.com');
$_SERVER['HTTP_HOST'] = 'example.com.ar';
$this->assertEqual(env('HTTP_BASE'), '.example.com.ar');
$_SERVER['HTTP_HOST'] = 'www.example.com.ar';
$this->assertEqual(env('HTTP_BASE'), '.example.com.ar');
$_SERVER['HTTP_HOST'] = 'subdomain.example.com.ar';
$this->assertEqual(env('HTTP_BASE'), '.example.com.ar');
$_SERVER['HTTP_HOST'] = 'double.subdomain.example.com'; $_SERVER['HTTP_HOST'] = 'double.subdomain.example.com';
$this->assertEqual(env('HTTP_BASE'), '.subdomain.example.com'); $this->assertEqual(env('HTTP_BASE'), '.subdomain.example.com');
$_SERVER['HTTP_HOST'] = 'double.subdomain.example.com.ar';
$this->assertEqual(env('HTTP_BASE'), '.subdomain.example.com.ar');
$_SERVER = $_ENV = array(); $_SERVER = $_ENV = array();
$_SERVER['SCRIPT_NAME'] = '/a/test/test.php'; $_SERVER['SCRIPT_NAME'] = '/a/test/test.php';

View file

@ -63,7 +63,7 @@ class TaskCollectionTest extends CakeTestCase {
* @return void * @return void
*/ */
function testLoadWithEnableFalse() { function testLoadWithEnableFalse() {
$result = $this->Tasks->load('DbConfig', array(), false); $result = $this->Tasks->load('DbConfig', array('enabled' => false));
$this->assertInstanceOf('DbConfigTask', $result); $this->assertInstanceOf('DbConfigTask', $result);
$this->assertInstanceOf('DbConfigTask', $this->Tasks->DbConfig); $this->assertInstanceOf('DbConfigTask', $this->Tasks->DbConfig);

View file

@ -297,7 +297,6 @@ class FixtureTaskTest extends CakeTestCase {
$result = $this->Task->bake('Article', 'comments'); $result = $this->Task->bake('Article', 'comments');
$this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result); $this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result);
$this->assertPattern('/public \$name \= \'Article\';/', $result);
$this->assertPattern('/public \$table \= \'comments\';/', $result); $this->assertPattern('/public \$table \= \'comments\';/', $result);
$this->assertPattern('/public \$fields = array\(/', $result); $this->assertPattern('/public \$fields = array\(/', $result);

View file

@ -666,7 +666,6 @@ class ModelTaskTest extends CakeTestCase {
); );
$result = $this->Task->bake('BakeArticle', compact('validate')); $result = $this->Task->bake('BakeArticle', compact('validate'));
$this->assertPattern('/class BakeArticle extends AppModel \{/', $result); $this->assertPattern('/class BakeArticle extends AppModel \{/', $result);
$this->assertPattern('/\$name \= \'BakeArticle\'/', $result);
$this->assertPattern('/\$validate \= array\(/', $result); $this->assertPattern('/\$validate \= array\(/', $result);
$expected = <<< STRINGEND $expected = <<< STRINGEND
array( array(

View file

@ -31,6 +31,10 @@ class TestMemcacheEngine extends MemcacheEngine {
function parseServerString($server) { function parseServerString($server) {
return $this->_parseServerString($server); return $this->_parseServerString($server);
} }
function setMemcache($memcache) {
$this->_Memcache = $memcache;
}
} }
/** /**
@ -357,7 +361,25 @@ class MemcacheEngineTest extends CakeTestCase {
$this->assertTrue($result, 'Could not write with duration 0'); $this->assertTrue($result, 'Could not write with duration 0');
$result = Cache::read('test_key', 'memcache'); $result = Cache::read('test_key', 'memcache');
$this->assertEqual($result, 'written!'); $this->assertEqual($result, 'written!');
}
/**
* test that durations greater than 30 days never expire
*
* @return void
*/
function testLongDurationEqualToZero() {
$memcache =& new TestMemcacheEngine();
$memcache->settings['compress'] = false;
$mock = $this->getMock('Memcache');
$memcache->setMemcache($mock);
$mock->expects($this->once())
->method('set')
->with('key', 'value', false, 0);
$value = 'value';
$memcache->write('key', $value, 50 * DAY);
} }
} }

View file

@ -21,6 +21,12 @@ App::uses('CookieComponent', 'Controller/Component');
App::uses('SecurityComponent', 'Controller/Component'); App::uses('SecurityComponent', 'Controller/Component');
App::uses('ComponentCollection', 'Controller'); App::uses('ComponentCollection', 'Controller');
/**
* Extended CookieComponent
*/
class CookieAliasComponent extends CookieComponent {
}
class ComponentCollectionTest extends CakeTestCase { class ComponentCollectionTest extends CakeTestCase {
/** /**
* setup * setup
@ -59,6 +65,35 @@ class ComponentCollectionTest extends CakeTestCase {
$this->assertSame($result, $this->Components->Cookie); $this->assertSame($result, $this->Components->Cookie);
} }
/**
* Tests loading as an alias
*
* @return void
*/
function testLoadWithAlias() {
$result = $this->Components->load('Cookie', array('className' => 'CookieAlias', 'somesetting' => true));
$this->assertInstanceOf('CookieAliasComponent', $result);
$this->assertInstanceOf('CookieAliasComponent', $this->Components->Cookie);
$this->assertTrue($this->Components->Cookie->settings['somesetting']);
$result = $this->Components->attached();
$this->assertEquals(array('Cookie'), $result, 'attached() results are wrong.');
$this->assertTrue($this->Components->enabled('Cookie'));
$result = $this->Components->load('Cookie');
$this->assertInstanceOf('CookieAliasComponent', $result);
App::build(array('plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)));
$result = $this->Components->load('SomeOther', array('className' => 'TestPlugin.OtherComponent'));
$this->assertInstanceOf('OtherComponentComponent', $result);
$this->assertInstanceOf('OtherComponentComponent', $this->Components->SomeOther);
$result = $this->Components->attached();
$this->assertEquals(array('Cookie', 'SomeOther'), $result, 'attached() results are wrong.');
App::build();
}
/** /**
* test load and enable = false * test load and enable = false
* *

View file

@ -850,6 +850,23 @@ class ControllerTest extends CakeTestCase {
$Controller->redirect('http://cakephp.org', 301); $Controller->redirect('http://cakephp.org', 301);
} }
/**
* test that beforeRedirect callback returnning false in controller
*
* @return void
*/
function testRedirectBeforeRedirectInController() {
$Controller = $this->getMock('Controller', array('_stop', 'beforeRedirect'));
$Controller->response = $this->getMock('CakeResponse', array('header'));
$Controller->Components = $this->getMock('ComponentCollection');
$Controller->expects($this->once())->method('beforeRedirect')
->will($this->returnValue(false));
$Controller->response->expects($this->never())->method('header');
$Controller->expects($this->never())->method('_stop');
$Controller->redirect('http://cakephp.org');
}
/** /**
* testMergeVars method * testMergeVars method
* *

View file

@ -413,6 +413,12 @@ class Test7Behavior extends ModelBehavior{
} }
} }
/**
* Extended TestBehavior
*/
class TestAliasBehavior extends TestBehavior {
}
/** /**
* BehaviorCollection class * BehaviorCollection class
* *
@ -431,6 +437,31 @@ class BehaviorCollectionTest extends CakeTestCase {
'core.attachment', 'core.tag', 'core.articles_tag' 'core.attachment', 'core.tag', 'core.articles_tag'
); );
/**
* Tests loading aliased behaviors
*/
function testLoadAlias() {
$Apple = new Apple();
$this->assertIdentical($Apple->Behaviors->attached(), array());
$Apple->Behaviors->load('Test', array('className' => 'TestAlias', 'somesetting' => true));
$this->assertIdentical($Apple->Behaviors->attached(), array('Test'));
$this->assertInstanceOf('TestAliasBehavior', $Apple->Behaviors->Test);
$this->assertTrue($Apple->Behaviors->Test->settings['Apple']['somesetting']);
$this->assertEquals($Apple->Behaviors->Test->testMethod($Apple, true), 'working');
$this->assertEquals($Apple->testMethod(true), 'working');
$this->assertEquals($Apple->Behaviors->dispatchMethod($Apple, 'testMethod'), 'working');
App::build(array('plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)));
$this->assertTrue($Apple->Behaviors->load('SomeOther', array('className' => 'TestPlugin.TestPluginPersisterOne')));
$this->assertInstanceOf('TestPluginPersisterOneBehavior', $Apple->Behaviors->SomeOther);
$result = $Apple->Behaviors->attached();
$this->assertEquals(array('Test', 'SomeOther'), $result, 'attached() results are wrong.');
App::build();
}
/** /**
* testBehaviorBinding method * testBehaviorBinding method
* *

View file

@ -51,12 +51,16 @@ class ConnectionManagerTest extends CakeTestCase {
$source = ConnectionManager::getDataSource(key($connections)); $source = ConnectionManager::getDataSource(key($connections));
$this->assertTrue(is_object($source)); $this->assertTrue(is_object($source));
}
$this->expectError(); /**
* testGetDataSourceException() method
$source = ConnectionManager::getDataSource('non_existent_source'); *
$this->assertEqual($source, null); * @return void
* @expectedException MissingDatasourceConfigException
*/
public function testGetDataSourceException() {
ConnectionManager::getDataSource('non_existent_source');
} }
/** /**
@ -203,12 +207,17 @@ class ConnectionManagerTest extends CakeTestCase {
$loaded = ConnectionManager::loadDataSource($connection); $loaded = ConnectionManager::loadDataSource($connection);
$this->assertEqual($loaded, !$exists, "Failed loading the {$connection['classname']} datasource"); $this->assertEqual($loaded, !$exists, "Failed loading the {$connection['classname']} datasource");
} }
}
/**
* testLoadDataSourceException() method
*
* @return void
* @expectedException MissingDatasourceFileException
*/
public function testLoadDataSourceException() {
$connection = array('classname' => 'NonExistentDataSource', 'filename' => 'non_existent'); $connection = array('classname' => 'NonExistentDataSource', 'filename' => 'non_existent');
$this->expectError();
$loaded = ConnectionManager::loadDataSource($connection); $loaded = ConnectionManager::loadDataSource($connection);
$this->assertEqual($loaded, null);
} }
/** /**

View file

@ -1505,7 +1505,6 @@ class ModelWriteTest extends BaseModelTest {
); );
$TestModel->save($data); $TestModel->save($data);
$result = $TestModel->read(null, 1); $result = $TestModel->read(null, 1);
$time = date('Y-M-D H:i:s');
$expected = array(4, 5); $expected = array(4, 5);
$this->assertEqual(Set::extract('/JoinC/JoinAsJoinC/id', $result), $expected); $this->assertEqual(Set::extract('/JoinC/JoinAsJoinC/id', $result), $expected);
$expected = array('new record', 'new record'); $expected = array('new record', 'new record');

View file

@ -54,16 +54,16 @@ class GenericObjectCollection extends ObjectCollection {
* *
* @param string $object Object name * @param string $object Object name
* @param array $settings Settings array * @param array $settings Settings array
* @param boolean $enable Start object as enabled
* @return array List of loaded objects * @return array List of loaded objects
*/ */
public function load($object, $settings = array(), $enable = true) { public function load($object, $settings = array()) {
list($plugin, $name) = pluginSplit($object); list($plugin, $name) = pluginSplit($object);
if (isset($this->_loaded[$name])) { if (isset($this->_loaded[$name])) {
return $this->_loaded[$name]; return $this->_loaded[$name];
} }
$objectClass = $name . 'GenericObject'; $objectClass = $name . 'GenericObject';
$this->_loaded[$name] = new $objectClass($this, $settings); $this->_loaded[$name] = new $objectClass($this, $settings);
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) { if ($enable === true) {
$this->_enabled[] = $name; $this->_enabled[] = $name;
} }

View file

@ -2310,9 +2310,11 @@ class RouterTest extends CakeTestCase {
'action' => 'view', 'action' => 'view',
'pass' => array(1), 'pass' => array(1),
'named' => array(), 'named' => array(),
'url' => array('url' => 'eng/posts/view/1')
)); ));
$request->query = array('url' => 'eng/posts/view/1', 'test' => 'value');
$result = Router::reverse($request); $result = Router::reverse($request);
$expected = '/eng/posts/view/1?test=value';
$this->assertEquals($expected, $result);
} }
/** /**

View file

@ -127,6 +127,16 @@ class DatabaseSessionTest extends CakeTestCase {
$this->assertEquals($expected, $result); $this->assertEquals($expected, $result);
} }
/**
* testReadAndWriteWithDatabaseStorage method
*
* @access public
* @return void
*/
function testWriteEmptySessionId() {
$result = $this->storage->write('', 'This is a Test');
$this->assertFalse($result);
}
/** /**
* test read() * test read()
* *

View file

@ -101,8 +101,15 @@ class SetTest extends CakeTestCase {
$result = Set::filter(array(1, array('empty', false))); $result = Set::filter(array(1, array('empty', false)));
$expected = array(1, array('empty')); $expected = array(1, array('empty'));
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$result = Set::filter(array(1, array('2', false, array(3, null))));
$expected = array(1, array('2', 2 => array(3)));
$this->assertEqual($expected, $result);
$this->assertSame(array(), Set::filter(array()));
} }
/** /**
* testNumericArrayCheck method * testNumericArrayCheck method
* *

View file

@ -20,6 +20,13 @@
App::uses('HelperCollection', 'View/Helper'); App::uses('HelperCollection', 'View/Helper');
App::uses('View', 'View'); App::uses('View', 'View');
/**
* Extended HtmlHelper
*/
App::import('Helper', 'Html');
class HtmlAliasHelper extends HtmlHelper {
}
class HelperCollectionTest extends CakeTestCase { class HelperCollectionTest extends CakeTestCase {
/** /**
* setup * setup
@ -56,6 +63,34 @@ class HelperCollectionTest extends CakeTestCase {
$this->assertTrue($this->Helpers->enabled('Html')); $this->assertTrue($this->Helpers->enabled('Html'));
} }
/**
* Tests loading as an alias
*
* @return void
*/
function testLoadWithAlias() {
$result = $this->Helpers->load('Html', array('className' => 'HtmlAlias'));
$this->assertInstanceOf('HtmlAliasHelper', $result);
$this->assertInstanceOf('HtmlAliasHelper', $this->Helpers->Html);
$result = $this->Helpers->attached();
$this->assertEquals(array('Html'), $result, 'attached() results are wrong.');
$this->assertTrue($this->Helpers->enabled('Html'));
$result = $this->Helpers->load('Html');
$this->assertInstanceOf('HtmlAliasHelper', $result);
App::build(array('plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)));
$result = $this->Helpers->load('SomeOther', array('className' => 'TestPlugin.OtherHelper'));
$this->assertInstanceOf('OtherHelperHelper', $result);
$this->assertInstanceOf('OtherHelperHelper', $this->Helpers->SomeOther);
$result = $this->Helpers->attached();
$this->assertEquals(array('Html', 'SomeOther'), $result, 'attached() results are wrong.');
App::build();
}
/** /**
* test that the enabled setting disables the helper. * test that the enabled setting disables the helper.
* *

View file

@ -2174,6 +2174,35 @@ class FormHelperTest extends CakeTestCase {
'/div' '/div'
); );
$this->assertTags($result, $expected); $this->assertTags($result, $expected);
$this->Form->data = array();
$result = $this->Form->input('Publisher.id', array(
'label' => 'Publisher',
'type' => 'select',
'multiple' => 'checkbox',
'options' => array('Value 1' => 'Label 1', 'Value 2' => 'Label 2')
));
$expected = array(
array('div' => array('class' => 'input select')),
array('label' => array('for' => 'PublisherId')),
'Publisher',
'/label',
'input' => array('type' => 'hidden', 'name' => 'data[Publisher][id]', 'value' => '', 'id' => 'PublisherId'),
array('div' => array('class' => 'checkbox')),
array('input' => array('type' => 'checkbox', 'name' => 'data[Publisher][id][]', 'value' => 'Value 1', 'id' => 'PublisherIdValue1')),
array('label' => array('for' => 'PublisherIdValue1')),
'Label 1',
'/label',
'/div',
array('div' => array('class' => 'checkbox')),
array('input' => array('type' => 'checkbox', 'name' => 'data[Publisher][id][]', 'value' => 'Value 2', 'id' => 'PublisherIdValue2')),
array('label' => array('for' => 'PublisherIdValue2')),
'Label 2',
'/label',
'/div',
'/div'
);
$this->assertTags($result, $expected);
} }
/** /**
@ -3768,27 +3797,6 @@ class FormHelperTest extends CakeTestCase {
); );
$this->assertTags($result, $expected); $this->assertTags($result, $expected);
$result = $this->Form->checkbox('Model.field', array('checked' => 'checked'));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField_'),
array('input' => array('type' => 'checkbox', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField', 'checked' => 'checked'))
);
$this->assertTags($result, $expected);
$result = $this->Form->checkbox('Model.field', array('checked' => 1));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField_'),
array('input' => array('type' => 'checkbox', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField', 'checked' => 'checked'))
);
$this->assertTags($result, $expected);
$result = $this->Form->checkbox('Model.field', array('checked' => true));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField_'),
array('input' => array('type' => 'checkbox', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField', 'checked' => 'checked'))
);
$this->assertTags($result, $expected);
$this->Form->validationErrors['Model']['field'] = 1; $this->Form->validationErrors['Model']['field'] = 1;
$this->Form->request->data['Contact']['published'] = 1; $this->Form->request->data['Contact']['published'] = 1;
$result = $this->Form->checkbox('Contact.published', array('id' => 'theID')); $result = $this->Form->checkbox('Contact.published', array('id' => 'theID'));
@ -3829,6 +3837,49 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected); $this->assertTags($result, $expected);
} }
/**
* test the checked option for checkboxes.
*
* @return void
*/
function testCheckboxCheckedOption() {
$result = $this->Form->checkbox('Model.field', array('checked' => 'checked'));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField_'),
array('input' => array('type' => 'checkbox', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField', 'checked' => 'checked'))
);
$this->assertTags($result, $expected);
$result = $this->Form->checkbox('Model.field', array('checked' => 1));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField_'),
array('input' => array('type' => 'checkbox', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField', 'checked' => 'checked'))
);
$this->assertTags($result, $expected);
$result = $this->Form->checkbox('Model.field', array('checked' => true));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField_'),
array('input' => array('type' => 'checkbox', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField', 'checked' => 'checked'))
);
$this->assertTags($result, $expected);
$result = $this->Form->checkbox('Model.field', array('checked' => false));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField_'),
array('input' => array('type' => 'checkbox', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField'))
);
$this->assertTags($result, $expected);
$this->Form->request->data['Model']['field'] = 1;
$result = $this->Form->checkbox('Model.field', array('checked' => false));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'ModelField_'),
array('input' => array('type' => 'checkbox', 'name' => 'data[Model][field]', 'value' => '1', 'id' => 'ModelField'))
);
$this->assertTags($result, $expected);
}
/** /**
* Test that disabling a checkbox also disables the hidden input so no value is submitted * Test that disabling a checkbox also disables the hidden input so no value is submitted
* *
@ -5757,6 +5808,28 @@ class FormHelperTest extends CakeTestCase {
))); )));
} }
/**
* test get form, and inputs when the model param is false
*
* @return void
*/
function testGetFormWithFalseModel() {
$encoding = strtolower(Configure::read('App.encoding'));
$result = $this->Form->create(false, array('type' => 'get'));
$expected = array('form' => array(
'id' => 'addForm', 'method' => 'get', 'action' => '/contact_test/add',
'accept-charset' => $encoding
));
$this->assertTags($result, $expected);
$result = $this->Form->text('reason');
$expected = array(
'input' => array('type' => 'text', 'name' => 'reason', 'id' => 'reason')
);
$this->assertTags($result, $expected);
}
/** /**
* test that datetime() works with GET style forms. * test that datetime() works with GET style forms.
* *

View file

@ -274,6 +274,16 @@ class TextHelperTest extends CakeTestCase {
$expected = 'Text with a url <a href="http://www.cot.ag/cuIb2Q">www.cot.ag/cuIb2Q</a> and more'; $expected = 'Text with a url <a href="http://www.cot.ag/cuIb2Q">www.cot.ag/cuIb2Q</a> and more';
$result = $this->Text->autoLinkUrls($text); $result = $this->Text->autoLinkUrls($text);
$this->assertEqual($expected, $result); $this->assertEqual($expected, $result);
$text = 'Text with a url http://www.does--not--work.com and more';
$expected = 'Text with a url <a href="http://www.does--not--work.com">http://www.does--not--work.com</a> and more';
$result = $this->Text->autoLinkUrls($text);
$this->assertEqual($expected, $result);
$text = 'Text with a url http://www.not--work.com and more';
$expected = 'Text with a url <a href="http://www.not--work.com">http://www.not--work.com</a> and more';
$result = $this->Text->autoLinkUrls($text);
$this->assertEqual($expected, $result);
} }
/** /**
@ -293,6 +303,11 @@ class TextHelperTest extends CakeTestCase {
$result = $this->Text->autoLinkEmails($text); $result = $this->Text->autoLinkEmails($text);
$this->assertPattern('#^' . $expected . '$#', $result); $this->assertPattern('#^' . $expected . '$#', $result);
$text = "Text with o'hare._-bob@example.com address";
$expected = 'Text with <a href="mailto:o&#039;hare._-bob@example.com">o&#039;hare._-bob@example.com</a> address';
$result = $this->Text->autoLinkEmails($text);
$this->assertEqual($expected, $result);
$text = 'Text with email@example.com address'; $text = 'Text with email@example.com address';
$expected = 'Text with <a href="mailto:email@example.com" \s*class="link">email@example.com</a> address'; $expected = 'Text with <a href="mailto:email@example.com" \s*class="link">email@example.com</a> address';
$result = $this->Text->autoLinkEmails($text, array('class' => 'link')); $result = $this->Text->autoLinkEmails($text, array('class' => 'link'));

View file

@ -547,6 +547,21 @@ class ViewTest extends CakeTestCase {
$this->assertInstanceOf('HtmlHelper', $View->Html); $this->assertInstanceOf('HtmlHelper', $View->Html);
} }
/**
* test that ctp is used as a fallback file extension for elements
*
* @return void
*/
function testElementCtpFallback() {
$View = new TestView($this->PostsController);
$View->ext = '.missing';
$element = 'test_element';
$expected = 'this is the test element';
$result = $View->element($element);
$this->assertEqual($expected, $result);
}
/** /**
* testLoadHelpers method * testLoadHelpers method
* *

View file

@ -32,7 +32,7 @@ $this->loadHelper('Html');
<body> <body>
<div id="container"> <div id="container">
<div id="header"> <div id="header">
<h1><?php echo $this->Html->link(__('CakePHP: the rapid development php framework', true), 'http://cakephp.org');?></h1> <h1><?php echo $this->Html->link(__('CakePHP: the rapid development php framework'), 'http://cakephp.org');?></h1>
</div> </div>
<div id="content"> <div id="content">
@ -41,7 +41,7 @@ $this->loadHelper('Html');
</div> </div>
<div id="footer"> <div id="footer">
<?php echo $this->Html->link( <?php echo $this->Html->link(
$this->Html->image('cake.power.gif', array('alt'=> __("CakePHP: the rapid development php framework", true), 'border'=>"0")), $this->Html->image('cake.power.gif', array('alt'=> __("CakePHP: the rapid development php framework"), 'border'=>"0")),
'http://www.cakephp.org/', 'http://www.cakephp.org/',
array('target'=>'_blank'), null, false array('target'=>'_blank'), null, false
); );