Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Harold Putman 2012-11-13 17:18:00 -05:00
commit 77886a9c5b
106 changed files with 1284 additions and 594 deletions

View file

@ -10,6 +10,16 @@ env:
- DB=pgsql
- DB=sqlite
matrix:
allow_failures:
- php: 5.4
env:
- PHPCS=1
include:
- php: 5.4
env:
- PHPCS=1
before_script:
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'CREATE DATABASE cakephp_test;'; fi"
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'CREATE DATABASE cakephp_test2;'; fi"
@ -23,6 +33,9 @@ before_script:
server.listen(80, 'localhost');
console.log('TCP server listening on port 80 at localhost.');" > app/tmp/socket.js
- sudo node ./app/tmp/socket.js &
- pear channel-discover pear.cakephp.org
- pear install --alldeps cakephp/CakePHP_CodeSniffer
- phpenv rehash
- set +H
- echo "<?php
class DATABASE_CONFIG {
@ -105,7 +118,7 @@ before_script:
}" > app/Config/database.php
script:
- ./lib/Cake/Console/cake test core AllTests --stderr
- sh -c "if [ '$PHPCS' != '1' ]; then ./lib/Cake/Console/cake test core AllTests --stderr; else phpcs --extensions=php --standard=CakePHP ./lib/Cake; fi"
notifications:
email: false

View file

@ -19,14 +19,17 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
// @codingStandardsIgnoreStart
/*
*
* Using the Schema command line utility
* cake schema run create i18n
*
*/
class i18nSchema extends CakeSchema {
// @codingStandardsIgnoreEnd
public $name = 'i18n';
public function before($event = array()) {

View file

@ -114,7 +114,7 @@ class TestShell extends Shell {
))->addOption('stop-on-failure', array(
'help' => __d('cake_console', 'Stop execution upon first failure.'),
'boolean' => true
))->addOption('stop-on-skipped ', array(
))->addOption('stop-on-skipped', array(
'help' => __d('cake_console', 'Stop execution upon first skipped test.'),
'boolean' => true
))->addOption('stop-on-incomplete', array(
@ -132,7 +132,7 @@ class TestShell extends Shell {
))->addOption('no-globals-backup', array(
'help' => __d('cake_console', 'Do not backup and restore $GLOBALS for each test.'),
'boolean' => true
))->addOption('static-backup ', array(
))->addOption('static-backup', array(
'help' => __d('cake_console', 'Backup and restore static attributes for each test.'),
'boolean' => true
))->addOption('syntax-check', array(

View file

@ -21,14 +21,17 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
// @codingStandardsIgnoreStart
/*
*
* Using the Schema command line utility
* cake schema run create i18n
*
*/
class i18nSchema extends CakeSchema {
// @codingStandardsIgnoreEnd
public $name = 'i18n';
public function before($event = array()) {

View file

@ -98,11 +98,11 @@ Configure::write('Dispatcher.filters', array(
App::uses('CakeLog', 'Log');
CakeLog::config('debug', array(
'engine' => 'FileLog',
'scopes' => array('notice', 'info', 'debug'),
'types' => array('notice', 'info', 'debug'),
'file' => 'debug',
));
CakeLog::config('error', array(
'engine' => 'FileLog',
'scopes' => array('warning', 'error', 'critical', 'alert', 'emergency'),
'types' => array('warning', 'error', 'critical', 'alert', 'emergency'),
'file' => 'error',
));

View file

@ -19,6 +19,8 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('AppController', 'Controller');
/**
* Error Handling Controller
*
@ -50,7 +52,11 @@ class CakeErrorController extends AppController {
*/
public function __construct($request = null, $response = null) {
parent::__construct($request, $response);
if (count(Router::extensions())) {
if (
count(Router::extensions()) &&
!array_key_exists('RequestHandler', $this->components) &&
!in_array('RequestHandler', $this->components, true)
) {
$this->components[] = 'RequestHandler';
}
$this->constructClasses();

View file

@ -84,7 +84,7 @@ abstract class BaseAuthenticate {
}
$result = ClassRegistry::init($userModel)->find('first', array(
'conditions' => $conditions,
'recursive' => (int)$this->settings['recursive'],
'recursive' => $this->settings['recursive'],
'contain' => $this->settings['contain'],
));
if (empty($result) || empty($result[$model])) {

View file

@ -170,7 +170,7 @@ class DigestAuthenticate extends BaseAuthenticate {
}
$result = ClassRegistry::init($userModel)->find('first', array(
'conditions' => $conditions,
'recursive' => (int)$this->settings['recursive']
'recursive' => $this->settings['recursive']
));
if (empty($result) || empty($result[$model])) {
return false;

View file

@ -796,7 +796,7 @@ class Controller extends Object implements CakeEventListener {
* @return array Array with keys url, status and exit
*/
protected function _parseBeforeRedirect($response, $url, $status, $exit) {
if (is_array($response) && isset($response[0])) {
if (is_array($response) && array_key_exists(0, $response)) {
foreach ($response as $resp) {
if (is_array($resp) && isset($resp['url'])) {
extract($resp, EXTR_OVERWRITE);

View file

@ -73,9 +73,13 @@ class Object {
$extra['autoRender'] = 1;
unset($extra[$index]);
}
if (is_array($url) && !isset($extra['url'])) {
$arrayUrl = is_array($url);
if ($arrayUrl && !isset($extra['url'])) {
$extra['url'] = array();
}
if ($arrayUrl && !isset($extra['data'])) {
$extra['data'] = array();
}
$extra = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
$data = isset($extra['data']) ? $extra['data'] : null;
unset($extra['data']);
@ -88,11 +92,12 @@ class Object {
} 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);
$request = new CakeRequest(Router::reverse($params));
}
if (isset($data)) {
$request->data = $data;
}
$dispatcher = new Dispatcher();
$result = $dispatcher->dispatch($request, new CakeResponse(), $extra);
Router::popRequest();

View file

@ -22,7 +22,6 @@
App::uses('Debugger', 'Utility');
App::uses('CakeLog', 'Log');
App::uses('ExceptionRenderer', 'Error');
App::uses('AppController', 'Controller');
/**
*

View file

@ -142,15 +142,14 @@ class ExceptionRenderer {
* @return Controller
*/
protected function _getController($exception) {
App::uses('AppController', 'Controller');
App::uses('CakeErrorController', 'Controller');
if (!$request = Router::getRequest(true)) {
$request = new CakeRequest();
}
$response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
try {
if (class_exists('AppController')) {
$controller = new CakeErrorController($request, $response);
}
$controller = new CakeErrorController($request, $response);
} catch (Exception $e) {
}
if (empty($controller)) {

View file

@ -24,13 +24,6 @@ App::uses('CakePlugin', 'Core');
App::uses('L10n', 'I18n');
App::uses('Multibyte', 'I18n');
if (function_exists('mb_internal_encoding')) {
$encoding = Configure::read('App.encoding');
if (!empty($encoding)) {
mb_internal_encoding($encoding);
}
}
/**
* I18n handles translation of Text and time format strings.
*

View file

@ -1008,7 +1008,8 @@ class Multibyte {
if ($charset == 'UTF-8') {
$parts = array();
$maxchars = floor(($length * 3) / 4);
while (strlen($string) > $maxchars) {
$stringLength = strlen($string);
while ($stringLength > $maxchars) {
$i = (int)$maxchars;
$test = ord($string[$i]);
while ($test >= 128 && $test <= 191) {
@ -1017,6 +1018,7 @@ class Multibyte {
}
$parts[] = base64_encode(substr($string, 0, $i));
$string = substr($string, $i);
$stringLength = strlen($string);
}
$parts[] = base64_encode($string);
$string = implode($spacer, $parts);

View file

@ -67,6 +67,7 @@ App::uses('LogEngineCollection', 'Log');
* application. By using scopes you can control logging for each part
* of your application and still keep standard log levels.
*
*
* See CakeLog::config() and CakeLog::write() for more information
* on scopes
*
@ -173,7 +174,10 @@ class CakeLog {
*
* The above logger will only capture log entries made in the
* `payment` and `order` scopes. All other scopes including the
* undefined scope will be ignored.
* undefined scope will be ignored. Its important to remember that
* when using scopes you must also define the `types` of log messages
* that a logger will handle. Failing to do so will result in the logger
* catching all log messages even if the scope is incorrect.
*
* @param string $key The keyname for this logger, used to remove the
* logger later.
@ -422,24 +426,29 @@ class CakeLog {
$logged = false;
foreach (self::$_Collection->enabled() as $streamName) {
$logger = self::$_Collection->{$streamName};
$types = null;
$scopes = array();
$types = $scopes = $config = array();
if ($logger instanceof BaseLog) {
$config = $logger->config();
if (isset($config['types'])) {
$types = $config['types'];
}
if (isset($config['scopes'])) {
$scopes = $config['scopes'];
}
}
if (is_string($scope)) {
$inScope = in_array($scope, $scopes);
} else {
$intersect = array_intersect($scope, $scopes);
$inScope = !empty($intersect);
if (isset($config['types'])) {
$types = $config['types'];
}
if (empty($types) || in_array($type, $types) || in_array($type, $scopes) && $inScope) {
if (isset($config['scopes'])) {
$scopes = $config['scopes'];
}
$inScope = (count(array_intersect((array)$scope, $scopes)) > 0);
$correctLevel = in_array($type, $types);
if (
// No config is a catch all (bc mode)
(empty($types) && empty($scopes)) ||
// BC layer for mixing scope & level
(in_array($type, $scopes)) ||
// no scopes, but has level
(empty($scopes) && $correctLevel) ||
// exact scope + level
($correctLevel && $inScope)
) {
$logger->write($type, $message);
$logged = true;
}

View file

@ -91,21 +91,25 @@ class ContainableBehavior extends ModelBehavior {
*/
public function beforeFind(Model $Model, $query) {
$reset = (isset($query['reset']) ? $query['reset'] : true);
$noContain = (
(isset($this->runtime[$Model->alias]['contain']) && empty($this->runtime[$Model->alias]['contain'])) ||
(isset($query['contain']) && empty($query['contain']))
);
$noContain = false;
$contain = array();
if (isset($this->runtime[$Model->alias]['contain'])) {
$noContain = empty($this->runtime[$Model->alias]['contain']);
$contain = $this->runtime[$Model->alias]['contain'];
unset($this->runtime[$Model->alias]['contain']);
}
if (isset($query['contain'])) {
$contain = array_merge($contain, (array)$query['contain']);
$noContain = $noContain || empty($query['contain']);
if ($query['contain'] !== false) {
$contain = array_merge($contain, (array)$query['contain']);
}
}
$noContain = $noContain && empty($contain);
if (
$noContain || !$contain || in_array($contain, array(null, false), true) ||
(isset($contain[0]) && $contain[0] === null)
$noContain || empty($contain) || (isset($contain[0]) && $contain[0] === null)
) {
if ($noContain) {
$query['recursive'] = -1;

View file

@ -383,6 +383,21 @@ class TranslateBehavior extends ModelBehavior {
$this->runtime[$Model->alias]['beforeSave'] = $tempData;
}
/**
* Restores model data to the original data.
* This solves issues with saveAssociated and validate = first.
*
* @param Model $model
* @return void
*/
public function afterValidate(Model $Model) {
$Model->data[$Model->alias] = array_merge(
$Model->data[$Model->alias],
$this->runtime[$Model->alias]['beforeSave']
);
return true;
}
/**
* afterSave Callback
*

View file

@ -178,7 +178,7 @@ class TreeBehavior extends ModelBehavior {
extract($this->settings[$Model->alias]);
$this->_addToWhitelist($Model, array($left, $right));
if (!$Model->id) {
if (!$Model->id || !$Model->exists()) {
if (array_key_exists($parent, $Model->data[$Model->alias]) && $Model->data[$Model->alias][$parent]) {
$parentNode = $Model->find('first', array(
'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]),

View file

@ -921,14 +921,14 @@ class DboSource extends DataSource {
$this->_queriesCnt++;
$this->_queriesTime += $this->took;
$this->_queriesLog[] = array(
'query' => $sql,
'params' => $params,
'affected' => $this->affected,
'numRows' => $this->numRows,
'took' => $this->took
'query' => $sql,
'params' => $params,
'affected' => $this->affected,
'numRows' => $this->numRows,
'took' => $this->took
);
if (count($this->_queriesLog) > $this->_queriesLogMax) {
array_pop($this->_queriesLog);
array_shift($this->_queriesLog);
}
}
@ -2490,16 +2490,16 @@ class DboSource extends DataSource {
$count = count($value);
if ($count === 1 && !preg_match("/\s+NOT$/", $key)) {
$data = $this->_quoteFields($key) . ' = (';
} else {
$data = $this->_quoteFields($key) . ' IN (';
}
if ($quoteValues) {
if (is_object($model)) {
$columnType = $model->getColumnType($key);
if ($quoteValues) {
if (is_object($model)) {
$columnType = $model->getColumnType($key);
}
$data .= implode(', ', $this->value($value, $columnType));
}
$data .= implode(', ', $this->value($value, $columnType));
$data .= ')';
} else {
$data = $this->_parseKey($model, $key, $value);
}
$data .= ')';
} else {
$ret = $this->conditionKeysToString($value, $quoteValues, $model);
if (count($ret) > 1) {
@ -2917,6 +2917,10 @@ class DboSource extends DataSource {
}
$statement->execute();
$statement->closeCursor();
if ($this->fullDebug) {
$this->logQuery($sql, $value);
}
}
return $this->commit();
}
@ -2984,7 +2988,7 @@ class DboSource extends DataSource {
$tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
}
}
if (empty($indexes) && !empty($primary)) {
if (!isset($columns['indexes']['PRIMARY']) && !empty($primary)) {
$col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
$indexes = array_merge($indexes, $this->buildIndex($col, $table));
}

View file

@ -558,6 +558,8 @@ class Model extends Object implements CakeEventListener {
*/
protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
// @codingStandardsIgnoreStart
/**
* Holds model associations temporarily to allow for dynamic (un)binding.
*
@ -586,6 +588,8 @@ class Model extends Object implements CakeEventListener {
*/
public $__backContainableAssociation = array();
// @codingStandardsIgnoreEnd
/**
* The ID of the model record that was last inserted.
*
@ -1082,7 +1086,7 @@ class Model extends Object implements CakeEventListener {
}
/**
* Sets a custom table for your controller class. Used by your controller to select a database table.
* Sets a custom table for your model class. Used by your controller to select a database table.
*
* @param string $tableName Name of the custom table
* @throws MissingTableException when database table $tableName is not found on data source
@ -2017,7 +2021,7 @@ class Model extends Object implements CakeEventListener {
* @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
* @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
*/
public function saveAll($data, $options = array()) {
public function saveAll($data = array(), $options = array()) {
$options = array_merge(array('validate' => 'first'), $options);
if (Hash::numeric(array_keys($data))) {
if ($options['validate'] === 'only') {
@ -2183,7 +2187,7 @@ class Model extends Object implements CakeEventListener {
if ($options['validate'] === 'first') {
$validates = $this->validateAssociated($data, $options);
if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, Hash::flatten($validates), true))) {
return $validates;
}
$options['validate'] = false;
@ -2613,9 +2617,12 @@ class Model extends Object implements CakeEventListener {
*
* Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you
* have issues with database views.
*
* Note: find(count) has its own return values.
*
* @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
* @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
* @return array Array of records
* @return array Array of records, or Null on failure.
* @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
*/
public function find($type = 'first', $query = array()) {
@ -2638,10 +2645,10 @@ class Model extends Object implements CakeEventListener {
if ($type === 'all') {
return $results;
} else {
if ($this->findMethods[$type] === true) {
return $this->{'_find' . ucfirst($type)}('after', $query, $results);
}
}
if ($this->findMethods[$type] === true) {
return $this->{'_find' . ucfirst($type)}('after', $query, $results);
}
}
@ -2707,7 +2714,7 @@ class Model extends Object implements CakeEventListener {
return $query;
} elseif ($state === 'after') {
if (empty($results[0])) {
return false;
return array();
}
return $results[0];
}
@ -2749,8 +2756,8 @@ class Model extends Object implements CakeEventListener {
} elseif ($state === 'after') {
foreach (array(0, $this->alias) as $key) {
if (isset($results[0][$key]['count'])) {
if (($count = count($results)) > 1) {
return $count;
if ($query['group']) {
return count($results);
} else {
return intval($results[0][$key]['count']);
}

View file

@ -163,9 +163,9 @@ class CakeValidationRule {
*/
public function checkRequired($field, &$data) {
return (
(!isset($data[$field]) && $this->isRequired() === true) ||
(!array_key_exists($field, $data) && $this->isRequired() === true) ||
(
isset($data[$field]) && (empty($data[$field]) &&
array_key_exists($field, $data) && (empty($data[$field]) &&
!is_numeric($data[$field])) && $this->allowEmpty === false
)
);

View file

@ -192,7 +192,7 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
* @return CakeValidationSet this instance
*/
public function setRule($name, $rule) {
if (!$rule instanceof CakeValidationRule) {
if (!($rule instanceof CakeValidationRule)) {
$rule = new CakeValidationRule($rule);
}
$this->_rules[$name] = $rule;
@ -236,9 +236,10 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
*/
public function setRules($rules = array(), $mergeVars = true) {
if ($mergeVars === false) {
$this->_rules = $rules;
} else {
$this->_rules = array_merge($this->_rules, $rules);
$this->_rules = array();
}
foreach ($rules as $name => $rule) {
$this->setRule($name, $rule);
}
return $this;
}
@ -280,7 +281,7 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
$message = __d($this->_validationDomain, $name);
}
} else {
$message = __d('cake_dev', 'This field cannot be left blank');
$message = __d('cake', 'This field cannot be left blank');
}
return $message;

View file

@ -15,8 +15,7 @@
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Set', 'Utility');
App::uses('Hash', 'Utility');
/**
* A class that helps wrap Request information and particulars about a single request.
@ -163,11 +162,12 @@ class CakeRequest implements ArrayAccess {
protected function _processPost() {
if ($_POST) {
$this->data = $_POST;
} elseif ($this->is('put') || $this->is('delete')) {
$this->data = $this->_readInput();
if (strpos(env('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0) {
parse_str($this->data, $this->data);
}
} elseif (
($this->is('put') || $this->is('delete')) &&
strpos(env('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0
) {
$data = $this->_readInput();
parse_str($data, $this->data);
}
if (ini_get('magic_quotes_gpc') === '1') {
$this->data = stripslashes_deep($this->data);
@ -229,8 +229,10 @@ class CakeRequest implements ArrayAccess {
protected function _url() {
if (!empty($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} elseif (isset($_SERVER['REQUEST_URI'])) {
} elseif (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '://') === false) {
$uri = $_SERVER['REQUEST_URI'];
} elseif (isset($_SERVER['REQUEST_URI'])) {
$uri = substr($_SERVER['REQUEST_URI'], strlen(FULL_BASE_URL));
} elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
$uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
} elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
@ -319,7 +321,7 @@ class CakeRequest implements ArrayAccess {
protected function _processFiles() {
if (isset($_FILES) && is_array($_FILES)) {
foreach ($_FILES as $name => $data) {
if ($name != 'data') {
if ($name !== 'data') {
$this->params['form'][$name] = $data;
}
}
@ -351,7 +353,7 @@ class CakeRequest implements ArrayAccess {
$this->_processFileData($newPath, $fields, $field);
} else {
$newPath .= '.' . $field;
$this->data = Set::insert($this->data, $newPath, $fields);
$this->data = Hash::insert($this->data, $newPath, $fields);
}
}
}

View file

@ -403,7 +403,7 @@ class HttpSocket extends CakeSocket {
}
if ($this->request['redirect'] && $this->response->isRedirect()) {
$request['uri'] = $this->response->getHeader('Location');
$request['uri'] = trim(urldecode($this->response->getHeader('Location')), '=');
$request['redirect'] = is_int($this->request['redirect']) ? $this->request['redirect'] - 1 : $this->request['redirect'];
$this->response = $this->request($request);
}

View file

@ -633,7 +633,7 @@ class Router {
* @return array Parameter information
*/
public static function getParams($current = false) {
if ($current) {
if ($current && self::$_requests) {
return self::$_requests[count(self::$_requests) - 1]->params;
}
if (isset(self::$_requests[0])) {

View file

@ -67,7 +67,7 @@ class BasicsTest extends CakeTestCase {
$one = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true);
$two = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true);
$result = array_diff_key($one, $two);
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
}
/**

View file

@ -121,7 +121,6 @@ class MemcacheEngineTest extends CakeTestCase {
$Memcache = new MemcacheEngine();
$Memcache->init(array('engine' => 'Memcache', 'servers' => $servers));
$servers = array_keys($Memcache->__Memcache->getExtendedStats());
$settings = $Memcache->settings();
$this->assertEquals($settings['servers'], $servers);
Cache::drop('dual_server');
@ -230,12 +229,11 @@ class MemcacheEngineTest extends CakeTestCase {
$result = Cache::write('other_test', $data, 'memcache');
$this->assertTrue($result);
sleep(2);
sleep(3);
$result = Cache::read('other_test', 'memcache');
$this->assertFalse($result);
Cache::config('memcache', array('duration' => '+1 second'));
sleep(2);
$result = Cache::read('other_test', 'memcache');
$this->assertFalse($result);

View file

@ -177,7 +177,7 @@ class AclShellTest extends CakeTestCase {
$Aro = ClassRegistry::init('Aro');
$result = $Aro->findById(3);
$this->assertFalse($result);
$this->assertSame(array(), $result);
}
/**

View file

@ -181,7 +181,7 @@ class ControllerTaskTest extends CakeTestCase {
public function testDoHelpersNo() {
$this->Task->expects($this->any())->method('in')->will($this->returnValue('n'));
$result = $this->Task->doHelpers();
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
}
/**
@ -218,7 +218,7 @@ class ControllerTaskTest extends CakeTestCase {
public function testDoComponentsNo() {
$this->Task->expects($this->any())->method('in')->will($this->returnValue('n'));
$result = $this->Task->doComponents();
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
}
/**

View file

@ -483,14 +483,14 @@ class DbAclTest extends CakeTestCase {
/**
* debug function - to help editing/creating test cases for the ACL component
*
* To check the overall ACL status at any time call $this->__debug();
* To check the overall ACL status at any time call $this->_debug();
* Generates a list of the current aro and aco structures and a grid dump of the permissions that are defined
* Only designed to work with the db based ACL
*
* @param bool $treesToo
* @return void
*/
protected function __debug($printTreesToo = false) {
protected function _debug($printTreesToo = false) {
$this->Acl->Aro->displayField = 'alias';
$this->Acl->Aco->displayField = 'alias';
$aros = $this->Acl->Aro->find('list', array('order' => 'lft'));
@ -518,10 +518,10 @@ class DbAclTest extends CakeTestCase {
}
foreach ($permissions as $key => $values) {
array_unshift($values, $key);
$values = array_map(array(&$this, '__pad'), $values);
$values = array_map(array(&$this, '_pad'), $values);
$permissions[$key] = implode (' ', $values);
}
$permisssions = array_map(array(&$this, '__pad'), $permissions);
$permisssions = array_map(array(&$this, '_pad'), $permissions);
array_unshift($permissions, 'Current Permissions :');
if ($printTreesToo) {
debug(array('aros' => $this->Acl->Aro->generateTreeList(), 'acos' => $this->Acl->Aco->generateTreeList()));
@ -537,7 +537,7 @@ class DbAclTest extends CakeTestCase {
* @param integer $len
* @return void
*/
protected function __pad($string = '', $len = 14) {
protected function _pad($string = '', $len = 14) {
return str_pad($string, $len);
}
}

View file

@ -412,11 +412,11 @@ class CookieComponentTest extends CakeTestCase {
$this->assertNull($data);
$_COOKIE['CakeTestCookie'] = array(
'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')),
'Encrytped_array' => $this->_encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')),
'Encrytped_multi_cookies' => array(
'name' => $this->__encrypt('CakePHP'),
'version' => $this->__encrypt('1.2.0.x'),
'tag' => $this->__encrypt('CakePHP Rocks!')),
'name' => $this->_encrypt('CakePHP'),
'version' => $this->_encrypt('1.2.0.x'),
'tag' => $this->_encrypt('CakePHP Rocks!')),
'Plain_array' => '{"name":"CakePHP","version":"1.2.0.x","tag":"CakePHP Rocks!"}',
'Plain_multi_cookies' => array(
'name' => 'CakePHP',
@ -467,11 +467,11 @@ class CookieComponentTest extends CakeTestCase {
$this->assertEquals($expected, $data);
$_COOKIE['CakeTestCookie'] = array(
'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')),
'Encrytped_array' => $this->_encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')),
'Encrytped_multi_cookies' => array(
'name' => $this->__encrypt('CakePHP'),
'version' => $this->__encrypt('1.2.0.x'),
'tag' => $this->__encrypt('CakePHP Rocks!')),
'name' => $this->_encrypt('CakePHP'),
'version' => $this->_encrypt('1.2.0.x'),
'tag' => $this->_encrypt('CakePHP Rocks!')),
'Plain_array' => '{"name":"CakePHP","version":"1.2.0.x","tag":"CakePHP Rocks!"}',
'Plain_multi_cookies' => array(
'name' => 'CakePHP',
@ -594,7 +594,7 @@ class CookieComponentTest extends CakeTestCase {
* @param array|string $value
* @return string
*/
protected function __encrypt($value) {
protected function _encrypt($value) {
if (is_array($value)) {
$value = $this->_implode($value);
}

View file

@ -347,7 +347,7 @@ class AppTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = App::objects('NonExistingType');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
App::build(array(
'plugins' => array(
@ -414,9 +414,9 @@ class AppTest extends CakeTestCase {
$this->assertTrue(in_array('OtherComponent', $result));
$result = App::objects('TestPluginTwo.behavior');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$result = App::objects('TestPluginTwo.Model/Behavior');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$result = App::objects('model', null, false);
$this->assertTrue(in_array('Comment', $result));

View file

@ -619,6 +619,24 @@ class ObjectTest extends CakeTestCase {
$this->assertEquals($expected, $result['named']);
}
/**
* Test that requestAction handles get parameters correctly.
*
* @return void
*/
public function testRequestActionGetParameters() {
$result = $this->object->requestAction(
'/request_action/params_pass?get=value&limit=5'
);
$this->assertEquals('value', $result->query['get']);
$result = $this->object->requestAction(
array('controller' => 'request_action', 'action' => 'params_pass'),
array('url' => array('get' => 'value', 'limit' => 5))
);
$this->assertEquals('value', $result->query['get']);
}
/**
* test that requestAction does not fish data out of the POST
* superglobal.
@ -632,7 +650,6 @@ class ObjectTest extends CakeTestCase {
'item' => 'value'
));
$result = $this->object->requestAction(array('controller' => 'request_action', 'action' => 'post_pass'));
$expected = null;
$this->assertEmpty($result);
$result = $this->object->requestAction(

View file

@ -19,7 +19,6 @@
App::uses('ExceptionRenderer', 'Error');
App::uses('Controller', 'Controller');
App::uses('AppController', 'Controller');
App::uses('Component', 'Controller');
App::uses('Router', 'Routing');

View file

@ -234,6 +234,10 @@ class CakeEventManagerTest extends CakeTestCase {
* @return void
*/
public function testDispatchReturnValue() {
$this->skipIf(
version_compare(PHPUnit_Runner_Version::id(), '3.7', '<'),
'These tests fail in PHPUnit 3.6'
);
$manager = new CakeEventManager;
$listener = $this->getMock('CakeEventTestListener');
$anotherListener = $this->getMock('CakeEventTestListener');
@ -241,11 +245,12 @@ class CakeEventManagerTest extends CakeTestCase {
$manager->attach(array($anotherListener, 'listenerFunction'), 'fake.event');
$event = new CakeEvent('fake.event');
$firstStep = clone $event;
$listener->expects($this->at(0))->method('listenerFunction')
->with($firstStep)
->with($event)
->will($this->returnValue('something special'));
$anotherListener->expects($this->at(0))->method('listenerFunction')->with($event);
$anotherListener->expects($this->at(0))
->method('listenerFunction')
->with($event);
$manager->dispatch($event);
$this->assertEquals('something special', $event->result);
}
@ -256,6 +261,11 @@ class CakeEventManagerTest extends CakeTestCase {
* @return void
*/
public function testDispatchFalseStopsEvent() {
$this->skipIf(
version_compare(PHPUnit_Runner_Version::id(), '3.7', '<'),
'These tests fail in PHPUnit 3.6'
);
$manager = new CakeEventManager;
$listener = $this->getMock('CakeEventTestListener');
$anotherListener = $this->getMock('CakeEventTestListener');
@ -263,11 +273,11 @@ class CakeEventManagerTest extends CakeTestCase {
$manager->attach(array($anotherListener, 'listenerFunction'), 'fake.event');
$event = new CakeEvent('fake.event');
$originalEvent = clone $event;
$listener->expects($this->at(0))->method('listenerFunction')
->with($originalEvent)
->with($event)
->will($this->returnValue(false));
$anotherListener->expects($this->never())->method('listenerFunction');
$anotherListener->expects($this->never())
->method('listenerFunction');
$manager->dispatch($event);
$this->assertTrue($event->isStopped());
}

View file

@ -175,7 +175,7 @@ class CakeLogTest extends CakeTestCase {
CakeLog::drop('file');
$result = CakeLog::configured();
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
}
/**
@ -331,21 +331,22 @@ class CakeLogTest extends CakeTestCase {
/**
* test backward compatible scoped logging
*
* @return void
*/
public function testScopedLoggingBC() {
$this->_deleteLogs();
$this->_resetLogConfig();
CakeLog::config('shops', array(
'engine' => 'FileLog',
'types' => array('info', 'notice', 'warning'),
'scopes' => array('transactions', 'orders'),
'file' => 'shops',
));
));
$this->_deleteLogs();
CakeLog::write('info', 'info message');
$this->assertFalse(file_exists(LOGS . 'error.log'));
$this->assertTrue(file_exists(LOGS . 'shops.log'));
$this->assertTrue(file_exists(LOGS . 'debug.log'));
$this->_deleteLogs();
@ -375,7 +376,6 @@ class CakeLogTest extends CakeTestCase {
CakeLog::write('warning', 'warning message');
$this->assertTrue(file_exists(LOGS . 'error.log'));
$this->assertTrue(file_exists(LOGS . 'shops.log'));
$this->assertFalse(file_exists(LOGS . 'debug.log'));
$this->_deleteLogs();
@ -383,29 +383,47 @@ class CakeLogTest extends CakeTestCase {
CakeLog::drop('shops');
}
public function testScopedLoggingExclusive() {
$this->_deleteLogs();
CakeLog::config('shops', array(
'engine' => 'FileLog',
'types' => array('info', 'notice', 'warning'),
'scopes' => array('transactions', 'orders'),
'file' => 'shops.log',
));
CakeLog::config('eggs', array(
'engine' => 'FileLog',
'types' => array('info', 'notice', 'warning'),
'scopes' => array('eggs'),
'file' => 'eggs.log',
));
CakeLog::write('info', 'transactions message', 'transactions');
$this->assertFalse(file_exists(LOGS . 'eggs.log'));
$this->assertTrue(file_exists(LOGS . 'shops.log'));
$this->_deleteLogs();
CakeLog::write('info', 'eggs message', 'eggs');
$this->assertTrue(file_exists(LOGS . 'eggs.log'));
$this->assertFalse(file_exists(LOGS . 'shops.log'));
}
/**
* test scoped logging
*
* @return void
*/
public function testScopedLogging() {
if (file_exists(LOGS . 'shops.log')) {
unlink(LOGS . 'shops.log');
}
if (file_exists(LOGS . 'error.log')) {
unlink(LOGS . 'error.log');
}
if (file_exists(LOGS . 'debug.log')) {
unlink(LOGS . 'debug.log');
}
$this->_resetLogConfig();
$this->_deleteLogs();
CakeLog::config('shops', array(
'engine' => 'FileLog',
'types' => array('info', 'notice', 'warning'),
'scopes' => array('transactions', 'orders'),
'file' => 'shops',
));
'file' => 'shops.log',
));
CakeLog::write('info', 'info message', 'transactions');
$this->assertFalse(file_exists(LOGS . 'error.log'));

View file

@ -261,6 +261,19 @@ class ContainableBehaviorTest extends CakeTestCase {
$this->assertFalse(Set::matches('/Comment/User', $r));
}
/**
* Test that mixing contain() and the contain find option.
*
* @return void
*/
public function testContainAndContainOption() {
$this->Article->contain();
$r = $this->Article->find('all', array(
'contain' => array('Comment')
));
$this->assertTrue(isset($r[0]['Comment']), 'No comment returned');
}
/**
* testFindEmbeddedNoBindings method
*
@ -2980,7 +2993,8 @@ class ContainableBehaviorTest extends CakeTestCase {
'User' => array(
'fields' => array('user')
)
)
),
'order' => 'Article.id ASC',
));
$this->assertTrue(isset($result[0]['Article']['title']), 'title missing %s');
$this->assertTrue(isset($result[0]['Article']['body']), 'body missing %s');
@ -3003,7 +3017,10 @@ class ContainableBehaviorTest extends CakeTestCase {
'conditions' => array('created >=' => '2007-03-18 12:24')
)
));
$result = $this->Article->find('all', array('fields' => array('title'), 'order' => array('Article.id' => 'ASC')));
$result = $this->Article->find('all', array(
'fields' => array('title'),
'order' => array('Article.id' => 'ASC')
));
$expected = array(
array(
'Article' => array('id' => 1, 'title' => 'First Article'),

View file

@ -422,7 +422,7 @@ class TranslateBehaviorTest extends CakeTestCase {
$TestModel = new TranslatedItem();
$TestModel->locale = 'rus';
$result = $TestModel->read(null, 1);
$this->assertFalse($result);
$this->assertSame(array(), $result);
$TestModel->locale = array('rus');
$result = $TestModel->read(null, 1);
@ -460,10 +460,10 @@ class TranslateBehaviorTest extends CakeTestCase {
Configure::write('debug', 0);
$result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => false));
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'after'));
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
Configure::write('debug', $debug);
}
@ -530,6 +530,38 @@ class TranslateBehaviorTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* testSaveAssociatedCreate method
*
* @return void
*/
public function testSaveAssociatedMultipleLocale() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel = new TranslatedItem();
$data = array(
'slug' => 'fourth_translated',
'title' => array(
'eng' => 'Title #4',
'spa' => 'Leyenda #4',
),
'content' => array(
'eng' => 'Content #4',
'spa' => 'Contenido #4',
),
'translated_article_id' => 1,
);
$TestModel->create();
$TestModel->saveAssociated($data);
$translations = array('title' => 'Title', 'content' => 'Content');
$TestModel->bindTranslation($translations, false);
$TestModel->locale = array('eng', 'spa');
$result = $TestModel->read();
$this->assertCount(2, $result['Title']);
$this->assertCount(2, $result['Content']);
}
/**
* Test that saving only some of the translated fields allows the record to be found again.
*

View file

@ -354,8 +354,6 @@ class TreeBehaviorNumberTest extends CakeTestCase {
$expected = array_merge(array($modelClass => array('name' => 'testAddMiddle', $parentField => '2')), $result);
$this->assertSame($expected, $result);
$laterCount = $this->Tree->find('count');
$laterCount = $this->Tree->find('count');
$this->assertEquals($initialCount + 1, $laterCount);
@ -369,6 +367,36 @@ class TreeBehaviorNumberTest extends CakeTestCase {
$this->assertSame($validTree, true);
}
/**
* testAddWithPreSpecifiedId method
*
* @return void
*/
public function testAddWithPreSpecifiedId() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find('first', array(
'fields' => array('id'),
'conditions' => array($modelClass . '.name' => '1.1')
));
$this->Tree->create();
$result = $this->Tree->save(array($modelClass => array(
'id' => 100,
'name' => 'testAddMiddle',
$parentField => $data[$modelClass]['id'])
));
$expected = array_merge(
array($modelClass => array('id' => 100, 'name' => 'testAddMiddle', $parentField => '2')),
$result
);
$this->assertSame($expected, $result);
$this->assertTrue($this->Tree->verify());
}
/**
* testAddInvalid method
*

View file

@ -169,12 +169,13 @@ class TreeBehaviorScopedTest extends CakeTestCase {
public function testTranslatingTree() {
$this->Tree = new FlagTree();
$this->Tree->cacheQueries = false;
$this->Tree->Behaviors->attach('Translate', array('name'));
$this->Tree->Behaviors->attach('Translate', array('title'));
//Save
$this->Tree->locale = 'eng';
$data = array('FlagTree' => array(
'name' => 'name #1',
'title' => 'name #1',
'name' => 'test',
'locale' => 'eng',
'parent_id' => null,
));
@ -182,7 +183,8 @@ class TreeBehaviorScopedTest extends CakeTestCase {
$result = $this->Tree->find('all');
$expected = array(array('FlagTree' => array(
'id' => 1,
'name' => 'name #1',
'title' => 'name #1',
'name' => 'test',
'parent_id' => null,
'lft' => 1,
'rght' => 2,
@ -191,15 +193,16 @@ class TreeBehaviorScopedTest extends CakeTestCase {
)));
$this->assertEquals($expected, $result);
//update existing record, same locale
// update existing record, same locale
$this->Tree->create();
$data['FlagTree']['name'] = 'Named 2';
$data['FlagTree']['title'] = 'Named 2';
$this->Tree->id = 1;
$this->Tree->save($data);
$result = $this->Tree->find('all');
$expected = array(array('FlagTree' => array(
'id' => 1,
'name' => 'Named 2',
'title' => 'Named 2',
'name' => 'test',
'parent_id' => null,
'lft' => 1,
'rght' => 2,
@ -208,51 +211,67 @@ class TreeBehaviorScopedTest extends CakeTestCase {
)));
$this->assertEquals($expected, $result);
//update different locale, same record
// update different locale, same record
$this->Tree->create();
$this->Tree->locale = 'deu';
$this->Tree->id = 1;
$data = array('FlagTree' => array(
'id' => 1,
'parent_id' => null,
'name' => 'namen #1',
'title' => 'namen #1',
'name' => 'test',
'locale' => 'deu',
));
$this->Tree->save($data);
$this->Tree->locale = 'deu';
$result = $this->Tree->find('all');
$expected = array(array('FlagTree' => array(
'id' => 1,
'name' => 'namen #1',
'parent_id' => null,
'lft' => 1,
'rght' => 2,
'flag' => 0,
'locale' => 'deu',
)));
$expected = array(
array(
'FlagTree' => array(
'id' => 1,
'title' => 'namen #1',
'name' => 'test',
'parent_id' => null,
'lft' => 1,
'rght' => 2,
'flag' => 0,
'locale' => 'deu',
)
)
);
$this->assertEquals($expected, $result);
//Save with bindTranslation
// Save with bindTranslation
$this->Tree->locale = 'eng';
$data = array(
'name' => array('eng' => 'New title', 'spa' => 'Nuevo leyenda'),
'title' => array('eng' => 'New title', 'spa' => 'Nuevo leyenda'),
'name' => 'test',
'parent_id' => null
);
$this->Tree->create($data);
$this->Tree->save();
$this->Tree->unbindTranslation();
$translations = array('name' => 'Name');
$translations = array('title' => 'Title');
$this->Tree->bindTranslation($translations, false);
$this->Tree->locale = array('eng', 'spa');
$result = $this->Tree->read();
$expected = array(
'FlagTree' => array('id' => 2, 'parent_id' => null, 'locale' => 'eng', 'name' => 'New title', 'flag' => 0, 'lft' => 3, 'rght' => 4),
'Name' => array(
array('id' => 21, 'locale' => 'eng', 'model' => 'FlagTree', 'foreign_key' => 2, 'field' => 'name', 'content' => 'New title'),
array('id' => 22, 'locale' => 'spa', 'model' => 'FlagTree', 'foreign_key' => 2, 'field' => 'name', 'content' => 'Nuevo leyenda')
'FlagTree' => array(
'id' => 2,
'parent_id' => null,
'locale' => 'eng',
'name' => 'test',
'title' => 'New title',
'flag' => 0,
'lft' => 3,
'rght' => 4
),
'Title' => array(
array('id' => 21, 'locale' => 'eng', 'model' => 'FlagTree', 'foreign_key' => 2, 'field' => 'title', 'content' => 'New title'),
array('id' => 22, 'locale' => 'spa', 'model' => 'FlagTree', 'foreign_key' => 2, 'field' => 'title', 'content' => 'Nuevo leyenda')
),
);
$this->assertEquals($expected, $result);

View file

@ -21,6 +21,7 @@
App::uses('Model', 'Model');
App::uses('AppModel', 'Model');
App::uses('String', 'Utility');
require_once dirname(dirname(__FILE__)) . DS . 'models.php';
/**
@ -56,6 +57,37 @@ class TreeBehaviorUuidTest extends CakeTestCase {
*/
public $fixtures = array('core.uuid_tree');
/**
* testAddWithPreSpecifiedId method
*
* @return void
*/
public function testAddWithPreSpecifiedId() {
extract($this->settings);
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find('first', array(
'fields' => array('id'),
'conditions' => array($modelClass . '.name' => '1.1')
));
$id = String::uuid();
$this->Tree->create();
$result = $this->Tree->save(array($modelClass => array(
'id' => $id,
'name' => 'testAddMiddle',
$parentField => $data[$modelClass]['id'])
));
$expected = array_merge(
array($modelClass => array('id' => $id, 'name' => 'testAddMiddle', $parentField => '2')),
$result
);
$this->assertSame($expected, $result);
$this->assertTrue($this->Tree->verify());
}
/**
* testMovePromote method
*

View file

@ -786,21 +786,22 @@ class BehaviorCollectionTest extends CakeTestCase {
public function testBehaviorBelongsToFindCallbacks() {
$this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.');
$conditions = array('order' => 'Apple.id ASC');
$Apple = new Apple();
$Apple->unbindModel(array('hasMany' => array('Child'), 'hasOne' => array('Sample')), false);
$expected = $Apple->find('all');
$expected = $Apple->find('all', $conditions);
$Apple->unbindModel(array('belongsTo' => array('Parent')));
$wellBehaved = $Apple->find('all');
$wellBehaved = $Apple->find('all', $conditions);
$Apple->Parent->Behaviors->attach('Test');
$Apple->unbindModel(array('belongsTo' => array('Parent')));
$this->assertSame($Apple->find('all'), $wellBehaved);
$this->assertSame($Apple->find('all', $conditions), $wellBehaved);
$Apple->Parent->Behaviors->attach('Test', array('before' => 'off'));
$this->assertSame($expected, $Apple->find('all'));
$this->assertSame($expected, $Apple->find('all', $conditions));
$Apple->Parent->Behaviors->attach('Test', array('before' => 'test'));
$this->assertSame($expected, $Apple->find('all'));
$this->assertSame($expected, $Apple->find('all', $conditions));
$Apple->Parent->Behaviors->attach('Test', array('before' => 'modify'));
$expected2 = array(
@ -816,22 +817,23 @@ class BehaviorCollectionTest extends CakeTestCase {
);
$result2 = $Apple->find('all', array(
'fields' => array('Apple.id', 'Parent.id', 'Parent.name', 'Parent.mytime'),
'conditions' => array('Apple.id <' => '4')
'conditions' => array('Apple.id <' => '4'),
'order' => 'Apple.id ASC',
));
$this->assertEquals($expected2, $result2);
$Apple->Parent->Behaviors->disable('Test');
$result = $Apple->find('all');
$result = $Apple->find('all', $conditions);
$this->assertEquals($expected, $result);
$Apple->Parent->Behaviors->attach('Test', array('after' => 'off'));
$this->assertEquals($expected, $Apple->find('all'));
$this->assertEquals($expected, $Apple->find('all', $conditions));
$Apple->Parent->Behaviors->attach('Test', array('after' => 'test'));
$this->assertEquals($expected, $Apple->find('all'));
$this->assertEquals($expected, $Apple->find('all', $conditions));
$Apple->Parent->Behaviors->attach('Test', array('after' => 'test2'));
$this->assertEquals($expected, $Apple->find('all'));
$this->assertEquals($expected, $Apple->find('all', $conditions));
}
/**

View file

@ -877,6 +877,52 @@ class MysqlTest extends CakeTestCase {
$this->assertContains('`user_id` int(11) NOT NULL,', $result);
}
/**
* Test that the primary flag is handled correctly.
*
* @return void
*/
public function testCreateSchemaAutoPrimaryKey() {
$schema = new CakeSchema();
$schema->tables = array(
'no_indexes' => array(
'id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'),
'data' => array('type' => 'integer', 'null' => false),
'indexes' => array(),
)
);
$result = $this->Dbo->createSchema($schema, 'no_indexes');
$this->assertContains('PRIMARY KEY (`id`)', $result);
$this->assertNotContains('UNIQUE KEY', $result);
$schema->tables = array(
'primary_index' => array(
'id' => array('type' => 'integer', 'null' => false),
'data' => array('type' => 'integer', 'null' => false),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'some_index' => array('column' => 'data', 'unique' => 1)
),
)
);
$result = $this->Dbo->createSchema($schema, 'primary_index');
$this->assertContains('PRIMARY KEY (`id`)', $result);
$this->assertContains('UNIQUE KEY `some_index` (`data`)', $result);
$schema->tables = array(
'primary_flag_has_index' => array(
'id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'),
'data' => array('type' => 'integer', 'null' => false),
'indexes' => array (
'some_index' => array('column' => 'data', 'unique' => 1)
),
)
);
$result = $this->Dbo->createSchema($schema, 'primary_flag_has_index');
$this->assertContains('PRIMARY KEY (`id`)', $result);
$this->assertContains('UNIQUE KEY `some_index` (`data`)', $result);
}
/**
* Tests that listSources method sends the correct query and parses the result accordingly
* @return void
@ -1914,7 +1960,7 @@ class MysqlTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Dbo->conditions(array('score' => array(2 => 1, 2, 10)));
$expected = " WHERE score IN (1, 2, 10)";
$expected = " WHERE `score` IN (1, 2, 10)";
$this->assertEquals($expected, $result);
$result = $this->Dbo->conditions("Aro.rght = Aro.lft + 1.1");
@ -2194,7 +2240,7 @@ class MysqlTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Dbo->conditions(array('score' => array(1, 2, 10)));
$expected = " WHERE score IN (1, 2, 10)";
$expected = " WHERE `score` IN (1, 2, 10)";
$this->assertEquals($expected, $result);
$result = $this->Dbo->conditions(array('score' => array()));
@ -2285,7 +2331,7 @@ class MysqlTest extends CakeTestCase {
'NOT' => array('Course.id' => null, 'Course.vet' => 'N', 'level_of_education_id' => array(912,999)),
'Enrollment.yearcompleted >' => '0')
);
$this->assertRegExp('/^\s*WHERE\s+\(NOT\s+\(`Course`\.`id` IS NULL\)\s+AND NOT\s+\(`Course`\.`vet`\s+=\s+\'N\'\)\s+AND NOT\s+\(level_of_education_id IN \(912, 999\)\)\)\s+AND\s+`Enrollment`\.`yearcompleted`\s+>\s+\'0\'\s*$/', $result);
$this->assertRegExp('/^\s*WHERE\s+\(NOT\s+\(`Course`\.`id` IS NULL\)\s+AND NOT\s+\(`Course`\.`vet`\s+=\s+\'N\'\)\s+AND NOT\s+\(`level_of_education_id` IN \(912, 999\)\)\)\s+AND\s+`Enrollment`\.`yearcompleted`\s+>\s+\'0\'\s*$/', $result);
$result = $this->Dbo->conditions(array('id <>' => '8'));
$this->assertRegExp('/^\s*WHERE\s+`id`\s+<>\s+\'8\'\s*$/', $result);
@ -2321,7 +2367,7 @@ class MysqlTest extends CakeTestCase {
$conditions = array('id' => array(2, 5, 6, 9, 12, 45, 78, 43, 76));
$result = $this->Dbo->conditions($conditions);
$expected = " WHERE id IN (2, 5, 6, 9, 12, 45, 78, 43, 76)";
$expected = " WHERE `id` IN (2, 5, 6, 9, 12, 45, 78, 43, 76)";
$this->assertEquals($expected, $result);
$conditions = array('title' => 'user(s)');

View file

@ -574,7 +574,7 @@ class SqlserverTest extends CakeTestCase {
$indexes = array('client_id' => array('column' => 'client_id'));
$result = $this->db->buildIndex($indexes, 'items');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$indexes = array('client_id' => array('column' => array('client_id', 'period_id'), 'unique' => 1));
$result = $this->db->buildIndex($indexes, 'items');

View file

@ -1103,4 +1103,73 @@ class DboSourceTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* Test conditionKeysToString()
*
* @return void
*/
public function testConditionKeysToString() {
$Article = ClassRegistry::init('Article');
$conn = $this->getMock('MockPDO', array('quote'));
$db = new DboTestSource;
$db->setConnection($conn);
$conn->expects($this->at(0))
->method('quote')
->will($this->returnValue('just text'));
$conditions = array('Article.name' => 'just text');
$result = $db->conditionKeysToString($conditions, true, $Article);
$expected = "Article.name = just text";
$this->assertEquals($expected, $result[0]);
$conn->expects($this->at(0))
->method('quote')
->will($this->returnValue('just text'));
$conn->expects($this->at(1))
->method('quote')
->will($this->returnValue('other text'));
$conditions = array('Article.name' => array('just text', 'other text'));
$result = $db->conditionKeysToString($conditions, true, $Article);
$expected = "Article.name IN (just text, other text)";
$this->assertEquals($expected, $result[0]);
}
/**
* Test conditionKeysToString() with virtual field
*
* @return void
*/
public function testConditionKeysToStringVirtualField() {
$Article = ClassRegistry::init('Article');
$Article->virtualFields = array(
'extra' => 'something virtual'
);
$conn = $this->getMock('MockPDO', array('quote'));
$db = new DboTestSource;
$db->setConnection($conn);
$conn->expects($this->at(0))
->method('quote')
->will($this->returnValue('just text'));
$conditions = array('Article.extra' => 'just text');
$result = $db->conditionKeysToString($conditions, true, $Article);
$expected = "(" . $Article->virtualFields['extra'] . ") = just text";
$this->assertEquals($expected, $result[0]);
$conn->expects($this->at(0))
->method('quote')
->will($this->returnValue('just text'));
$conn->expects($this->at(1))
->method('quote')
->will($this->returnValue('other text'));
$conditions = array('Article.extra' => array('just text', 'other text'));
$result = $db->conditionKeysToString($conditions, true, $Article);
$expected = "(" . $Article->virtualFields['extra'] . ") IN (just text, other text)";
$this->assertEquals($expected, $result[0]);
}
}

View file

@ -107,12 +107,12 @@ class ModelDeleteTest extends BaseModelTest {
$result = $Portfolio->find('first', array(
'conditions' => array('Portfolio.id' => 1)
));
$this->assertFalse($result);
$this->assertSame(array(), $result);
$result = $Portfolio->ItemsPortfolio->find('all', array(
'conditions' => array('ItemsPortfolio.portfolio_id' => 1)
));
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
}
/**
@ -195,7 +195,7 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertTrue($result);
$result = $TestModel->read(null, 2);
$this->assertFalse($result);
$this->assertSame(array(), $result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
@ -216,7 +216,7 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertTrue($result);
$result = $TestModel->read(null, 3);
$this->assertFalse($result);
$this->assertSame(array(), $result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
@ -448,16 +448,16 @@ class ModelDeleteTest extends BaseModelTest {
$TestModel->recursive = 2;
$result = $TestModel->read(null, 2);
$this->assertFalse($result);
$this->assertSame(array(), $result);
$result = $TestModel->Comment->read(null, 5);
$this->assertFalse($result);
$this->assertSame(array(), $result);
$result = $TestModel->Comment->read(null, 6);
$this->assertFalse($result);
$this->assertSame(array(), $result);
$result = $TestModel->Comment->Attachment->read(null, 1);
$this->assertFalse($result);
$this->assertSame(array(), $result);
$result = $TestModel->find('count');
$this->assertEquals(2, $result);

View file

@ -4203,7 +4203,8 @@ class ModelReadTest extends BaseModelTest {
$this->assertTrue($result);
$result = $TestModel->find('all', array(
'fields' => 'User.id, User.user'
'fields' => 'User.id, User.user',
'order' => array('User.id' => 'ASC'),
));
$expected = array(
array(
@ -4290,13 +4291,14 @@ class ModelReadTest extends BaseModelTest {
$TestModel->resetAssociations();
$result = $TestModel->hasMany;
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$result = $TestModel->bindModel(array('hasMany' => array('Comment')), false);
$this->assertTrue($result);
$result = $TestModel->find('all', array(
'fields' => 'User.id, User.user'
'fields' => 'User.id, User.user',
'order' => array('User.id' => 'ASC'),
));
$expected = array(
@ -4407,7 +4409,8 @@ class ModelReadTest extends BaseModelTest {
$this->assertEquals($expected, $result);
$result = $TestModel->find('all', array(
'fields' => 'User.id, User.user'
'fields' => 'User.id, User.user',
'order' => array('User.id' => 'ASC'),
));
$expected = array(
array('User' => array('id' => '1', 'user' => 'mariano')),
@ -4417,7 +4420,8 @@ class ModelReadTest extends BaseModelTest {
$this->assertEquals($expected, $result);
$result = $TestModel->find('all', array(
'fields' => 'User.id, User.user'
'fields' => 'User.id, User.user',
'order' => array('User.id' => 'ASC'),
));
$expected = array(
array(
@ -4505,7 +4509,10 @@ class ModelReadTest extends BaseModelTest {
$result = $TestModel->unbindModel(array('hasMany' => array('Comment')), false);
$this->assertTrue($result);
$result = $TestModel->find('all', array('fields' => 'User.id, User.user'));
$result = $TestModel->find('all', array(
'fields' => 'User.id, User.user',
'order' => array('User.id' => 'ASC'),
));
$expected = array(
array('User' => array('id' => '1', 'user' => 'mariano')),
array('User' => array('id' => '2', 'user' => 'nate')),
@ -4522,7 +4529,10 @@ class ModelReadTest extends BaseModelTest {
)));
$this->assertTrue($result);
$result = $TestModel->find('all', array('fields' => 'User.id, User.user'));
$result = $TestModel->find('all', array(
'fields' => 'User.id, User.user',
'order' => array('User.id' => 'ASC'),
));
$expected = array(
array(
'User' => array(
@ -4959,7 +4969,9 @@ class ModelReadTest extends BaseModelTest {
public function testAssociationAfterFind() {
$this->loadFixtures('Post', 'Author', 'Comment');
$TestModel = new Post();
$result = $TestModel->find('all');
$result = $TestModel->find('all', array(
'order' => array('Post.id' => 'ASC')
));
$expected = array(
array(
'Post' => array(
@ -5028,6 +5040,7 @@ class ModelReadTest extends BaseModelTest {
)));
$result = $Author->find('all', array(
'conditions' => array('Author.id' => 1),
'order' => array('Author.id' => 'ASC'),
'recursive' => 2
));
$expected = array(
@ -5110,7 +5123,10 @@ class ModelReadTest extends BaseModelTest {
public function testAssociationAfterFindCalbacksDisabled() {
$this->loadFixtures('Post', 'Author', 'Comment');
$TestModel = new Post();
$result = $TestModel->find('all', array('callbacks' => false));
$result = $TestModel->find('all', array(
'callbacks' => false,
'order' => array('Post.id' => 'ASC'),
));
$expected = array(
array(
'Post' => array(
@ -5177,6 +5193,7 @@ class ModelReadTest extends BaseModelTest {
$result = $Author->find('all', array(
'conditions' => array('Author.id' => 1),
'recursive' => 2,
'order' => array('Author.id' => 'ASC'),
'callbacks' => false
));
$expected = array(
@ -6860,6 +6877,17 @@ class ModelReadTest extends BaseModelTest {
));
$result = $Article->find('count', array('group' => array('Article.user_id')));
$this->assertEquals($expected, $result);
$expected = count($Article->find('all', array(
'fields' => array('Article.user_id'),
'conditions' => array('Article.user_id' => 1),
'group' => 'Article.user_id')
));
$result = $Article->find('count', array(
'conditions' => array('Article.user_id' => 1),
'group' => array('Article.user_id'),
));
$this->assertEquals($expected, $result);
}
/**
@ -6886,7 +6914,7 @@ class ModelReadTest extends BaseModelTest {
$this->skipIf($this->db instanceof Sqlite, 'SELECT COUNT(DISTINCT field) is not compatible with SQLite.');
$this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.');
$this->loadFixtures('Project');
$this->loadFixtures('Project', 'Thread');
$TestModel = new Project();
$TestModel->create(array('name' => 'project')) && $TestModel->save();
$TestModel->create(array('name' => 'project')) && $TestModel->save();
@ -7745,7 +7773,9 @@ class ModelReadTest extends BaseModelTest {
$this->assertEquals($expected, $result);
$Post->Author->virtualFields = array('joined' => 'Post.id * Author.id');
$result = $Post->find('all');
$result = $Post->find('all', array(
'order' => array('Post.id' => 'ASC')
));
$result = Hash::extract($result, '{n}.Author.joined');
$expected = array(1, 6, 3);
$this->assertEquals($expected, $result);

View file

@ -4536,7 +4536,7 @@ class ModelWriteTest extends BaseModelTest {
$this->assertFalse($result);
$result = $model->find('all');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$expected = array('Comment' => array(
1 => array('comment' => array('This field cannot be left blank'))
));
@ -4725,6 +4725,32 @@ class ModelWriteTest extends BaseModelTest {
$this->assertEquals($expected, $TestModel->Comment->validationErrors);
}
/**
* test that saveAll still behaves like previous versions (does not necessarily need a first argument)
*
* @return void
*/
public function testSaveAllWithSet() {
$this->loadFixtures('Article', 'Tag', 'Comment', 'User', 'ArticlesTag');
$data = array(
'Article' => array(
'user_id' => 1,
'title' => 'Article Has and belongs to Many Tags'
),
'Tag' => array(
'Tag' => array(1, 2)
),
'Comment' => array(
array(
'comment' => 'Article comment',
'user_id' => 1
)));
$Article = new Article();
$Article->set($data);
$result = $Article->saveAll();
$this->assertFalse(empty($result));
}
/**
* test that saveAll behaves like plain save() when supplied empty data
*
@ -4740,7 +4766,7 @@ class ModelWriteTest extends BaseModelTest {
$this->assertFalse(empty($result));
$model = new ProductUpdateAll();
$result = $model->saveAll(array());
$result = $model->saveAll();
$this->assertFalse($result);
}
@ -4830,6 +4856,51 @@ class ModelWriteTest extends BaseModelTest {
$this->assertEquals($expected, $result[6]['Attachment']);
}
/**
* Test that validate = first, atomic = false works when associated records
* fail validation.
*
* @return void
*/
public function testSaveAssociatedAtomicFalseValidateFirstWithErrors() {
$this->loadFixtures('Comment', 'Article', 'User');
$Article = ClassRegistry::init('Article');
$Article->Comment->validator()->add('comment', array(
array('rule' => 'notEmpty')
));
$data = array(
'Article' => array(
'user_id' => 1,
'title' => 'Foo',
'body' => 'text',
'published' => 'N'
),
'Comment' => array(
array(
'user_id' => 1,
'comment' => '',
'published' => 'N',
)
),
);
$Article->saveAssociated(
$data,
array('validate' => 'first', 'atomic' => false)
);
$result = $Article->validationErrors;
$expected = array(
'Comment' => array(
array(
'comment' => array( 'This field cannot be left blank' )
)
)
);
$this->assertEquals($expected, $result);
}
/**
* testSaveMany method
*
@ -5869,7 +5940,7 @@ class ModelWriteTest extends BaseModelTest {
$this->assertFalse($result);
$result = $model->find('all');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$expected = array('Comment' => array(
1 => array('comment' => array('This field cannot be left blank'))
));

View file

@ -171,4 +171,29 @@ class CakeValidationRuleTest extends CakeTestCase {
$Rule->isUpdate(true);
$this->assertTrue($Rule->isEmptyAllowed());
}
/**
* Test checkRequired method
*
* @return void
*/
public function testCheckRequiredWhenRequiredAndAllowEmpty() {
$Rule = $this->getMock('CakeValidationRule', array('isRequired'));
$Rule->expects($this->any())
->method('isRequired')
->will($this->returnValue(true));
$Rule->allowEmpty = true;
$fieldname = 'field';
$data = array(
$fieldname => null
);
$this->assertFalse($Rule->checkRequired($fieldname, $data), "A null but present field should not fail requirement check if allowEmpty is true");
$Rule->allowEmpty = false;
$this->assertTrue($Rule->checkRequired($fieldname, $data), "A null but present field should fail requirement check if allowEmpty is false");
}
}

View file

@ -156,10 +156,22 @@ class CakeValidationSetTest extends CakeTestCase {
$result = $Field->getRules();
$this->assertEquals(array('validEmail'), array_keys($result));
$Field->setRules(array('validEmail' => $rule), false);
$result = $Field->getRules();
$this->assertEquals(array('validEmail'), array_keys($result));
$this->assertTrue(array_pop($result) instanceof CakeValidationRule);
$rules = array('notEmpty' => $RuleEmpty);
$Field->setRules($rules, true);
$result = $Field->getRules();
$this->assertEquals(array('validEmail', 'notEmpty'), array_keys($result));
$rules = array('notEmpty' => array('rule' => 'notEmpty'));
$Field->setRules($rules, true);
$result = $Field->getRules();
$this->assertEquals(array('validEmail', 'notEmpty'), array_keys($result));
$this->assertTrue(array_pop($result) instanceof CakeValidationRule);
$this->assertTrue(array_pop($result) instanceof CakeValidationRule);
}
/**

View file

@ -311,9 +311,10 @@ class CakeRequestTest extends CakeTestCase {
$request = $this->getMock('TestCakeRequest', array('_readInput'));
$request->expects($this->at(0))->method('_readInput')
->will($this->returnValue('{Article":["title"]}'));
->will($this->returnValue('{"Article":["title"]}'));
$request->reConstruct();
$this->assertEquals('{Article":["title"]}', $request->data);
$result = $request->input('json_decode', true);
$this->assertEquals(array('title'), $result['Article']);
}
/**
@ -587,6 +588,24 @@ class CakeRequestTest extends CakeTestCase {
$this->assertEquals($request->params['form'], $_FILES);
}
/**
* Test that files in the 0th index work.
*/
public function testFilesZeroithIndex() {
$_FILES = array(
0 => array(
'name' => 'cake_sqlserver_patch.patch',
'type' => 'text/plain',
'tmp_name' => '/private/var/tmp/phpy05Ywj',
'error' => 0,
'size' => 6271,
),
);
$request = new CakeRequest('some/path');
$this->assertEquals($_FILES, $request->params['form']);
}
/**
* test method overrides coming in from POST data.
*
@ -1628,6 +1647,30 @@ class CakeRequestTest extends CakeTestCase {
'webroot' => '/',
),
),
array(
'Apache - w/rewrite, document root set above top level cake dir, request root, absolute REQUEST_URI',
array(
'App' => array(
'base' => false,
'baseUrl' => false,
'dir' => 'app',
'webroot' => 'webroot'
),
'SERVER' => array(
'SERVER_NAME' => 'localhost',
'DOCUMENT_ROOT' => '/Library/WebServer/Documents',
'SCRIPT_FILENAME' => '/Library/WebServer/Documents/site/index.php',
'REQUEST_URI' => FULL_BASE_URL . '/site/posts/index',
'SCRIPT_NAME' => '/site/app/webroot/index.php',
'PHP_SELF' => '/site/app/webroot/index.php',
),
),
array(
'url' => 'posts/index',
'base' => '/site',
'webroot' => '/site/',
),
),
array(
'Nginx - w/rewrite, document root set to webroot, request root, no PATH_INFO',
array(
@ -1667,7 +1710,7 @@ class CakeRequestTest extends CakeTestCase {
*/
public function testEnvironmentDetection($name, $env, $expected) {
$_GET = array();
$this->__loadEnvironment($env);
$this->_loadEnvironment($env);
$request = new CakeRequest();
$this->assertEquals($expected['url'], $request->url, "url error");
@ -1870,7 +1913,7 @@ XML;
* @param array $env
* @return void
*/
protected function __loadEnvironment($env) {
protected function _loadEnvironment($env) {
if (isset($env['App'])) {
Configure::write('App', $env['App']);
}

View file

@ -762,6 +762,38 @@ class HttpSocketTest extends CakeTestCase {
$this->assertEquals('HTTP/1.x 2', $response->first10);
}
/**
* Test that redirect urls are urldecoded
*
* @return void
*/
public function testRequestWithRedirectUrlEncoded() {
$request = array(
'uri' => 'http://localhost/oneuri',
'redirect' => 1
);
$serverResponse1 = "HTTP/1.x 302 Found\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\nLocation: http://i.cmpnet.com%2Ftechonline%2Fpdf%2Fa.pdf=\r\n\r\n";
$serverResponse2 = "HTTP/1.x 200 OK\r\nDate: Mon, 16 Apr 2007 04:14:16 GMT\r\nServer: CakeHttp Server\r\nContent-Type: text/html\r\n\r\n<h1>You have been redirected</h1>";
$this->Socket->expects($this->at(1))
->method('read')
->will($this->returnValue($serverResponse1));
$this->Socket->expects($this->at(3))
->method('write')
->with($this->logicalAnd(
$this->stringContains('Host: i.cmpnet.com'),
$this->stringContains('GET /techonline/pdf/a.pdf')
));
$this->Socket->expects($this->at(4))
->method('read')
->will($this->returnValue($serverResponse2));
$response = $this->Socket->request($request);
$this->assertEquals('<h1>You have been redirected</h1>', $response->body());
}
/**
* testRequestWithRedirect method
*
@ -781,6 +813,11 @@ class HttpSocketTest extends CakeTestCase {
$this->assertEquals('<h1>You have been redirected</h1>', $response->body());
}
/**
* Test that redirects with a count limit are decremented.
*
* @return void
*/
public function testRequestWithRedirectAsInt() {
$request = array(
'uri' => 'http://localhost/oneuri',
@ -795,6 +832,11 @@ class HttpSocketTest extends CakeTestCase {
$this->assertEquals(1, $this->Socket->request['redirect']);
}
/**
* Test that redirects after the redirect count reaches 9 are not followed.
*
* @return void
*/
public function testRequestWithRedirectAsIntReachingZero() {
$request = array(
'uri' => 'http://localhost/oneuri',

View file

@ -1574,7 +1574,7 @@ class DispatcherTest extends CakeTestCase {
$this->assertTextEquals($out, $cached);
$filename = $this->__cachePath($request->here());
$filename = $this->_cachePath($request->here());
unlink($filename);
}
@ -1657,79 +1657,13 @@ class DispatcherTest extends CakeTestCase {
unset($_POST['_method']);
}
/**
* backupEnvironment method
*
* @return void
*/
protected function __backupEnvironment() {
return array(
'App' => Configure::read('App'),
'GET' => $_GET,
'POST' => $_POST,
'SERVER' => $_SERVER
);
}
/**
* reloadEnvironment method
*
* @return void
*/
protected function __reloadEnvironment() {
foreach ($_GET as $key => $val) {
unset($_GET[$key]);
}
foreach ($_POST as $key => $val) {
unset($_POST[$key]);
}
foreach ($_SERVER as $key => $val) {
unset($_SERVER[$key]);
}
Configure::write('App', array());
}
/**
* loadEnvironment method
*
* @param array $env
* @return void
*/
protected function __loadEnvironment($env) {
if ($env['reload']) {
$this->__reloadEnvironment();
}
if (isset($env['App'])) {
Configure::write('App', $env['App']);
}
if (isset($env['GET'])) {
foreach ($env['GET'] as $key => $val) {
$_GET[$key] = $val;
}
}
if (isset($env['POST'])) {
foreach ($env['POST'] as $key => $val) {
$_POST[$key] = $val;
}
}
if (isset($env['SERVER'])) {
foreach ($env['SERVER'] as $key => $val) {
$_SERVER[$key] = $val;
}
}
}
/**
* cachePath method
*
* @param string $here
* @return string
*/
protected function __cachePath($here) {
protected function _cachePath($here) {
$path = $here;
if ($here == '/') {
$path = 'home';

View file

@ -111,7 +111,7 @@ class RouterTest extends CakeTestCase {
$_SERVER['REQUEST_METHOD'] = 'GET';
$result = Router::parse('/posts/add');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
Router::reload();
$resources = Router::mapResources('Posts', array('id' => '[a-z0-9_]+'));
@ -1907,7 +1907,7 @@ class RouterTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = Router::parse('/blog/foobar');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$result = Router::url(array('controller' => 'blog_posts', 'action' => 'foo'));
$this->assertEquals('/blog_posts/foo', $result);
@ -2117,7 +2117,7 @@ class RouterTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = Router::parse('/badness/test/test_action');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
Router::reload();
Router::connect('/:locale/:controller/:action/*', array(), array('locale' => 'dan|eng'));

View file

@ -340,14 +340,14 @@ class CakeTimeTest extends CakeTestCase {
$this->assertEquals(date('Y-d-m', $time), $this->Time->nice($time));
$this->assertEquals('%Y-%d-%m', $this->Time->niceFormat);
CakeTime::$niceFormat = '%Y-%d-%m %H:%M:%S';
$this->assertEquals(date('Y-d-m H:i:s', $time), $this->Time->nice($time));
$this->assertEquals('%Y-%d-%m %H:%M:%S', $this->Time->niceFormat);
CakeTime::$niceFormat = '%Y-%d-%m %H:%M';
$this->assertEquals(date('Y-d-m H:i', $time), $this->Time->nice($time));
$this->assertEquals('%Y-%d-%m %H:%M', $this->Time->niceFormat);
date_default_timezone_set('UTC');
$result = $this->Time->nice(null, 'America/New_York');
$expected = $this->Time->nice(time(), 'America/New_York');
$this->assertEquals($expected, $result);
$this->assertEquals(substr($expected, 0, -1), substr($result, 0, -1));
$this->_restoreSystemTimezone();
}
@ -474,7 +474,7 @@ class CakeTimeTest extends CakeTestCase {
date_default_timezone_set('UTC');
$serverTime = new DateTime('now');
$serverTime = new DateTime('2012-12-11 14:15:20');
$timezones = array('Europe/London', 'Europe/Brussels', 'UTC', 'America/Denver', 'America/Caracas', 'Asia/Kathmandu');
foreach ($timezones as $timezone) {
@ -509,17 +509,18 @@ class CakeTimeTest extends CakeTestCase {
* @return void
*/
public function testToRss() {
$this->assertEquals(date('r'), $this->Time->toRss(time()));
$date = '2012-08-12 12:12:45';
$time = strtotime($date);
$this->assertEquals(date('r', $time), $this->Time->toRss($time));
if (!$this->skipIf(!class_exists('DateTimeZone'), '%s DateTimeZone class not available.')) {
$timezones = array('Europe/London', 'Europe/Brussels', 'UTC', 'America/Denver', 'America/Caracas', 'Asia/Kathmandu');
foreach ($timezones as $timezone) {
$yourTimezone = new DateTimeZone($timezone);
$yourTime = new DateTime('now', $yourTimezone);
$userOffset = $yourTimezone->getOffset($yourTime) / HOUR;
$this->assertEquals($yourTime->format('r'), $this->Time->toRss(time(), $userOffset));
$this->assertEquals($yourTime->format('r'), $this->Time->toRss(time(), $timezone));
}
$timezones = array('Europe/London', 'Europe/Brussels', 'UTC', 'America/Denver', 'America/Caracas', 'Asia/Kathmandu');
foreach ($timezones as $timezone) {
$yourTimezone = new DateTimeZone($timezone);
$yourTime = new DateTime($date, $yourTimezone);
$userOffset = $yourTimezone->getOffset($yourTime) / HOUR;
$time = $yourTime->format('U');
$this->assertEquals($yourTime->format('r'), $this->Time->toRss($time, $userOffset), "Failed on $timezone");
$this->assertEquals($yourTime->format('r'), $this->Time->toRss($time, $timezone), "Failed on $timezone");
}
}
@ -779,17 +780,17 @@ class CakeTimeTest extends CakeTestCase {
$expected = time();
$result = $this->Time->fromString(time(), $yourTimezone);
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
$result = $this->Time->fromString(time(), $timezoneServer->getName());
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
$result = $this->Time->fromString(time(), $timezoneServer);
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
Configure::write('Config.timezone', $timezoneServer->getName());
$result = $this->Time->fromString(time());
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
Configure::delete('Config.timezone');
}
@ -807,17 +808,17 @@ class CakeTimeTest extends CakeTestCase {
$result = $this->Time->fromString('+1 hour');
$expected = strtotime('+1 hour');
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
$timezone = date('Z', time());
$result = $this->Time->fromString('+1 hour', $timezone);
$expected = $this->Time->convert(strtotime('+1 hour'), $timezone);
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
$timezone = date_default_timezone_get();
$result = $this->Time->fromString('+1 hour', $timezone);
$expected = $this->Time->convert(strtotime('+1 hour'), $timezone);
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
date_default_timezone_set('UTC');
$date = new DateTime('now', new DateTimeZone('Europe/London'));
@ -840,7 +841,7 @@ class CakeTimeTest extends CakeTestCase {
$date->setTimezone(new DateTimeZone('UTC'));
$expected = $date->format('U') + $date->getOffset();
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
date_default_timezone_set('Australia/Melbourne');
@ -848,7 +849,7 @@ class CakeTimeTest extends CakeTestCase {
$result = $this->Time->fromString($date, 'Asia/Kuwait');
$date->setTimezone(new DateTimeZone('Asia/Kuwait'));
$expected = $date->format('U') + $date->getOffset();
$this->assertEquals($expected, $result);
$this->assertWithinMargin($expected, $result, 1);
$this->_restoreSystemTimezone();
}
@ -1058,10 +1059,10 @@ class CakeTimeTest extends CakeTestCase {
public function testCorrectTimezoneConversion() {
date_default_timezone_set('UTC');
$date = '2012-01-01 10:00:00';
$converted = CakeTime::format($date, '%Y-%m-%d %H:%M:%S', '', 'Europe/Copenhagen');
$converted = CakeTime::format($date, '%Y-%m-%d %H:%M', '', 'Europe/Copenhagen');
$expected = new DateTime($date);
$expected->setTimezone(new DateTimeZone('Europe/Copenhagen'));
$this->assertEquals($expected->format('Y-m-d H:i:s'), $converted);
$this->assertEquals($expected->format('Y-m-d H:i'), $converted);
}
}

View file

@ -298,7 +298,6 @@ class HashTest extends CakeTestCase {
'Author' => array('id' => '3', 'user' => 'larry', 'password' => null),
)
);
$result = Hash::flatten($data);
$expected = array(
'0.Post.id' => '1',
@ -317,6 +316,21 @@ class HashTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$data = array(
array(
'Post' => array('id' => '1', 'author_id' => null, 'title' => 'First Post'),
'Author' => array(),
)
);
$result = Hash::flatten($data);
$expected = array(
'0.Post.id' => '1',
'0.Post.author_id' => null,
'0.Post.title' => 'First Post',
'0.Author' => array()
);
$this->assertEquals($expected, $result);
$data = array(
array('Post' => array('id' => 1)),
array('Post' => array('id' => 2)),

View file

@ -109,6 +109,7 @@ class InflectorTest extends CakeTestCase {
$this->assertEquals(Inflector::singularize('roofs'), 'roof');
$this->assertEquals(Inflector::singularize('foes'), 'foe');
$this->assertEquals(Inflector::singularize('databases'), 'database');
$this->assertEquals(Inflector::singularize('cookies'), 'cookie');
$this->assertEquals(Inflector::singularize(''), '');
}
@ -160,6 +161,7 @@ class InflectorTest extends CakeTestCase {
$this->assertEquals(Inflector::pluralize('cafe'), 'cafes');
$this->assertEquals(Inflector::pluralize('roof'), 'roofs');
$this->assertEquals(Inflector::pluralize('foe'), 'foes');
$this->assertEquals(Inflector::pluralize('cookie'), 'cookies');
$this->assertEquals(Inflector::pluralize(''), '');
}

View file

@ -1967,7 +1967,7 @@ class SetTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = Set::combine($a, 'fail', 'fail');
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
}
/**
@ -3054,6 +3054,7 @@ class SetTest extends CakeTestCase {
/**
* Tests Set::flatten
*
* @see Hash test cases, as Set::flatten() is just a proxy.
* @return void
*/
public function testFlatten() {
@ -3064,6 +3065,21 @@ class SetTest extends CakeTestCase {
$data[9] = 'Shemp';
$result = Set::flatten($data);
$this->assertEquals($data, $result);
$data = array(
array(
'Post' => array('id' => '1', 'author_id' => null, 'title' => 'First Post'),
'Author' => array(),
)
);
$result = Set::flatten($data);
$expected = array(
'0.Post.id' => '1',
'0.Post.author_id' => null,
'0.Post.title' => 'First Post',
'0.Author' => array()
);
$this->assertEquals($expected, $result);
}
/**

View file

@ -115,10 +115,19 @@ class Contact extends CakeTestModel {
'required_one' => array('required' => array('rule' => array('notEmpty'))),
'imnotrequired' => array('required' => false, 'rule' => 'alphaNumeric', 'allowEmpty' => true),
'imalsonotrequired' => array(
'alpha' => array('rule' => 'alphaNumeric', 'allowEmpty' => true),
'between' => array('rule' => array('between', 5, 30)),
),
'imalsonotrequired2' => array(
'alpha' => array('rule' => 'alphaNumeric', 'allowEmpty' => true),
'between' => array('rule' => array('between', 5, 30), 'allowEmpty' => true),
),
'imnotrequiredeither' => array('required' => true, 'rule' => array('between', 5, 30), 'allowEmpty' => true),
'iamrequiredalways' => array(
'email' => array('rule' => 'email'),
'rule_on_create' => array('rule' => array('maxLength', 50), 'on' => 'create'),
'rule_on_update' => array('rule' => array('between', 1, 50), 'on' => 'update'),
),
);
/**
@ -2224,9 +2233,9 @@ class FormHelperTest extends CakeTestCase {
'type' => 'time',
'selected' => '18:15'
));
$this->assertRegExp('#<option value="06"[^>]*>6</option>#', $result);
$this->assertRegExp('#<option value="15"[^>]*>15</option>#', $result);
$this->assertRegExp('#<option value="pm"[^>]*>pm</option>#', $result);
$this->assertContains('<option value="06" selected="selected">6</option>', $result);
$this->assertContains('<option value="15" selected="selected">15</option>', $result);
$this->assertContains('<option value="pm" selected="selected">pm</option>', $result);
}
/**
@ -2235,6 +2244,24 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
public function testTimeSelectedWithInterval() {
$result = $this->Form->input('Model.start_time', array(
'type' => 'time',
'interval' => 15,
'selected' => array('hour' => '3', 'min' => '57', 'meridian' => 'pm')
));
$this->assertContains('<option value="04" selected="selected">4</option>', $result);
$this->assertContains('<option value="00" selected="selected">00</option>', $result);
$this->assertContains('<option value="pm" selected="selected">pm</option>', $result);
$result = $this->Form->input('Model.start_time', array(
'type' => 'time',
'interval' => 15,
'selected' => '2012-10-23 15:57:00'
));
$this->assertContains('<option value="04" selected="selected">4</option>', $result);
$this->assertContains('<option value="00" selected="selected">00</option>', $result);
$this->assertContains('<option value="pm" selected="selected">pm</option>', $result);
$result = $this->Form->input('Model.start_time', array(
'timeFormat' => 24,
'type' => 'time',
@ -2614,6 +2641,36 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
}
/**
* Test that magic input() selects are created for type=number
*
* @return void
*/
public function testInputMagicSelectForTypeNumber() {
$this->View->viewVars['balances'] = array(0 => 'nothing', 1 => 'some', 100 => 'a lot');
$this->Form->request->data = array('ValidateUser' => array('balance' => 1));
$result = $this->Form->input('ValidateUser.balance');
$expected = array(
'div' => array('class' => 'input select'),
'label' => array('for' => 'ValidateUserBalance'),
'Balance',
'/label',
'select' => array('name' => 'data[ValidateUser][balance]', 'id' => 'ValidateUserBalance'),
array('option' => array('value' => '0')),
'nothing',
'/option',
array('option' => array('value' => '1', 'selected' => 'selected')),
'some',
'/option',
array('option' => array('value' => '100')),
'a lot',
'/option',
'/select',
'/div'
);
$this->assertTags($result, $expected);
}
/**
* Test that magic input() selects can easily be converted into radio types without error.
*
@ -5621,26 +5678,10 @@ class FormHelperTest extends CakeTestCase {
$this->Form->request->data['Model']['field'] = '';
$result = $this->Form->hour('Model.field', true, array('value' => '23'));
$expected = array(
array('select' => array('name' => 'data[Model][field][hour]', 'id' => 'ModelFieldHour')),
array('option' => array('value' => '')),
'/option',
array('option' => array('value' => '00')),
'0',
'/option',
array('option' => array('value' => '01')),
'1',
'/option',
array('option' => array('value' => '02')),
'2',
'/option',
$hoursRegex,
array('option' => array('value' => '23', 'selected' => 'selected')),
'23',
'/option',
'/select',
);
$this->assertTags($result, $expected);
$this->assertContains('<option value="23" selected="selected">23</option>', $result);
$result = $this->Form->hour('Model.field', false, array('value' => '23'));
$this->assertContains('<option value="11" selected="selected">11</option>', $result);
$this->Form->request->data['Model']['field'] = '2006-10-10 00:12:32';
$result = $this->Form->hour('Model.field', true);
@ -7022,6 +7063,20 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$result = $this->Form->input('Contact.imalsonotrequired2');
$expected = array(
'div' => array('class' => 'input text'),
'label' => array('for' => 'ContactImalsonotrequired2'),
'Imalsonotrequired2',
'/label',
'input' => array(
'type' => 'text', 'name' => 'data[Contact][imalsonotrequired2]',
'id' => 'ContactImalsonotrequired2'
),
'/div'
);
$this->assertTags($result, $expected);
$result = $this->Form->input('Contact.imnotrequiredeither');
$expected = array(
'div' => array('class' => 'input text'),
@ -7035,6 +7090,20 @@ class FormHelperTest extends CakeTestCase {
'/div'
);
$this->assertTags($result, $expected);
$result = $this->Form->input('Contact.iamrequiredalways');
$expected = array(
'div' => array('class' => 'input text required'),
'label' => array('for' => 'ContactIamrequiredalways'),
'Iamrequiredalways',
'/label',
'input' => array(
'type' => 'text', 'name' => 'data[Contact][iamrequiredalways]',
'id' => 'ContactIamrequiredalways'
),
'/div'
);
$this->assertTags($result, $expected);
}
/**

View file

@ -904,7 +904,7 @@ class JsBaseEngineTest extends CakeTestCase {
public function testOptionMapping() {
$JsEngine = new OptionEngineHelper($this->View);
$result = $JsEngine->testMap();
$this->assertEquals(array(), $result);
$this->assertSame(array(), $result);
$result = $JsEngine->testMap(array('foo' => 'bar', 'baz' => 'sho'));
$this->assertEquals(array('foo' => 'bar', 'baz' => 'sho'), $result);

View file

@ -165,66 +165,92 @@ class TextHelperTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* Data provider for autoLinking
*/
public static function autoLinkProvider() {
return array(
array(
'This is a test text',
'This is a test text',
),
array(
'This is a test that includes (www.cakephp.org)',
'This is a test that includes (<a href="http://www.cakephp.org">www.cakephp.org</a>)',
),
array(
'This is a test that includes www.cakephp.org:8080',
'This is a test that includes <a href="http://www.cakephp.org:8080">www.cakephp.org:8080</a>',
),
array(
'This is a test that includes http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment',
'This is a test that includes <a href="http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>',
),
array(
'This is a test that includes www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment',
'This is a test that includes <a href="http://www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>',
),
array(
'This is a test that includes http://example.com/test.php?foo=bar text',
'This is a test that includes <a href="http://example.com/test.php?foo=bar">http://example.com/test.php?foo=bar</a> text',
),
array(
'This is a test that includes www.example.com/test.php?foo=bar text',
'This is a test that includes <a href="http://www.example.com/test.php?foo=bar">www.example.com/test.php?foo=bar</a> text',
),
array(
'Text with a partial www.cakephp.org URL',
'Text with a partial <a href="http://www.cakephp.org">www.cakephp.org</a> URL',
),
array(
'Text with a partial WWW.cakephp.org URL',
'Text with a partial <a href="http://WWW.cakephp.org">WWW.cakephp.org</a> URL',
),
array(
'Text with a partial WWW.cakephp.org &copy, URL',
'Text with a partial <a href="http://WWW.cakephp.org">WWW.cakephp.org</a> &amp;copy, URL',
),
array(
'Text with a url www.cot.ag/cuIb2Q and more',
'Text with a url <a href="http://www.cot.ag/cuIb2Q">www.cot.ag/cuIb2Q</a> and more',
),
array(
'Text with a url http://www.does--not--work.com and more',
'Text with a url <a href="http://www.does--not--work.com">http://www.does--not--work.com</a> and more',
),
array(
'Text with a url http://www.not--work.com and more',
'Text with a url <a href="http://www.not--work.com">http://www.not--work.com</a> and more',
),
);
}
/**
* testAutoLinkUrls method
*
* @dataProvider autoLinkProvider
* @return void
*/
public function testAutoLinkUrls($text, $expected) {
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
}
/**
* Test the options for autoLinkUrls
*
* @return void
*/
public function testAutoLinkUrls() {
$text = 'This is a test text';
$expected = 'This is a test text';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
$text = 'This is a test that includes (www.cakephp.org)';
$expected = 'This is a test that includes (<a href="http://www.cakephp.org">www.cakephp.org</a>)';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
$text = 'This is a test that includes http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment';
$expected = 'This is a test that includes <a href="http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
$text = 'This is a test that includes www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment';
$expected = 'This is a test that includes <a href="http://www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
$text = 'Text with a partial www.cakephp.org URL';
$expected = 'Text with a partial <a href="http://www.cakephp.org"\s*>www.cakephp.org</a> URL';
$result = $this->Text->autoLinkUrls($text);
$this->assertRegExp('#^' . $expected . '$#', $result);
public function testAutoLinkUrlsOptions() {
$text = 'Text with a partial www.cakephp.org URL';
$expected = 'Text with a partial <a href="http://www.cakephp.org" \s*class="link">www.cakephp.org</a> URL';
$result = $this->Text->autoLinkUrls($text, array('class' => 'link'));
$this->assertRegExp('#^' . $expected . '$#', $result);
$text = 'Text with a partial WWW.cakephp.org URL';
$expected = 'Text with a partial <a href="http://WWW.cakephp.org"\s*>WWW.cakephp.org</a> URL';
$result = $this->Text->autoLinkUrls($text);
$this->assertRegExp('#^' . $expected . '$#', $result);
$text = 'Text with a partial WWW.cakephp.org &copy; URL';
$expected = 'Text with a partial <a href="http://WWW.cakephp.org"\s*>WWW.cakephp.org</a> &copy; URL';
$result = $this->Text->autoLinkUrls($text, array('escape' => false));
$this->assertRegExp('#^' . $expected . '$#', $result);
$text = 'Text with a url www.cot.ag/cuIb2Q 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);
$this->assertEquals($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->assertEquals($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->assertEquals($expected, $result);
}
/**

View file

@ -132,11 +132,14 @@ class MediaViewTest extends CakeTestCase {
$this->MediaView->response->expects($this->at(1))
->method('header')
->with(array(
'Date' => gmdate('D, d M Y H:i:s', time()) . ' GMT',
'Expires' => '0',
'Cache-Control' => 'private, must-revalidate, post-check=0, pre-check=0',
'Pragma' => 'no-cache'
->with($this->logicalAnd(
$this->arrayHasKey('Date'),
$this->arrayHasKey('Expires'),
$this->arrayHasKey('Cache-Control'),
$this->arrayHasKey('Pragma'),
$this->contains('0'),
$this->contains('private, must-revalidate, post-check=0, pre-check=0'),
$this->contains('no-cache')
));
$this->MediaView->response->expects($this->once())

View file

@ -41,11 +41,11 @@ class FlagTreeFixture extends CakeTestFixture {
* @var array
*/
public $fields = array(
'id' => array('type' => 'integer','key' => 'primary'),
'name' => array('type' => 'string','null' => false),
'id' => array('type' => 'integer','key' => 'primary'),
'name' => array('type' => 'string','null' => false),
'parent_id' => 'integer',
'lft' => array('type' => 'integer','null' => false),
'rght' => array('type' => 'integer','null' => false),
'flag' => array('type' => 'integer','null' => false, 'length' => 1, 'default' => 0)
'lft' => array('type' => 'integer','null' => false),
'rght' => array('type' => 'integer','null' => false),
'flag' => array('type' => 'integer','null' => false, 'length' => 1, 'default' => 0)
);
}

View file

@ -16,5 +16,8 @@
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('AppController', 'Controller');
class TestPluginAppController extends AppController {
}

View file

@ -17,6 +17,8 @@
*/
require_once 'PHPUnit/TextUI/TestRunner.php';
App::uses('CakeFixtureManager', 'TestSuite/Fixture');
/**
* A custom test runner for Cake's use of PHPUnit.
*

View file

@ -75,7 +75,13 @@ class CakeTestFixture {
if (!empty($this->useDbConfig)) {
$connection = $this->useDbConfig;
if (strpos($connection, 'test') !== 0) {
throw new CakeException(__d('cake_dev', 'Invalid datasource %s for object %s', $connection, $this->name));
$message = __d(
'cake_dev',
'Invalid datasource name "%s" for "%s" fixture. Fixture datasource names must begin with "test".',
$connection,
$this->name
);
throw new CakeException($message);
}
}
$this->Schema = new CakeSchema(array('name' => 'TestSuite', 'connection' => $connection));

View file

@ -1,4 +1,5 @@
<?php
// @codingStandardsIgnoreFile
/**
* Short description for file.
*
@ -28,7 +29,7 @@
<?php if (!empty($plugins)): ?>
<li style="padding-top: 10px">
<span style="font-size: 18px">Plugins</span>
<?php foreach ($plugins as $plugin): ?>
<?php foreach ($plugins as $plugin) : ?>
<ul>
<li style="padding-top: 10px">
<span style="font-size: 18px"><?php echo $plugin; ?></span>

View file

@ -211,7 +211,10 @@ class CakeNumber {
* - `decimals` - Decimal separator symbol ie. '.'
* - `negative` - Symbol for negative numbers. If equal to '()',
* the number will be wrapped with ( and )
* - `escape` - Should the output be htmlentity escaped? Defaults to true
* - `escape` - Should the output be escaped for html special characters.
* The default value for this option is controlled by the currency settings.
* By default the EUR, and GBP contain HTML encoded symbols. If you require non HTML
* encoded symbols you will need to update the settings with the correct bytes.
*
* @param float $number
* @param string $currency Shortcut to default options. Valid values are

View file

@ -527,7 +527,7 @@ class Hash {
$element = $data[$key];
unset($data[$key]);
if (is_array($element)) {
if (is_array($element) && !empty($element)) {
if (!empty($data)) {
$stack[] = array($data, $path);
}

View file

@ -55,7 +55,7 @@ class Inflector {
'/$/' => 's',
),
'uninflected' => array(
'.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', 'people'
'.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', 'people', 'cookie'
),
'irregular' => array(
'atlas' => 'atlases',
@ -63,6 +63,7 @@ class Inflector {
'brother' => 'brothers',
'cafe' => 'cafes',
'child' => 'children',
'cookie' => 'cookies',
'corpus' => 'corpuses',
'cow' => 'cows',
'ganglion' => 'ganglions',
@ -176,7 +177,7 @@ class Inflector {
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A',
'/À|Á|Â|Ã|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/ç|ć|ĉ|ċ|č/' => 'c',

View file

@ -533,7 +533,7 @@ class Set {
*
* @param array $data Array from where to extract
* @param string|array $path As an array, or as a dot-separated string.
* @return array Extracted data
* @return array|null Extracted data or null when $data or $path are empty.
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::classicExtract
*/
public static function classicExtract($data, $path = null) {

View file

@ -17,4 +17,4 @@
// @license MIT License (http://www.opensource.org/licenses/mit-license.php)
// +--------------------------------------------------------------------------------------------+ //
////////////////////////////////////////////////////////////////////////////////////////////////////
2.2.2
2.2.3

View file

@ -247,13 +247,17 @@ class FormHelper extends AppHelper {
if (empty($validationRules) || count($validationRules) === 0) {
return false;
}
$isUpdate = $this->requestType === 'put';
foreach ($validationRules as $rule) {
$rule->isUpdate($this->requestType === 'put');
if ($rule->isEmptyAllowed()) {
return false;
$rule->isUpdate($isUpdate);
if ($rule->skip()) {
continue;
}
return !$rule->allowEmpty;
}
return true;
return false;
}
/**
@ -299,8 +303,9 @@ class FormHelper extends AppHelper {
* can be overridden when calling input()
* - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
*
* @param string $model The model object which the form is being defined for. Should
* @param string|array $model The model object which the form is being defined for. Should
* include the plugin name for plugin forms. e.g. `ContactManager.Contact`.
* If an array is passed and $options argument is empty, the array will be used as options.
* @param array $options An array of html attributes and options.
* @return string An formatted opening FORM tag.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
@ -993,7 +998,7 @@ class FormHelper extends AppHelper {
if (
(!isset($options['options']) && in_array($options['type'], $types)) ||
(isset($magicType) && $options['type'] == 'text')
(isset($magicType) && in_array($options['type'], array('text', 'number')))
) {
$varName = Inflector::variable(
Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
@ -1005,12 +1010,17 @@ class FormHelper extends AppHelper {
}
$options['options'] = $varOptions;
}
if ($options['type'] === 'select' && array_key_exists('step', $options)) {
unset($options['step']);
}
}
$autoLength = (
!array_key_exists('maxlength', $options) &&
isset($fieldDef['length']) &&
is_scalar($fieldDef['length'])
is_scalar($fieldDef['length']) &&
$options['type'] !== 'select'
);
if ($autoLength && $options['type'] == 'text') {
$options['maxlength'] = $fieldDef['length'];
@ -2041,6 +2051,11 @@ class FormHelper extends AppHelper {
} elseif ($attributes['value'] === false) {
$attributes['value'] = null;
}
if ($attributes['value'] > 12 && !$format24Hours) {
$attributes['value'] -= 12;
}
return $this->select(
$fieldName . ".hour",
$this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
@ -2184,50 +2199,12 @@ class FormHelper extends AppHelper {
}
if (!empty($attributes['value'])) {
if (is_array($attributes['value'])) {
extract($attributes['value']);
} else {
if (is_numeric($attributes['value'])) {
$attributes['value'] = strftime('%Y-%m-%d %H:%M:%S', $attributes['value']);
}
$meridian = 'am';
$pos = strpos($attributes['value'], '-');
if ($pos !== false) {
$date = explode('-', $attributes['value']);
$days = explode(' ', $date[2]);
$day = $days[0];
$month = $date[1];
$year = $date[0];
} else {
$days[1] = $attributes['value'];
}
if (!empty($timeFormat)) {
$time = explode(':', $days[1]);
if (($time[0] > 12) && $timeFormat == '12') {
$time[0] = $time[0] - 12;
$meridian = 'pm';
} elseif ($time[0] == '12' && $timeFormat == '12') {
$meridian = 'pm';
} elseif ($time[0] == '00' && $timeFormat == '12') {
$time[0] = 12;
} elseif ($time[0] >= 12) {
$meridian = 'pm';
}
if ($time[0] == 0 && $timeFormat == '12') {
$time[0] = 12;
}
$hour = $min = null;
if (isset($time[1])) {
$hour = $time[0];
$min = $time[1];
}
}
}
list($year, $month, $day, $hour, $min, $meridian) = $this->_getDateTimeValue(
$attributes['value'],
$timeFormat
);
}
$elements = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
$defaults = array(
'minYear' => null, 'maxYear' => null, 'separator' => '-',
'interval' => 1, 'monthNames' => true
@ -2258,42 +2235,42 @@ class FormHelper extends AppHelper {
list($year, $month, $day, $hour, $min, $meridian) = $newTime;
}
if (isset($attributes['id'])) {
if (is_string($attributes['id'])) {
// build out an array version
foreach ($elements as $element) {
$selectAttrName = 'select' . $element . 'Attr';
${$selectAttrName} = $attributes;
${$selectAttrName}['id'] = $attributes['id'] . $element;
}
} elseif (is_array($attributes['id'])) {
// check for missing ones and build selectAttr for each element
$attributes['id'] += array(
'month' => '', 'year' => '', 'day' => '',
'hour' => '', 'minute' => '', 'meridian' => ''
);
foreach ($elements as $element) {
$selectAttrName = 'select' . $element . 'Attr';
${$selectAttrName} = $attributes;
${$selectAttrName}['id'] = $attributes['id'][strtolower($element)];
}
$keys = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
$attrs = array_fill_keys($keys, $attributes);
$hasId = isset($attributes['id']);
if ($hasId && is_array($attributes['id'])) {
// check for missing ones and build selectAttr for each element
$attributes['id'] += array(
'month' => '',
'year' => '',
'day' => '',
'hour' => '',
'minute' => '',
'meridian' => ''
);
foreach ($keys as $key) {
$attrs[$key]['id'] = $attributes['id'][strtolower($key)];
}
} else {
// build the selectAttrName with empty id's to pass
foreach ($elements as $element) {
$selectAttrName = 'select' . $element . 'Attr';
${$selectAttrName} = $attributes;
}
if ($hasId && is_string($attributes['id'])) {
// build out an array version
foreach ($keys as $key) {
$attrs[$key]['id'] = $attributes['id'] . $key;
}
}
if (is_array($attributes['empty'])) {
$attributes['empty'] += array(
'month' => true, 'year' => true, 'day' => true,
'hour' => true, 'minute' => true, 'meridian' => true
'month' => true,
'year' => true,
'day' => true,
'hour' => true,
'minute' => true,
'meridian' => true
);
foreach ($elements as $element) {
$selectAttrName = 'select' . $element . 'Attr';
${$selectAttrName}['empty'] = $attributes['empty'][strtolower($element)];
foreach ($keys as $key) {
$attrs[$key]['empty'] = $attributes['empty'][strtolower($key)];
}
}
@ -2301,47 +2278,98 @@ class FormHelper extends AppHelper {
foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
switch ($char) {
case 'Y':
$selectYearAttr['value'] = $year;
$attrs['Year']['value'] = $year;
$selects[] = $this->year(
$fieldName, $minYear, $maxYear, $selectYearAttr
$fieldName, $minYear, $maxYear, $attrs['Year']
);
break;
case 'M':
$selectMonthAttr['value'] = $month;
$selectMonthAttr['monthNames'] = $monthNames;
$selects[] = $this->month($fieldName, $selectMonthAttr);
$attrs['Month']['value'] = $month;
$attrs['Month']['monthNames'] = $monthNames;
$selects[] = $this->month($fieldName, $attrs['Month']);
break;
case 'D':
$selectDayAttr['value'] = $day;
$selects[] = $this->day($fieldName, $selectDayAttr);
$attrs['Day']['value'] = $day;
$selects[] = $this->day($fieldName, $attrs['Day']);
break;
}
}
$opt = implode($separator, $selects);
$selectMinuteAttr['interval'] = $interval;
$attrs['Minute']['interval'] = $interval;
switch ($timeFormat) {
case '24':
$selectHourAttr['value'] = $hour;
$selectMinuteAttr['value'] = $min;
$opt .= $this->hour($fieldName, true, $selectHourAttr) . ':' .
$this->minute($fieldName, $selectMinuteAttr);
$attrs['Hour']['value'] = $hour;
$attrs['Minute']['value'] = $min;
$opt .= $this->hour($fieldName, true, $attrs['Hour']) . ':' .
$this->minute($fieldName, $attrs['Minute']);
break;
case '12':
$selectHourAttr['value'] = $hour;
$selectMinuteAttr['value'] = $min;
$selectMeridianAttr['value'] = $meridian;
$opt .= $this->hour($fieldName, false, $selectHourAttr) . ':' .
$this->minute($fieldName, $selectMinuteAttr) . ' ' .
$this->meridian($fieldName, $selectMeridianAttr);
break;
default:
$opt .= '';
$attrs['Hour']['value'] = $hour;
$attrs['Minute']['value'] = $min;
$attrs['Meridian']['value'] = $meridian;
$opt .= $this->hour($fieldName, false, $attrs['Hour']) . ':' .
$this->minute($fieldName, $attrs['Minute']) . ' ' .
$this->meridian($fieldName, $attrs['Meridian']);
break;
}
return $opt;
}
/**
* Parse the value for a datetime selected value
*
* @param string|array $value The selected value.
* @param integer $timeFormat The time format
* @return array Array of selected value.
*/
protected function _getDateTimeValue($value, $timeFormat) {
$year = $month = $day = $hour = $min = $meridian = null;
if (is_array($value)) {
extract($value);
if ($meridian === 'pm') {
$hour += 12;
}
return array($year, $month, $day, $hour, $min, $meridian);
}
if (is_numeric($value)) {
$value = strftime('%Y-%m-%d %H:%M:%S', $value);
}
$meridian = 'am';
$pos = strpos($value, '-');
if ($pos !== false) {
$date = explode('-', $value);
$days = explode(' ', $date[2]);
$day = $days[0];
$month = $date[1];
$year = $date[0];
} else {
$days[1] = $value;
}
if (!empty($timeFormat)) {
$time = explode(':', $days[1]);
if ($time[0] >= '12' && $timeFormat == '12') {
$meridian = 'pm';
} elseif ($time[0] == '00' && $timeFormat == '12') {
$time[0] = 12;
} elseif ($time[0] >= 12) {
$meridian = 'pm';
}
if ($time[0] == 0 && $timeFormat == '12') {
$time[0] = 12;
}
$hour = $min = null;
if (isset($time[1])) {
$hour = $time[0];
$min = $time[1];
}
}
return array($year, $month, $day, $hour, $min, $meridian);
}
/**
* Gets the input field name for the current tag
*

View file

@ -101,7 +101,7 @@ class TextHelper extends AppHelper {
$this->_placeholders = array();
$options += array('escape' => true);
$pattern = '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[^\s<>()]+\.[a-z]+(?:\/[^\s]+)?)#i';
$pattern = '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[a-z0-9.\-:]+(?:/[^\s]*)?)#i';
$text = preg_replace_callback(
$pattern,
array(&$this, '_insertPlaceHolder'),

View file

@ -145,6 +145,12 @@ App::$bootstrapping = true;
Configure::bootstrap(isset($boot) ? $boot : true);
if (function_exists('mb_internal_encoding')) {
$encoding = Configure::read('App.encoding');
if (!empty($encoding)) {
mb_internal_encoding($encoding);
}
}
/**
* Full url prefix