Merge branch '2.0-request' into 2.0

Still tons of tests failing
Conflicts:
	cake/dispatcher.php
	cake/libs/controller/components/auth.php
	cake/libs/controller/components/request_handler.php
	cake/libs/controller/components/security.php
	cake/libs/controller/controller.php
	cake/libs/router.php
	cake/libs/view/helper.php
	cake/libs/view/helpers/html.php
	cake/libs/view/view.php
	cake/tests/cases/dispatcher.test.php
	cake/tests/cases/libs/controller/components/auth.test.php
	cake/tests/cases/libs/controller/components/request_handler.test.php
	cake/tests/cases/libs/controller/components/security.test.php
	cake/tests/cases/libs/controller/controller.test.php
	cake/tests/cases/libs/router.test.php
	cake/tests/cases/libs/view/helper.test.php
	cake/tests/cases/libs/view/helpers/cache.test.php
	cake/tests/cases/libs/view/helpers/form.test.php
	cake/tests/cases/libs/view/helpers/html.test.php
	cake/tests/cases/libs/view/helpers/js.test.php
	cake/tests/cases/libs/view/helpers/paginator.test.php
This commit is contained in:
José Lorenzo Rodríguez 2010-08-27 23:31:41 -04:30
commit f63b093d24
41 changed files with 5894 additions and 3946 deletions

View file

@ -24,7 +24,7 @@
/**
* List of helpers to include
*/
App::import('Core', 'Router');
App::import('Core', array('Router', 'CakeRequest', 'CakeResponse'));
App::import('Controller', 'Controller', false);
/**
@ -35,7 +35,7 @@ App::import('Controller', 'Controller', false);
* @package cake
* @subpackage cake.cake
*/
class Dispatcher extends Object {
class Dispatcher {
/**
* Base URL
@ -69,6 +69,22 @@ class Dispatcher extends Object {
*/
public $params = null;
/**
* The request object
*
* @var CakeRequest
* @access public
*/
public $request = null;
/**
* The response object
*
* @var CakeResponse
* @access public
*/
public $response = null;
/**
* Constructor.
*/
@ -89,85 +105,66 @@ class Dispatcher extends Object {
* the form of Missing Controllers information. It does the same with Actions (methods of Controllers are called
* Actions).
*
* @param string $url URL information to work on
* @param mixed $url Either a string url or a CakeRequest object information to work on. If $url is a string
* It will be used to create the request object.
* @param array $additionalParams Settings array ("bare", "return") which is melded with the GET and POST params
* @return boolean Success
*/
public function dispatch($url = null, $additionalParams = array()) {
if ($this->base === false) {
$this->base = $this->baseUrl();
}
if (is_array($url)) {
$url = $this->_extractParams($url, $additionalParams);
} else {
if ($url) {
$_GET['url'] = $url;
}
$url = $this->getUrl();
$this->params = array_merge($this->parseParams($url), $additionalParams);
}
$this->here = $this->base . '/' . $url;
if ($url instanceof CakeRequest) {
$request = $url;
} else {
$request = new CakeRequest($url);
}
$this->here = $request->here;
if ($this->asset($url) || $this->cached($url)) {
if ($this->asset($request->url) || $this->cached($request->url)) {
return;
}
$request = $this->parseParams($request, $additionalParams);
$this->request = $request;
$controller = $this->_getController();
if (!is_object($controller)) {
Router::setRequestInfo(array($this->params, array('base' => $this->base, 'webroot' => $this->webroot)));
Router::setRequestInfo($request);
return $this->cakeError('missingController', array(array(
'className' => Inflector::camelize($this->params['controller']) . 'Controller',
'webroot' => $this->webroot,
'className' => Inflector::camelize($request->params['controller']) . 'Controller',
'webroot' => $request->webroot,
'url' => $url,
'base' => $this->base
'base' => $request->base
)));
}
$privateAction = $this->params['action'][0] === '_';
$privateAction = $request->params['action'][0] === '_';
$prefixes = Router::prefixes();
if (!empty($prefixes)) {
if (isset($this->params['prefix'])) {
$this->params['action'] = $this->params['prefix'] . '_' . $this->params['action'];
} elseif (strpos($this->params['action'], '_') > 0) {
list($prefix, $action) = explode('_', $this->params['action']);
if (isset($request->params['prefix'])) {
$request->params['action'] = $request->params['prefix'] . '_' . $request->params['action'];
} elseif (strpos($request->params['action'], '_') > 0) {
list($prefix, $action) = explode('_', $request->params['action']);
$privateAction = in_array($prefix, $prefixes);
}
}
Router::setRequestInfo(array(
$this->params, array('base' => $this->base, 'here' => $this->here, 'webroot' => $this->webroot)
));
Router::setRequestInfo($request);
if ($privateAction) {
return $this->cakeError('privateAction', array(array(
'className' => Inflector::camelize($this->params['controller'] . "Controller"),
'action' => $this->params['action'],
'webroot' => $this->webroot,
'url' => $url,
'base' => $this->base
'className' => Inflector::camelize($request->params['controller'] . "Controller"),
'action' => $request->params['action'],
'webroot' => $request->webroot,
'url' => $request->url,
'base' => $request->base
)));
}
$controller->base = $this->base;
$controller->here = $this->here;
$controller->webroot = $this->webroot;
$controller->plugin = isset($this->params['plugin']) ? $this->params['plugin'] : null;
$controller->params =& $this->params;
$controller->action =& $this->params['action'];
$controller->passedArgs = array_merge($this->params['pass'], $this->params['named']);
if (!empty($this->params['data'])) {
$controller->data =& $this->params['data'];
} else {
$controller->data = null;
}
if (isset($this->params['return']) && $this->params['return'] == 1) {
$controller->autoRender = false;
}
if (!empty($this->params['bare'])) {
$controller->autoLayout = false;
}
return $this->_invoke($controller, $this->params);
return $this->_invoke($controller, $request);
}
/**
@ -180,38 +177,39 @@ class Dispatcher extends Object {
* @param boolean $missingAction Set to true if missing action should be rendered, false otherwise
* @return string Output as sent by controller
*/
protected function _invoke(&$controller, $params) {
protected function _invoke(&$controller, $request) {
$controller->constructClasses();
$controller->startupProcess();
$methods = array_flip($controller->methods);
if (!isset($methods[$params['action']])) {
if (!isset($methods[$request->params['action']])) {
if ($controller->scaffold !== false) {
App::import('Controller', 'Scaffold', false);
return new Scaffold($controller, $params);
return new Scaffold($controller, $request);
}
return $this->cakeError('missingAction', array(array(
'className' => Inflector::camelize($params['controller']."Controller"),
'action' => $params['action'],
'webroot' => $this->webroot,
'url' => $this->here,
'base' => $this->base
'className' => Inflector::camelize($request->params['controller']."Controller"),
'action' => $request->params['action'],
'webroot' => $request->webroot,
'url' => $request->here,
'base' => $request->base
)));
}
$output = call_user_func_array(array(&$controller, $params['action']), $params['pass']);
$output =& call_user_func_array(array(&$controller, $request->params['action']), $request->params['pass']);
if ($controller->autoRender) {
$controller->output = $controller->render();
} elseif (empty($controller->output)) {
$controller->output = $output;
$controller->render();
} elseif ($this->response->body() === null) {
$this->response->body($output);
}
$controller->shutdownProcess();
if (isset($params['return'])) {
return $controller->output;
if (isset($request->params['return'])) {
return $this->response->body();
}
echo($controller->output);
$this->response->send();
}
/**
@ -234,135 +232,21 @@ class Dispatcher extends Object {
/**
* Returns array of GET and POST parameters. GET parameters are taken from given URL.
*
* @param string $fromUrl URL to mine for parameter information.
* @param CakeRequest $fromUrl CakeRequest object to mine for parameter information.
* @return array Parameters found in POST and GET.
*/
public function parseParams($fromUrl) {
$params = array();
if (isset($_POST)) {
$params['form'] = $_POST;
if (ini_get('magic_quotes_gpc') === '1') {
$params['form'] = stripslashes_deep($params['form']);
}
if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$params['form']['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
}
if (isset($params['form']['_method'])) {
if (!empty($_SERVER)) {
$_SERVER['REQUEST_METHOD'] = $params['form']['_method'];
} else {
$_ENV['REQUEST_METHOD'] = $params['form']['_method'];
}
unset($params['form']['_method']);
}
}
public function parseParams(CakeRequest $request, $additionalParams = array()) {
$namedExpressions = Router::getNamedExpressions();
extract($namedExpressions);
include CONFIGS . 'routes.php';
$params = array_merge(Router::parse($fromUrl), $params);
if (strlen($params['action']) === 0) {
$params['action'] = 'index';
$params = Router::parse($request->url);
$request->addParams($params);
if (!empty($additionalParams)) {
$request->addParams($additionalParams);
}
if (isset($params['form']['data'])) {
$params['data'] = $params['form']['data'];
unset($params['form']['data']);
}
if (isset($_GET)) {
if (ini_get('magic_quotes_gpc') === '1') {
$url = stripslashes_deep($_GET);
} else {
$url = $_GET;
}
if (isset($params['url'])) {
$params['url'] = array_merge($params['url'], $url);
} else {
$params['url'] = $url;
}
}
foreach ($_FILES as $name => $data) {
if ($name != 'data') {
$params['form'][$name] = $data;
}
}
if (isset($_FILES['data'])) {
foreach ($_FILES['data'] as $key => $data) {
foreach ($data as $model => $fields) {
if (is_array($fields)) {
foreach ($fields as $field => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$params['data'][$model][$field][$k][$key] = $v;
}
} else {
$params['data'][$model][$field][$key] = $value;
}
}
} else {
$params['data'][$model][$key] = $fields;
}
}
}
}
return $params;
}
/**
* Returns a base URL and sets the proper webroot
*
* @return string Base URL
*/
public function baseUrl() {
$dir = $webroot = null;
$config = Configure::read('App');
extract($config);
if (!$base) {
$base = $this->base;
}
if ($base !== false) {
$this->webroot = $base . '/';
return $this->base = $base;
}
if (!$baseUrl) {
$replace = array('<', '>', '*', '\'', '"');
$base = str_replace($replace, '', dirname(env('PHP_SELF')));
if ($webroot === 'webroot' && $webroot === basename($base)) {
$base = dirname($base);
}
if ($dir === 'app' && $dir === basename($base)) {
$base = dirname($base);
}
if ($base === DS || $base === '.') {
$base = '';
}
$this->webroot = $base .'/';
return $base;
}
$file = '/' . basename($baseUrl);
$base = dirname($baseUrl);
if ($base === DS || $base === '.') {
$base = '';
}
$this->webroot = $base .'/';
if (!empty($base)) {
if (strpos($this->webroot, $dir) === false) {
$this->webroot .= $dir . '/' ;
}
if (strpos($this->webroot, $webroot) === false) {
$this->webroot .= $webroot . '/';
}
}
return $base . $file;
return $request;
}
/**
@ -373,13 +257,18 @@ class Dispatcher extends Object {
*/
protected function &_getController() {
$controller = false;
$ctrlClass = $this->__loadController($this->params);
$ctrlClass = $this->__loadController($this->request);
if (!$ctrlClass) {
return $controller;
}
if (!$this->response) {
$this->response = new CakeResponse(array(
'charset' => Configure::read('App.encoding')
));
}
$ctrlClass .= 'Controller';
if (class_exists($ctrlClass)) {
$controller =& new $ctrlClass();
$controller = new $ctrlClass($this->request, $this->response);
}
return $controller;
}
@ -391,14 +280,14 @@ class Dispatcher extends Object {
* @return string|bool Name of controller class name
* @access private
*/
function __loadController($params) {
function __loadController($request) {
$pluginName = $pluginPath = $controller = null;
if (!empty($params['plugin'])) {
$pluginName = $controller = Inflector::camelize($params['plugin']);
if (!empty($request->params['plugin'])) {
$pluginName = $controller = Inflector::camelize($request->params['plugin']);
$pluginPath = $pluginName . '.';
}
if (!empty($params['controller'])) {
$controller = Inflector::camelize($params['controller']);
if (!empty($request->params['controller'])) {
$controller = Inflector::camelize($request->params['controller']);
}
if ($pluginPath . $controller) {
if (App::import('Controller', $pluginPath . $controller)) {
@ -408,101 +297,6 @@ class Dispatcher extends Object {
return false;
}
/**
* Returns the REQUEST_URI from the server environment, or, failing that,
* constructs a new one, using the PHP_SELF constant and other variables.
*
* @return string URI
*/
public function uri() {
foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
if ($uri = env($var)) {
if ($var == 'argv') {
$uri = $uri[0];
}
break;
}
}
$base = preg_replace('/^\//', '', '' . Configure::read('App.baseUrl'));
if ($base) {
$uri = preg_replace('/^(?:\/)?(?:' . preg_quote($base, '/') . ')?(?:url=)?/', '', $uri);
}
if (PHP_SAPI == 'isapi') {
$uri = preg_replace('/^(?:\/)?(?:\/)?(?:\?)?(?:url=)?/', '', $uri);
}
if (!empty($uri)) {
if (key($_GET) && strpos(key($_GET), '?') !== false) {
unset($_GET[key($_GET)]);
}
$uri = explode('?', $uri, 2);
if (isset($uri[1])) {
parse_str($uri[1], $_GET);
}
$uri = $uri[0];
} else {
$uri = env('QUERY_STRING');
}
if (is_string($uri) && strpos($uri, 'index.php') !== false) {
list(, $uri) = explode('index.php', $uri, 2);
}
if (empty($uri) || $uri == '/' || $uri == '//') {
return '';
}
return str_replace('//', '/', '/' . $uri);
}
/**
* Returns and sets the $_GET[url] derived from the REQUEST_URI
*
* @param string $uri Request URI
* @param string $base Base path
* @return string URL
*/
public function getUrl($uri = null, $base = null) {
if (empty($_GET['url'])) {
if ($uri == null) {
$uri = $this->uri();
}
if ($base == null) {
$base = $this->base;
}
$url = null;
$tmpUri = preg_replace('/^(?:\?)?(?:\/)?/', '', $uri);
$baseDir = preg_replace('/^\//', '', dirname($base)) . '/';
if ($tmpUri === '/' || $tmpUri == $baseDir || $tmpUri == $base) {
$url = $_GET['url'] = '/';
} else {
if ($base && strpos($uri, $base) !== false) {
$elements = explode($base, $uri);
} elseif (preg_match('/^[\/\?\/|\/\?|\?\/]/', $uri)) {
$elements = array(1 => preg_replace('/^[\/\?\/|\/\?|\?\/]/', '', $uri));
} else {
$elements = array();
}
if (!empty($elements[1])) {
$_GET['url'] = $elements[1];
$url = $elements[1];
} else {
$url = $_GET['url'] = '/';
}
if (strpos($url, '/') === 0 && $url != '/') {
$url = $_GET['url'] = substr($url, 1);
}
}
} else {
$url = $_GET['url'];
}
if ($url{0} == '/') {
$url = substr($url, 1);
}
return $url;
}
/**
* Outputs cached dispatch view cache
*
@ -527,7 +321,7 @@ class Dispatcher extends Object {
App::import('View', 'View', false);
}
$controller = null;
$view =& new View($controller);
$view = new View($controller);
$return = $view->renderCache($filename, microtime(true));
if (!$return) {
ClassRegistry::removeObject('view');
@ -557,9 +351,12 @@ class Dispatcher extends Object {
strpos($url, 'cjs/') === 0 ||
preg_match('#^/((theme/[^/]+)/cjs/)|(([^/]+)(?<!js)/cjs)/#i', $url)
);
if (!$this->response) {
$this->response = new CakeResponse();
}
if (($isCss && empty($filters['css'])) || ($isJs && empty($filters['js']))) {
$this->header('HTTP/1.1 404 Not Found');
$this->response->statusCode(404);
$this->response->send();
return $this->_stop();
} elseif ($isCss) {
include WWW_ROOT . DS . $filters['css'];
@ -606,38 +403,22 @@ class Dispatcher extends Object {
* @return void
*/
protected function _deliverAsset($assetFile, $ext) {
$ob = @ini_get("zlib.output_compression") !== '1' && extension_loaded("zlib") && (strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
$compressionEnabled = $ob && Configure::read('Asset.compress');
if ($compressionEnabled) {
ob_start();
ob_start('ob_gzhandler');
}
App::import('View', 'Media', false);
$controller = null;
$Media = new MediaView($controller);
if (isset($Media->mimeType[$ext])) {
$contentType = $Media->mimeType[$ext];
} else {
ob_start();
$compressionEnabled = Configure::read('Asset.compress') && $this->response->compress();
if ($this->response->type($ext) == $ext) {
$contentType = 'application/octet-stream';
$agent = env('HTTP_USER_AGENT');
if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
$contentType = 'application/octetstream';
}
$this->response->type($contentType);
}
$this->header("Date: " . date("D, j M Y G:i:s ", filemtime($assetFile)) . 'GMT');
$this->header('Content-type: ' . $contentType);
$this->header("Expires: " . gmdate("D, j M Y H:i:s", time() + DAY) . " GMT");
$this->header("Cache-Control: cache");
$this->header("Pragma: cache");
$this->response->cache(filemtime($assetFile));
$this->response->send();
ob_clean();
if ($ext === 'css' || $ext === 'js') {
include($assetFile);
} else {
if ($compressionEnabled) {
ob_clean();
}
readfile($assetFile);
}
@ -645,15 +426,4 @@ class Dispatcher extends Object {
ob_end_flush();
}
}
/**
* Sends the specified headers to the client
*
* @param string $header header to send
* @todo Refactor this to use a response object or similar
* @return void
*/
public function header($header) {
header($header);
}
}

626
cake/libs/cake_request.php Normal file
View file

@ -0,0 +1,626 @@
<?php
/**
* A class that helps wrap Request information and particulars about a single request.
* Provides methods commonly used to introspect on the request headers and request body.
*
* Has both an Array and Object interface. You can access framework parameters using indexes
*
* `$request['controller']` or `$request->controller`.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Set');
class CakeRequest implements ArrayAccess {
/**
* Array of parameters parsed from the url.
*
* @var array
*/
public $params = array();
/**
* Array of POST data. Will contain form data as well as uploaded files.
* Will only contain data from inputs that start with 'data'. So
* `<input name="some_input" />` will not end up in data. However,
* `<input name="data[something]" />`
*
* @var array
*/
public $data = array();
/**
* Array of querystring arguments
*
* @var array
*/
public $query = array();
/**
* The url string used for the request.
*
* @var string
*/
public $url;
/**
* Base url path.
*
* @var string
*/
public $base = false;
/**
* webroot path segment for the request.
*
* @var string
*/
public $webroot = '/';
/**
* The full address to the current request
*
* @var string
*/
public $here = null;
/**
* The built in detectors used with `is()` can be modified with `addDetector()`.
*
* There are several ways to specify a detector, see CakeRequest::addDetector() for the
* various formats and ways to define detectors.
*
* @var array
*/
protected $_detectors = array(
'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
'ssl' => array('env' => 'HTTPS', 'value' => 1),
'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
'Android', 'AvantGo', 'BlackBerry', 'DoCoMo', 'iPod', 'iPhone',
'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'PalmOS', 'PalmSource',
'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
'webOS', 'Windows CE', 'Xiino'
))
);
/**
* Constructor
*
* @param string $url Url string to use
* @param boolean $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
* @return void
*/
public function __construct($url = null, $parseEnvironment = true) {
$this->base = $this->_base();
if (empty($url)) {
$url = $this->_url();
}
if ($url[0] == '/') {
$url = substr($url, 1);
}
$this->url = $url;
if ($parseEnvironment) {
$this->_processPost();
$this->_processGet();
$this->_processFiles();
}
$this->here = $this->base . '/' . $this->url;
}
/**
* process the post data and set what is there into the object.
*
* @return void
*/
protected function _processPost() {
$this->params['form'] = $_POST;
if (ini_get('magic_quotes_gpc') === '1') {
$this->params['form'] = stripslashes_deep($this->params['form']);
}
if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$this->params['form']['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
}
if (isset($this->params['form']['_method'])) {
if (!empty($_SERVER)) {
$_SERVER['REQUEST_METHOD'] = $this->params['form']['_method'];
} else {
$_ENV['REQUEST_METHOD'] = $this->params['form']['_method'];
}
unset($this->params['form']['_method']);
}
if (isset($this->params['form']['data'])) {
$this->data = $this->params['form']['data'];
unset($this->params['form']['data']);
}
}
/**
* Process the GET parameters and move things into the object.
*
* @return void
*/
protected function _processGet() {
if (ini_get('magic_quotes_gpc') === '1') {
$query = stripslashes_deep($_GET);
} else {
$query = $_GET;
}
if (strpos($this->url, '?') !== false) {
list(, $querystr) = explode('?', $this->url);
parse_str($querystr, $queryArgs);
$query += $queryArgs;
}
if (isset($this->params['url'])) {
$query = array_merge($this->params['url'], $query);
}
$query['url'] = $this->url;
$this->query = $query;
}
/**
* Returns the REQUEST_URI from the server environment, or, failing that,
* constructs a new one, using the PHP_SELF constant and other variables.
*
* @return string URI
*/
protected function _uri() {
foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
if ($uri = env($var)) {
if ($var == 'argv') {
$uri = $uri[0];
}
break;
}
}
$base = trim(Configure::read('App.baseUrl'), '/');
if ($base) {
$uri = preg_replace('/^(?:\/)?(?:' . preg_quote($base, '/') . ')?(?:url=)?/', '', $uri);
}
if (PHP_SAPI == 'isapi') {
$uri = preg_replace('/^(?:\/)?(?:\/)?(?:\?)?(?:url=)?/', '', $uri);
}
if (!empty($uri)) {
if (key($_GET) && strpos(key($_GET), '?') !== false) {
unset($_GET[key($_GET)]);
}
$uri = explode('?', $uri, 2);
if (isset($uri[1])) {
parse_str($uri[1], $_GET);
}
$uri = $uri[0];
} else {
$uri = env('QUERY_STRING');
}
if (is_string($uri) && strpos($uri, 'index.php') !== false) {
list(, $uri) = explode('index.php', $uri, 2);
}
if (empty($uri) || $uri == '/' || $uri == '//') {
return '';
}
return str_replace('//', '/', '/' . $uri);
}
/**
* Returns and sets the $_GET[url] derived from the REQUEST_URI
*
* @return string URL
*/
protected function _url() {
if (empty($_GET['url'])) {
$uri = $this->_uri();
$base = $this->base;
$url = null;
$tmpUri = preg_replace('/^(?:\?)?(?:\/)?/', '', $uri);
$baseDir = trim(dirname($base) . '/', '/');
if ($tmpUri === '/' || $tmpUri == $baseDir || $tmpUri == $base) {
$url = '/';
} else {
$elements = array();
if ($base && strpos($uri, $base) !== false) {
$elements = explode($base, $uri);
} elseif (preg_match('/^[\/\?\/|\/\?|\?\/]/', $uri)) {
$elements = array(1 => preg_replace('/^[\/\?\/|\/\?|\?\/]/', '', $uri));
}
if (!empty($elements[1])) {
$url = $elements[1];
} else {
$url = '/';
}
}
} else {
$url = $_GET['url'];
}
return $url;
}
/**
* Returns a base URL and sets the proper webroot
*
* @return string Base URL
*/
protected function _base() {
$dir = $webroot = null;
$config = Configure::read('App');
extract($config);
if (!$base) {
$base = $this->base;
}
if ($base !== false) {
$this->webroot = $base . '/';
return $base;
}
if (!$baseUrl) {
$replace = array('<', '>', '*', '\'', '"');
$base = str_replace($replace, '', dirname(env('PHP_SELF')));
if ($webroot === 'webroot' && $webroot === basename($base)) {
$base = dirname($base);
}
if ($dir === 'app' && $dir === basename($base)) {
$base = dirname($base);
}
if ($base === DS || $base === '.') {
$base = '';
}
$this->webroot = $base .'/';
return $base;
}
$file = '/' . basename($baseUrl);
$base = dirname($baseUrl);
if ($base === DS || $base === '.') {
$base = '';
}
$this->webroot = $base .'/';
if (!empty($base)) {
if (strpos($this->webroot, $dir) === false) {
$this->webroot .= $dir . '/' ;
}
if (strpos($this->webroot, $webroot) === false) {
$this->webroot .= $webroot . '/';
}
}
return $base . $file;
}
/**
* Process $_FILES and move things into the object.
*
* @return void
*/
protected function _processFiles() {
if (isset($_FILES) && is_array($_FILES)) {
foreach ($_FILES as $name => $data) {
if ($name != 'data') {
$this->params['form'][$name] = $data;
}
}
}
if (isset($_FILES['data'])) {
foreach ($_FILES['data'] as $key => $data) {
foreach ($data as $model => $fields) {
if (is_array($fields)) {
foreach ($fields as $field => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$this->data[$model][$field][$k][$key] = $v;
}
} else {
$this->data[$model][$field][$key] = $value;
}
}
} else {
$this->data[$model][$key] = $fields;
}
}
}
}
}
/**
* Get the IP the client is using, or says they are using.
*
* @param boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
* header. Setting $safe = false will will also look at HTTP_X_FORWARDED_FOR
* @return void
*/
public function clientIp($safe = true) {
if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
} else {
if (env('HTTP_CLIENT_IP') != null) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
$ipaddr = env('REMOTE_ADDR');
}
}
if (env('HTTP_CLIENTADDRESS') != null) {
$tmpipaddr = env('HTTP_CLIENTADDRESS');
if (!empty($tmpipaddr)) {
$ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
}
}
return trim($ipaddr);
}
/**
* Returns the referer that referred this request.
*
* @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
* @return string The referring address for this request.
*/
public function referer($local = false) {
$ref = env('HTTP_REFERER');
$forwarded = env('HTTP_X_FORWARDED_HOST');
if ($forwarded) {
$ref = $forwarded;
}
$base = '';
if (defined('FULL_BASE_URL')) {
$base = FULL_BASE_URL . $this->webroot;
}
if (!empty($ref) && !empty($base)) {
if ($local && strpos($ref, $base) === 0) {
$ref = substr($ref, strlen($base));
if ($ref[0] != '/') {
$ref = '/' . $ref;
}
return $ref;
} elseif (!$local) {
return $ref;
}
}
return '/';
}
/**
* Missing method handler, handles wrapping older style isAjax() type methods
*
* @param string $name The method called
* @param array $params Array of parameters for the method call
* @return mixed
* @throws BadMethodCallException when an invalid method is called.
*/
public function __call($name, $params) {
if (strpos($name, 'is') === 0) {
$type = strtolower(substr($name, 2));
return $this->is($type);
}
throw new BadMethodCallException(sprintf('Method %s does not exist', $name));
}
/**
* Magic get method allows access to parsed routing parameters directly on the object.
*
* @param string $name The property being accessed.
* @return mixed Either the value of the parameter or null.
*/
public function __get($name) {
if (isset($this->params[$name])) {
return $this->params[$name];
}
return null;
}
/**
* Check whether or not a Request is a certain type. Uses the built in detection rules
* as well as additional rules defined with CakeRequest::addDetector(). Any detector can be called
* with `is($type)` or `is$Type()`.
*
* @param string $type The type of request you want to check.
* @return boolean Whether or not the request is the type you are checking.
*/
public function is($type) {
$type = strtolower($type);
if (!isset($this->_detectors[$type])) {
return false;
}
$detect = $this->_detectors[$type];
if (isset($detect['env'])) {
if (isset($detect['value'])) {
return env($detect['env']) == $detect['value'];
}
if (isset($detect['pattern'])) {
return (bool)preg_match($detect['pattern'], env($detect['env']));
}
if (isset($detect['options'])) {
$pattern = '/' . implode('|', $detect['options']) . '/i';
return (bool)preg_match($pattern, env($detect['env']));
}
}
if (isset($detect['callback']) && is_callable($detect['callback'])) {
return call_user_func($detect['callback'], $this);
}
return false;
}
/**
* Add a new detector to the list of detectors that a request can use.
* There are several different formats and types of detectors that can be set.
*
* ### Environment value comparison
*
* An environment value comparison, compares a value fetched from `env()` to a known value
* the environment value is equality checked against the provided value.
*
* e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
*
* ### Pattern value comparison
*
* Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
*
* e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
*
* ### Option based comparison
*
* Option based comparisons use a list of options to create a regular expression. Subsequent calls
* to add an already defined options detector will merge the options.
*
* e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
*
* ### Callback detectors
*
* Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
* recieve the request object as its only parameter.
*
* e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
*
* @param string $name The name of the detector.
* @param array $options The options for the detector definition. See above.
* @return void
*/
public function addDetector($name, $options) {
if (isset($this->_detectors[$name]) && isset($options['options'])) {
$options = Set::merge($this->_detectors[$name], $options);
}
$this->_detectors[$name] = $options;
}
/**
* Add parameters to the request's parsed parameter set.
*
* @param array $params Array of parameters to merge in
* @return The current object, you can chain this method.
*/
public function addParams($params) {
$this->params = array_merge($this->params, $params);
return $this;
}
/**
* Add paths to the requests' paths vars
*
* @param array $paths Array of paths to merge in
* @return the current object, you can chain this method.
*/
public function addPaths($paths) {
foreach (array('webroot', 'here', 'base') as $element) {
if (isset($paths[$element])) {
$this->{$element} = $paths[$element];
}
}
return $this;
}
/**
* Read an HTTP header from the Request information.
*
* @param string $name Name of the header you want.
* @return mixed Either false on no header being set or the value of the header.
*/
public function header($name) {
$name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
if (!empty($_SERVER[$name])) {
return $_SERVER[$name];
}
return false;
}
/**
* Find out which content types the client accepts or check if they accept a
* particular type of content.
*
* @param string $type The content type to check for. Leave null to get all types a client accepts.
* @return mixed Either an array of all the types the client accepts or a boolean if they accept the
* provided type.
*/
public function accepts($type = null) {
$acceptTypes = explode(',', $this->header('accept'));
foreach ($acceptTypes as $i => $accepted) {
if (strpos($accepted, ';') !== false) {
list($accepted, $prefValue) = explode(';', $accepted);
$acceptTypes[$i] = $accepted;
}
}
if ($type === null) {
return $acceptTypes;
}
return in_array($type, $acceptTypes);
}
/**
* Array access read implementation
*
* @param string $name Name of the key being accessed.
* @return mixed
*/
public function offsetGet($name) {
if (isset($this->params[$name])) {
return $this->params[$name];
}
if ($name == 'url') {
return $this->query;
}
if ($name == 'data') {
return $this->data;
}
return null;
}
/**
* Array access write implementation
*
* @param string $name Name of the key being written
* @param mixed $value The value being written.
* @return void
*/
public function offsetSet($name, $value) {
$this->params[$name] = $value;
}
/**
* Array access isset() implementation
*
* @param string $name thing to check.
* @return boolean
*/
public function offsetExists($name) {
return isset($this->params[$name]);
}
/**
* Array access unset() implementation
*
* @param $name Name to unset.
* @return void
*/
public function offsetUnset($name) {
unset($this->params[$name]);
}
}

640
cake/libs/cake_response.php Normal file
View file

@ -0,0 +1,640 @@
<?php
/**
* A class reposible for managing the response text, status and headers of a HTTP response
*
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class CakeResponse {
/**
* Holds HTTP response statuses
*
* @var array
*/
protected $_statusCodes = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out'
);
/**
* Holds known mime type mappings
*
* @var array
*/
protected $_mimeTypes = array(
'ai' => 'application/postscript',
'bcpio' => 'application/x-bcpio',
'bin' => 'application/octet-stream',
'ccad' => 'application/clariscad',
'cdf' => 'application/x-netcdf',
'class' => 'application/octet-stream',
'cpio' => 'application/x-cpio',
'cpt' => 'application/mac-compactpro',
'csh' => 'application/x-csh',
'csv' => array('text/csv', 'application/vnd.ms-excel', 'text/plain'),
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dms' => 'application/octet-stream',
'doc' => 'application/msword',
'drw' => 'application/drafting',
'dvi' => 'application/x-dvi',
'dwg' => 'application/acad',
'dxf' => 'application/dxf',
'dxr' => 'application/x-director',
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'exe' => 'application/octet-stream',
'ez' => 'application/andrew-inset',
'flv' => 'video/x-flv',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'bz2' => 'application/x-bzip',
'7z' => 'application/x-7z-compressed',
'hdf' => 'application/x-hdf',
'hqx' => 'application/mac-binhex40',
'ico' => 'image/vnd.microsoft.icon',
'ips' => 'application/x-ipscript',
'ipx' => 'application/x-ipix',
'js' => 'text/javascript',
'latex' => 'application/x-latex',
'lha' => 'application/octet-stream',
'lsp' => 'application/x-lisp',
'lzh' => 'application/octet-stream',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'mif' => 'application/vnd.mif',
'ms' => 'application/x-troff-ms',
'nc' => 'application/x-netcdf',
'oda' => 'application/oda',
'otf' => 'font/otf',
'pdf' => 'application/pdf',
'pgn' => 'application/x-chess-pgn',
'pot' => 'application/mspowerpoint',
'pps' => 'application/mspowerpoint',
'ppt' => 'application/mspowerpoint',
'ppz' => 'application/mspowerpoint',
'pre' => 'application/x-freelance',
'prt' => 'application/pro_eng',
'ps' => 'application/postscript',
'roff' => 'application/x-troff',
'scm' => 'application/x-lotusscreencam',
'set' => 'application/set',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'sit' => 'application/x-stuffit',
'skd' => 'application/x-koan',
'skm' => 'application/x-koan',
'skp' => 'application/x-koan',
'skt' => 'application/x-koan',
'smi' => 'application/smil',
'smil' => 'application/smil',
'sol' => 'application/solids',
'spl' => 'application/x-futuresplash',
'src' => 'application/x-wais-source',
'step' => 'application/STEP',
'stl' => 'application/SLA',
'stp' => 'application/STEP',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
'swf' => 'application/x-shockwave-flash',
't' => 'application/x-troff',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'tr' => 'application/x-troff',
'tsp' => 'application/dsptype',
'ttf' => 'font/ttf',
'unv' => 'application/i-deas',
'ustar' => 'application/x-ustar',
'vcd' => 'application/x-cdlink',
'vda' => 'application/vda',
'xlc' => 'application/vnd.ms-excel',
'xll' => 'application/vnd.ms-excel',
'xlm' => 'application/vnd.ms-excel',
'xls' => 'application/vnd.ms-excel',
'xlw' => 'application/vnd.ms-excel',
'zip' => 'application/zip',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'au' => 'audio/basic',
'kar' => 'audio/midi',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mpga' => 'audio/mpeg',
'ra' => 'audio/x-realaudio',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'snd' => 'audio/basic',
'tsi' => 'audio/TSP-audio',
'wav' => 'audio/x-wav',
'asc' => 'text/plain',
'c' => 'text/plain',
'cc' => 'text/plain',
'css' => 'text/css',
'etx' => 'text/x-setext',
'f' => 'text/plain',
'f90' => 'text/plain',
'h' => 'text/plain',
'hh' => 'text/plain',
'html' => array('text/html', '*/*'),
'htm' => array('text/html', '*/*'),
'm' => 'text/plain',
'rtf' => 'text/rtf',
'rtx' => 'text/richtext',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
'tpl' => 'text/template',
'txt' => 'text/plain',
'text' => 'text/plain',
'xml' => array('application/xml', 'text/xml'),
'avi' => 'video/x-msvideo',
'fli' => 'video/x-fli',
'mov' => 'video/quicktime',
'movie' => 'video/x-sgi-movie',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'qt' => 'video/quicktime',
'viv' => 'video/vnd.vivo',
'vivo' => 'video/vnd.vivo',
'gif' => 'image/gif',
'ief' => 'image/ief',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'ppm' => 'image/x-portable-pixmap',
'ras' => 'image/cmu-raster',
'rgb' => 'image/x-rgb',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'ice' => 'x-conference/x-cooltalk',
'iges' => 'model/iges',
'igs' => 'model/iges',
'mesh' => 'model/mesh',
'msh' => 'model/mesh',
'silo' => 'model/mesh',
'vrml' => 'model/vrml',
'wrl' => 'model/vrml',
'mime' => 'www/mime',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-pdb',
'javascript' => 'text/javascript',
'json' => 'application/json',
'form' => 'application/x-www-form-urlencoded',
'file' => 'multipart/form-data',
'xhtml' => array('application/xhtml+xml', 'application/xhtml', 'text/xhtml'),
'xhtml-mobile' => 'application/vnd.wap.xhtml+xml',
'rss' => 'application/rss+xml',
'atom' => 'application/atom+xml',
'amf' => 'application/x-amf',
'wap' => array('text/vnd.wap.wml', 'text/vnd.wap.wmlscript', 'image/vnd.wap.wbmp'),
'wml' => 'text/vnd.wap.wml',
'wmlscript' => 'text/vnd.wap.wmlscript',
'wbmp' => 'image/vnd.wap.wbmp',
);
/**
* Protocol header to send to the client
*
* @var string
*/
protected $_protocol = 'HTTP/1.1';
/**
* Status code to send to the client
*
* @var integer
*/
protected $_status = 200;
/**
* Content type to send. This can be an 'extension' that will be transformed using the $_mimetypes array
* or a complete mime-type
*
* @var integer
*/
protected $_contentType = 'text/html';
/**
* Buffer list of headers
*
* @var array
*/
protected $_headers = array();
/**
* Buffer string for response message
*
* @var string
*/
protected $_body = null;
/**
* The charset the response body is encoded with
*
* @var string
*/
protected $_charset = 'UTF-8';
/**
* Class constructor
*
* @param array $options list of parameters to setup the response. Possible values are:
* - body: the rensonse text that should be sent to the client
* - status: the HTTP status code to respond with
* - type: a complete mime-type string or an extension mapepd in this class
* - charset: the charset for the response body
* @return void
*/
public function __construct(array $options = array()) {
if (isset($options['body'])) {
$this->body($options['body']);
}
if (isset($options['status'])) {
$this->statusCode($options['status']);
}
if (isset($options['type'])) {
$this->type($options['type']);
}
if (isset($options['charset'])) {
$this->charset($options['charset']);
}
}
/**
* Sends the complete response to the client including headers and message body
*
*/
public function send() {
if (isset($this->_headers['Location']) && $this->_status === 200) {
$this->statusCode(302);
}
$codeMessage = $this->_statusCodes[$this->_status];
$this->_sendHeader("{$this->_protocol} {$this->_status} {$codeMessage}");
$this->_sendHeader('Content-Type', "{$this->_contentType}; charset={$this->_charset}");
foreach ($this->_headers as $header => $value) {
$this->_sendHeader($header, $value);
}
$this->_sendContent($this->_body);
}
/**
* Sends a header to the client
*
* @param $name the header name
* @param $value the header value
*/
protected function _sendHeader($name, $value = null) {
if (is_null($value)) {
header($name);
} else {
header("{$name}: {$value}");
}
}
/**
* Sends a content string to the client
*
* @param $content string to send as response body
*/
protected function _sendContent($content) {
echo $content;
}
/**
* Buffers a header string to be sent
* Returns the complete list of buffered headers
*
* ### Single header
* e.g `header('Location', 'http://example.com');`
*
* ### Multiple headers
* e.g `header(array('Location' => 'http://example.com', 'X-Extra' => 'My header'));`
*
* ### String header
* e.g `header('WWW-Authenticate: Negotiate');`
*
* ### Array of string headers
* e.g `header(array('WWW-Authenticate: Negotiate'), array('Content-type: application/pdf'));`
*
* Multiple calls for setting the same header name will have the same effect as setting the header once
* with the last value sent for it
* e.g `header('WWW-Authenticate: Negotiate'); header('WWW-Authenticate: Not-Negotiate');`
* will have the same effect as only doing `header('WWW-Authenticate: Not-Negotiate');`
*
* @param mixed $header. An array of header strings or a single header string
* - an assotiative array of "header name" => "header value" is also accepted
* - an array of string headers is also accepted
* @param mixed $value. The header value.
* @return array list of headers to be sent
*/
public function header($header = null, $value = null) {
if (is_null($header)) {
return $this->_headers;
}
if (is_array($header)) {
foreach ($header as $h => $v) {
if (is_numeric($h)) {
$this->header($v);
continue;
}
$this->_headers[$h] = trim($v);
}
return $this->_headers;
}
if (!is_null($value)) {
$this->_headers[$header] = $value;
return $this->_headers;
}
list($header, $value) = explode(':', $header, 2);
$this->_headers[$header] = trim($value);
return $this->_headers;
}
/**
* Buffers the response message to be sent
* if $content is null the current buffer is returned
*
* @param string $content the string message to be sent
* @return string current message buffer if $content param is passed as null
*/
public function body($content = null) {
if (is_null($content)) {
return $this->_body;
}
return $this->_body = $content;
}
/**
* Sets the HTTP status code to be sent
* if $code is null the current code is returned
*
* @param integer $code
* @return integer current status code
*/
public function statusCode($code = null) {
if (is_null($code)) {
return $this->_status;
}
if (!isset($this->_statusCodes[$code])) {
throw new OutOfRangeException(__('Unknown status code'));
}
return $this->_status = $code;
}
/**
* Queries & sets valid HTTP response codes & messages.
*
* @param mixed $code If $code is an integer, then the corresponding code/message is
* returned if it exists, null if it does not exist. If $code is an array,
* then the 'code' and 'message' keys of each nested array are added to the default
* HTTP codes. Example:
*
* httpCodes(404); // returns array(404 => 'Not Found')
*
* httpCodes(array(
* 701 => 'Unicorn Moved',
* 800 => 'Unexpected Minotaur'
* )); // sets these new values, and returns true
*
* @return mixed associative array of the HTTP codes as keys, and the message
* strings as values, or null of the given $code does not exist.
*/
public function httpCodes($code = null) {
if (empty($code)) {
return $this->_statusCodes;
}
if (is_array($code)) {
$this->_statusCodes = $code + $this->_statusCodes;
return true;
}
if (!isset($this->_statusCodes[$code])) {
return null;
}
return array($code => $this->_statusCodes[$code]);
}
/**
* Sets the response content type. It can be either a file extension
* which will be mapped internally to a mime-type or a string representing a mime-type
* if $contentType is null the current content type is returned
* if $contentType is an associative array, it will be stored as a content type definition
*
* ### Setting the content type
* e.g `type('jpg');`
*
* ### Returning the current content type
* e.g `type();`
*
* ### Storing a content type definition
* e.g `type(array('keynote' => 'application/keynote'));`
*
* ### Replacing a content type definition
* e.g `type(array('jpg' => 'text/plain'));`
*
* @param string $contentType
* @return mixed current content type or false if supplied an invalid content type
*/
public function type($contentType = null) {
if (is_null($contentType)) {
return $this->_contentType;
}
if (is_array($contentType)) {
$type = key($contentType);
$defitition = current($contentType);
$this->_mimeTypes[$type] = $defitition;
return $this->_contentType;
}
if (isset($this->_mimeTypes[$contentType])) {
$contentType = $this->_mimeTypes[$contentType];
$contentType = is_array($contentType) ? current($contentType) : $contentType;
}
if (strpos($contentType, '/') === false) {
return false;
}
return $this->_contentType = $contentType;
}
/**
* Returns the mime type definition for an alias
*
* e.g `getMimeType('pdf'); // returns 'application/pdf'`
*
* @param string $alias the content type alias to map
* @return mixed string mapped mime type or false if $alias is not mapped
*/
public function getMimeType($alias) {
if (isset($this->_mimeTypes[$alias])) {
return $this->_mimeTypes[$alias];
}
return false;
}
/**
* Maps a content-type back to an alias
*
* e.g `mapType('application/pdf'); // returns 'pdf'`
*
* @param mixed $type Either a string content type to map, or an array of types.
* @return mixed Aliases for the types provided.
*/
public function mapType($ctype) {
if (is_array($ctype)) {
return array_map(array($this, 'mapType'), $ctype);
}
$keys = array_keys($this->_mimeTypes);
$count = count($keys);
foreach ($this->_mimeTypes as $alias => $types) {
if (is_array($types) && in_array($ctype, $types)) {
return $alias;
} elseif (is_string($types) && $types == $ctype) {
return $alias;
}
}
return null;
}
/**
* Sets the response charset
* if $charset is null the current charset is returned
*
* @param string $charset
* @return string current charset
*/
public function charset($charset = null) {
if (is_null($charset)) {
return $this->_charset;
}
return $this->_charset = $charset;
}
/**
* Sets the correct headers to instruct the client to not cache te response
*
* @return void
*/
public function disableCache() {
$this->header(array(
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
'Last-Modified' => gmdate("D, d M Y H:i:s") . " GMT",
'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
'Pragma' => 'no-cache'
));
}
/**
* Sets the correct headers to instruct the client to cache the response
*
* @param string $since a valid time since the response text has not been modified
* @param string $time a valid time for cache expiry
* @return void
*/
public function cache($since, $time = '+1 day') {
if (!is_integer($time)) {
$time = strtotime($time);
}
$this->header(array(
'Date' => date("D, j M Y G:i:s ", $since) . 'GMT',
'Expires' => gmdate("D, j M Y H:i:s", $time) . " GMT",
'Cache-Control' => 'cache',
'Pragma' => 'cache'
));
}
/**
* Sets the correct output buffering handler to send a compressed response
*
* @return boolean false if client does not accept compressed responses or no handler is available, true otherwise
*/
public function compress() {
$compressionEnabled = ini_get("zlib.output_compression") !== '1' &&
extension_loaded("zlib") &&
(strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
return $compressionEnabled && ob_start('ob_gzhandler');
}
/**
* Sets the correct headers to instruct the browser to dowload the response as a file
*
* @param string $filename the name of the file as the browser will download the response
* @return void
*/
public function download($filename) {
$this->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
}
}

View file

@ -37,7 +37,6 @@ class AuthComponent extends Component {
* Maintains current user login state.
*
* @var boolean
* @access private
*/
protected $_loggedIn = false;
@ -45,7 +44,6 @@ class AuthComponent extends Component {
* Other components utilized by AuthComponent
*
* @var array
* @access public
*/
public $components = array('Session', 'RequestHandler');
@ -53,7 +51,6 @@ class AuthComponent extends Component {
* A reference to the object used for authentication
*
* @var object
* @access public
* @link http://book.cakephp.org/view/1278/authenticate
*/
public $authenticate = null;
@ -67,7 +64,6 @@ class AuthComponent extends Component {
* 'object' will validate Controller::action against object::isAuthorized(user, controller, action)
*
* @var mixed
* @access public
* @link http://book.cakephp.org/view/1275/authorize
*/
public $authorize = false;
@ -77,7 +73,6 @@ class AuthComponent extends Component {
* with an invalid or expired session
*
* @var string
* @access public
* @link http://book.cakephp.org/view/1277/ajaxLogin
*/
public $ajaxLogin = null;
@ -86,7 +81,6 @@ class AuthComponent extends Component {
* The name of the element used for SessionComponent::setFlash
*
* @var string
* @access public
*/
public $flashElement = 'default';
@ -94,7 +88,6 @@ class AuthComponent extends Component {
* The name of the model that represents users which will be authenticated. Defaults to 'User'.
*
* @var string
* @access public
* @link http://book.cakephp.org/view/1266/userModel
*/
public $userModel = 'User';
@ -104,7 +97,6 @@ class AuthComponent extends Component {
* i.e. array('User.is_active' => 1).
*
* @var array
* @access public
* @link http://book.cakephp.org/view/1268/userScope
*/
public $userScope = array();
@ -114,7 +106,6 @@ class AuthComponent extends Component {
* $userModel, i.e. array('username' => 'login_name', 'password' => 'passwd').
*
* @var array
* @access public
* @link http://book.cakephp.org/view/1267/fields
*/
public $fields = array('username' => 'username', 'password' => 'password');
@ -124,7 +115,6 @@ class AuthComponent extends Component {
* unspecified, it will be "Auth.{$userModel name}".
*
* @var string
* @access public
* @link http://book.cakephp.org/view/1276/sessionKey
*/
public $sessionKey = null;
@ -136,7 +126,6 @@ class AuthComponent extends Component {
* "Controllers/".
*
* @var string
* @access public
* @link http://book.cakephp.org/view/1279/actionPath
*/
public $actionPath = null;
@ -146,7 +135,6 @@ class AuthComponent extends Component {
* logins.
*
* @var mixed
* @access public
* @link http://book.cakephp.org/view/1269/loginAction
*/
public $loginAction = null;
@ -158,7 +146,6 @@ class AuthComponent extends Component {
* set, the user will be redirected to the page specified in $loginRedirect.
*
* @var mixed
* @access public
* @link http://book.cakephp.org/view/1270/loginRedirect
*/
public $loginRedirect = null;
@ -169,7 +156,6 @@ class AuthComponent extends Component {
* Defaults to AuthComponent::$loginAction.
*
* @var mixed
* @access public
* @see AuthComponent::$loginAction
* @see AuthComponent::logout()
* @link http://book.cakephp.org/view/1271/logoutRedirect
@ -180,7 +166,6 @@ class AuthComponent extends Component {
* The name of model or model object, or any other object has an isAuthorized method.
*
* @var string
* @access public
*/
public $object = null;
@ -189,7 +174,6 @@ class AuthComponent extends Component {
* login failures, so as not to expose information on why the login failed.
*
* @var string
* @access public
* @link http://book.cakephp.org/view/1272/loginError
*/
public $loginError = null;
@ -199,7 +183,6 @@ class AuthComponent extends Component {
* acccess.
*
* @var string
* @access public
* @link http://book.cakephp.org/view/1273/authError
*/
public $authError = null;
@ -208,7 +191,6 @@ class AuthComponent extends Component {
* Determines whether AuthComponent will automatically redirect and exit if login is successful.
*
* @var boolean
* @access public
* @link http://book.cakephp.org/view/1274/autoRedirect
*/
public $autoRedirect = true;
@ -217,7 +199,6 @@ class AuthComponent extends Component {
* Controller actions for which user validation is not required.
*
* @var array
* @access public
* @see AuthComponent::allow()
* @link http://book.cakephp.org/view/1251/Setting-Auth-Component-Variables
*/
@ -227,7 +208,6 @@ class AuthComponent extends Component {
* Maps actions to CRUD operations. Used for controller-based validation ($validate = 'controller').
*
* @var array
* @access public
* @see AuthComponent::mapActions()
*/
public $actionMap = array(
@ -238,19 +218,26 @@ class AuthComponent extends Component {
'remove' => 'delete'
);
/**
* Request object
*
* @var CakeRequest
*/
public $request;
/**
* Form data from Controller::$data
*
* @deprecated Use $this->request->data instead
* @var array
* @access public
*/
public $data = array();
/**
* Parameter data from Controller::$params
*
* @deprecated Use $this->request instead
* @var array
* @access public
*/
public $params = array();
@ -265,7 +252,6 @@ class AuthComponent extends Component {
* Method list for bound controller
*
* @var array
* @access protected
*/
protected $_methods = array();
@ -275,8 +261,10 @@ class AuthComponent extends Component {
* @param object $controller A reference to the instantiating controller object
* @return void
*/
public function initialize(&$controller) {
$this->params = $controller->params;
public function initialize(Controller $controller, $settings = array()) {
$this->request = $controller->request;
$this->params = $this->request;
$crud = array('create', 'read', 'update', 'delete');
$this->actionMap = array_merge($this->actionMap, array_combine($crud, $crud));
$this->_methods = $controller->methods;
@ -320,7 +308,8 @@ class AuthComponent extends Component {
}
$methods = array_flip($controller->methods);
$action = $controller->params['action'];
$action = $controller->request->params['action'];
$isMissingAction = (
$controller->scaffold === false &&
!isset($methods[$action])
@ -333,12 +322,13 @@ class AuthComponent extends Component {
if (!$this->__setDefaults()) {
return false;
}
$this->data = $controller->data = $this->hashPasswords($controller->data);
$request =& $controller->request;
$this->request->data = $controller->request->data = $this->hashPasswords($request->data);
$url = '';
if (isset($controller->params['url']['url'])) {
$url = $controller->params['url']['url'];
if (isset($request->query['url'])) {
$url = $request->query['url'];
}
$url = Router::normalize($url);
$loginAction = Router::normalize($this->loginAction);
@ -354,20 +344,20 @@ class AuthComponent extends Component {
}
if ($loginAction == $url) {
$model =& $this->getModel();
if (empty($controller->data) || !isset($controller->data[$model->alias])) {
$model = $this->getModel();
if (empty($request->data) || !isset($request->data[$model->alias])) {
if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
$this->Session->write('Auth.redirect', $controller->referer(null, true));
}
return false;
}
$isValid = !empty($controller->data[$model->alias][$this->fields['username']]) &&
!empty($controller->data[$model->alias][$this->fields['password']]);
$isValid = !empty($request->data[$model->alias][$this->fields['username']]) &&
!empty($request->data[$model->alias][$this->fields['password']]);
if ($isValid) {
$username = $controller->data[$model->alias][$this->fields['username']];
$password = $controller->data[$model->alias][$this->fields['password']];
$username = $request->data[$model->alias][$this->fields['username']];
$password = $request->data[$model->alias][$this->fields['password']];
$data = array(
$model->alias . '.' . $this->fields['username'] => $username,
@ -383,14 +373,14 @@ class AuthComponent extends Component {
}
$this->Session->setFlash($this->loginError, $this->flashElement, array(), 'auth');
$controller->data[$model->alias][$this->fields['password']] = null;
$request->data[$model->alias][$this->fields['password']] = null;
return false;
} else {
if (!$this->user()) {
if (!$this->RequestHandler->isAjax()) {
$this->Session->setFlash($this->authError, $this->flashElement, array(), 'auth');
if (!empty($controller->params['url']) && count($controller->params['url']) >= 2) {
$query = $controller->params['url'];
if (!empty($request->query) && count($request->query) >= 2) {
$query = $request->query;
unset($query['url'], $query['ext']);
$url .= Router::queryString($query, array());
}
@ -415,12 +405,12 @@ class AuthComponent extends Component {
extract($this->__authType());
switch ($type) {
case 'controller':
$this->object =& $controller;
$this->object = $controller;
break;
case 'crud':
case 'actions':
if (isset($controller->Acl)) {
$this->Acl =& $controller->Acl;
$this->Acl = $controller->Acl;
} else {
trigger_error(__('Could not find AclComponent. Please include Acl in Controller::$components.'), E_USER_WARNING);
}
@ -531,22 +521,22 @@ class AuthComponent extends Component {
break;
case 'crud':
$this->mapActions();
if (!isset($this->actionMap[$this->params['action']])) {
if (!isset($this->actionMap[$this->request['action']])) {
trigger_error(
sprintf(__('Auth::startup() - Attempted access of un-mapped action "%1$s" in controller "%2$s"'), $this->params['action'], $this->params['controller']),
sprintf(__('Auth::startup() - Attempted access of un-mapped action "%1$s" in controller "%2$s"'), $this->request['action'], $this->request['controller']),
E_USER_WARNING
);
} else {
$valid = $this->Acl->check(
$user,
$this->action(':controller'),
$this->actionMap[$this->params['action']]
$this->actionMap[$this->request['action']]
);
}
break;
case 'model':
$this->mapActions();
$action = $this->params['action'];
$action = $this->request['action'];
if (isset($this->actionMap[$action])) {
$action = $this->actionMap[$action];
}
@ -723,7 +713,7 @@ class AuthComponent extends Component {
}
if ($key == null) {
$model =& $this->getModel();
$model = $this->getModel();
return array($model->alias => $this->Session->read($this->sessionKey));
} else {
$user = $this->Session->read($this->sessionKey);
@ -789,10 +779,10 @@ class AuthComponent extends Component {
* @link http://book.cakephp.org/view/1256/action
*/
public function action($action = ':plugin/:controller/:action') {
$plugin = empty($this->params['plugin']) ? null : Inflector::camelize($this->params['plugin']) . '/';
$plugin = empty($this->request['plugin']) ? null : Inflector::camelize($this->request['plugin']) . '/';
return str_replace(
array(':controller', ':action', ':plugin/'),
array(Inflector::camelize($this->params['controller']), $this->params['action'], $plugin),
array(Inflector::camelize($this->request['controller']), $this->request['action'], $plugin),
$this->actionPath . $action
);
}
@ -836,7 +826,7 @@ class AuthComponent extends Component {
} else {
$conditions = $this->userScope;
}
$model =& $this->getModel();
$model = $this->getModel();
if (empty($user)) {
$user = $this->user();
if (empty($user)) {
@ -910,7 +900,7 @@ class AuthComponent extends Component {
}
if (is_array($data)) {
$model =& $this->getModel();
$model = $this->getModel();
if(isset($data[$model->alias])) {
if (isset($data[$model->alias][$this->fields['username']]) && isset($data[$model->alias][$this->fields['password']])) {

View file

@ -48,101 +48,20 @@ class RequestHandlerComponent extends Component {
public $enabled = true;
/**
* Holds the content-type of the response that is set when using
* RequestHandler::respondAs()
* Holds the reference to Controller::$request
*
* @var string
* @access private
*/
private $__responseTypeSet = null;
/**
* Holds the copy of Controller::$params
*
* @var array
* @var CakeRequest
* @access public
*/
public $params = array();
public $request;
/**
* Friendly content-type mappings used to set response types and determine
* request types. Can be modified with RequestHandler::setContent()
* Holds the reference to Controller::$response
*
* @var array
* @access private
* @see RequestHandlerComponent::setContent
*/
private $__requestContent = array(
'javascript' => 'text/javascript',
'js' => 'text/javascript',
'json' => 'application/json',
'css' => 'text/css',
'html' => array('text/html', '*/*'),
'text' => 'text/plain',
'txt' => 'text/plain',
'csv' => array('application/vnd.ms-excel', 'text/plain'),
'form' => 'application/x-www-form-urlencoded',
'file' => 'multipart/form-data',
'xhtml' => array('application/xhtml+xml', 'application/xhtml', 'text/xhtml'),
'xhtml-mobile' => 'application/vnd.wap.xhtml+xml',
'xml' => array('application/xml', 'text/xml'),
'rss' => 'application/rss+xml',
'atom' => 'application/atom+xml',
'amf' => 'application/x-amf',
'wap' => array(
'text/vnd.wap.wml',
'text/vnd.wap.wmlscript',
'image/vnd.wap.wbmp'
),
'wml' => 'text/vnd.wap.wml',
'wmlscript' => 'text/vnd.wap.wmlscript',
'wbmp' => 'image/vnd.wap.wbmp',
'pdf' => 'application/pdf',
'zip' => 'application/x-zip',
'tar' => 'application/x-tar'
);
/**
* List of regular expressions for matching mobile device's user agent string
*
* @var array
* @var CakeResponse
* @access public
*/
public $mobileUA = array(
'Android',
'AvantGo',
'BlackBerry',
'DoCoMo',
'iPod',
'iPhone',
'J2ME',
'MIDP',
'NetFront',
'Nokia',
'Opera Mini',
'PalmOS',
'PalmSource',
'portalmmm',
'Plucker',
'ReqwirelessWeb',
'SonyEricsson',
'Symbian',
'UP\.Browser',
'webOS',
'Windows CE',
'Xiino'
);
/**
* Content-types accepted by the client. If extension parsing is enabled in the
* Router, and an extension is detected, the corresponding content-type will be
* used as the overriding primary content-type accepted.
*
* @var array
* @access private
* @see Router::parseExtensions()
*/
private $__acceptTypes = array();
public $response;
/**
* The template to use when rendering the given content type.
@ -190,19 +109,32 @@ class RequestHandlerComponent extends Component {
/**
* Initializes the component, gets a reference to Controller::$parameters, and
* checks to see if a file extension has been parsed by the Router. If yes, the
* corresponding content-type is pushed onto the list of accepted content-types
* as the first item.
* checks to see if a file extension has been parsed by the Router. Or if the
* HTTP_ACCEPT_TYPE is set to a single value that is a supported extension and mapped type.
* If yes, RequestHandler::$ext is set to that value
*
* @param object $controller A reference to the controller
* @param array $settings Array of settings to _set().
* @return void
* @see Router::parseExtensions()
*/
public function initialize(&$controller) {
public function initialize(&$controller, $settings = array()) {
$this->request = $controller->request;
$this->response = $controller->response;
if (isset($controller->params['url']['ext'])) {
$this->ext = $controller->params['url']['ext'];
}
if (empty($this->ext)) {
$accepts = $this->request->accepts();
$extensions = Router::extensions();
if (count($accepts) == 1) {
$mapped = $this->mapType($accepts[0]);
if (in_array($mapped, $extensions)) {
$this->ext = $mapped;
}
}
}
$this->_set($settings);
}
/**
@ -211,8 +143,10 @@ class RequestHandlerComponent extends Component {
*
* - Disabling layout rendering for Ajax requests (based on the HTTP_X_REQUESTED_WITH header)
* - If Router::parseExtensions() is enabled, the layout and template type are
* switched based on the parsed extension. For example, if controller/action.xml
* is requested, the view path becomes <i>app/views/controller/xml/action.ctp</i>.
* switched based on the parsed extension or Accept-Type header. For example, if `controller/action.xml`
* is requested, the view path becomes `app/views/controller/xml/action.ctp`. Also if
* `controller/action` is requested with `Accept-Type: application/xml` in the headers
* the view path will become `app/views/controller/xml/action.ctp`.
* - If a helper with the same name as the extension exists, it is added to the controller.
* - If the extension is of a type that RequestHandler understands, it will set that
* Content-type in the response header.
@ -223,20 +157,15 @@ class RequestHandlerComponent extends Component {
* @return void
*/
public function startup(&$controller) {
if (!$this->enabled) {
return;
}
$this->__initializeTypes();
$controller->params['isAjax'] = $this->isAjax();
$controller->request->params['isAjax'] = $this->request->is('ajax');
$isRecognized = (
!in_array($this->ext, array('html', 'htm')) &&
in_array($this->ext, array_keys($this->__requestContent))
$this->response->getMimeType($this->ext)
);
if (!empty($this->ext) && $isRecognized) {
$this->renderAs($controller, $this->ext);
} elseif ($this->isAjax()) {
} elseif ($this->request->is('ajax')) {
$this->renderAs($controller, 'ajax');
}
@ -262,7 +191,7 @@ class RequestHandlerComponent extends Component {
* @param mixed HTTP Status for redirect
*/
public function beforeRedirect(&$controller, $url, $status = null) {
if (!$this->isAjax()) {
if (!$this->request->is('ajax')) {
return;
}
foreach ($_POST as $key => $val) {
@ -272,12 +201,12 @@ class RequestHandlerComponent extends Component {
$url = Router::url($url + array('base' => false));
}
if (!empty($status)) {
$statusCode = $controller->httpCodes($status);
$statusCode = $this->response->httpCodes($status);
$code = key($statusCode);
$msg = $statusCode[$code];
$controller->header("HTTP/1.1 {$code} {$msg}");
$this->response->statusCode($code);
}
echo $this->requestAction($url, array('return', 'bare' => false));
$this->response->body($this->requestAction($url, array('return', 'bare' => false)));
$this->response->send();
$this->_stop();
}
@ -287,7 +216,7 @@ class RequestHandlerComponent extends Component {
* @return boolean True if call is Ajax
*/
public function isAjax() {
return env('HTTP_X_REQUESTED_WITH') === "XMLHttpRequest";
return $this->request->is('ajax');
}
/**
@ -296,7 +225,7 @@ class RequestHandlerComponent extends Component {
* @return boolean True if call is from Flash
*/
public function isFlash() {
return (preg_match('/^(Shockwave|Adobe) Flash/', env('HTTP_USER_AGENT')) == 1);
return $this->request->is('flash');
}
/**
@ -305,7 +234,7 @@ class RequestHandlerComponent extends Component {
* @return bool True if call is over HTTPS
*/
public function isSSL() {
return env('HTTPS');
return $this->request->is('ssl');
}
/**
@ -340,20 +269,9 @@ class RequestHandlerComponent extends Component {
* client accepts WAP content.
*
* @return boolean True if user agent is a mobile web browser
* @access public
* @deprecated Use of constant REQUEST_MOBILE_UA is deprecated and will be removed in future versions
*/
function isMobile() {
if (defined('REQUEST_MOBILE_UA')) {
$regex = '/' . REQUEST_MOBILE_UA . '/i';
} else {
$regex = '/' . implode('|', $this->mobileUA) . '/i';
}
if (preg_match($regex, env('HTTP_USER_AGENT')) || $this->accepts('wap')) {
return true;
}
return false;
return $this->request->is('mobile') || $this->accepts('wap');
}
/**
@ -369,36 +287,40 @@ class RequestHandlerComponent extends Component {
* Returns true if the current call a POST request
*
* @return boolean True if call is a POST
* @deprecated Use $this->request->is('post'); from your controller.
*/
public function isPost() {
return (strtolower(env('REQUEST_METHOD')) == 'post');
return $this->request->is('post');
}
/**
* Returns true if the current call a PUT request
*
* @return boolean True if call is a PUT
* @deprecated Use $this->request->is('put'); from your controller.
*/
public function isPut() {
return (strtolower(env('REQUEST_METHOD')) == 'put');
return $this->request->is('put');
}
/**
* Returns true if the current call a GET request
*
* @return boolean True if call is a GET
* @deprecated Use $this->request->is('get'); from your controller.
*/
public function isGet() {
return (strtolower(env('REQUEST_METHOD')) == 'get');
return $this->request->is('get');
}
/**
* Returns true if the current call a DELETE request
*
* @return boolean True if call is a DELETE
* @deprecated Use $this->request->is('delete'); from your controller.
*/
public function isDelete() {
return (strtolower(env('REQUEST_METHOD')) == 'delete');
return $this->request->is('delete');
}
/**
@ -426,59 +348,43 @@ class RequestHandlerComponent extends Component {
* @return void
*/
public function setContent($name, $type = null) {
if (is_array($name)) {
$this->__requestContent = array_merge($this->__requestContent, $name);
return;
}
$this->__requestContent[$name] = $type;
$this->response->type(array($name => $type));
}
/**
* Gets the server name from which this request was referred
*
* @return string Server address
* @deprecated use $this->request->referer() from your controller instead
*/
public function getReferer() {
if (env('HTTP_HOST') != null) {
$sessHost = env('HTTP_HOST');
}
if (env('HTTP_X_FORWARDED_HOST') != null) {
$sessHost = env('HTTP_X_FORWARDED_HOST');
}
return trim(preg_replace('/(?:\:.*)/', '', $sessHost));
return $this->request->referer(false);
}
/**
* Gets remote client IP
*
* @return string Client IP address
* @deprecated use $this->request->clientIp() from your controller instead.
*/
public function getClientIP($safe = true) {
if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
} else {
if (env('HTTP_CLIENT_IP') != null) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
$ipaddr = env('REMOTE_ADDR');
}
}
if (env('HTTP_CLIENTADDRESS') != null) {
$tmpipaddr = env('HTTP_CLIENTADDRESS');
if (!empty($tmpipaddr)) {
$ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
}
}
return trim($ipaddr);
return $this->request->clientIp($safe);
}
/**
* Determines which content types the client accepts. Acceptance is based on
* the file extension parsed by the Router (if present), and by the HTTP_ACCEPT
* header.
* header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types.
*
* Usage:
*
* `$this->RequestHandler->accepts(array('xml', 'html', 'json'));`
*
* Returns true if the client accepts any of the supplied types.
*
* `$this->RequestHandler->accepts('xml');`
*
* Returns true if the client accepts xml.
*
* @param mixed $type Can be null (or no parameter), a string type name, or an
* array of types
@ -490,37 +396,21 @@ class RequestHandlerComponent extends Component {
* @see RequestHandlerComponent::setContent()
*/
function accepts($type = null) {
$this->__initializeTypes();
$accepted = $this->request->accepts();
if ($type == null) {
return $this->mapType($this->__acceptTypes);
return $this->mapType($accepted);
} elseif (is_array($type)) {
foreach ($type as $t) {
if ($this->accepts($t) == true) {
$t = $this->mapAlias($t);
if (in_array($t, $accepted)) {
return true;
}
}
return false;
} elseif (is_string($type)) {
if (!isset($this->__requestContent[$type])) {
return false;
}
$content = $this->__requestContent[$type];
if (is_array($content)) {
foreach ($content as $c) {
if (in_array($c, $this->__acceptTypes)) {
return true;
}
}
} else {
if (in_array($content, $this->__acceptTypes)) {
return true;
}
}
$type = $this->mapAlias($type);
return in_array($type, $accepted);
}
return false;
}
@ -529,20 +419,22 @@ class RequestHandlerComponent extends Component {
* Determines the content type of the data the client has sent (i.e. in a POST request)
*
* @param mixed $type Can be null (or no parameter), a string type name, or an array of types
* @return mixed
* @return mixed If a single type is supplied a boolean will be returned. If no type is provided
* The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type
* in the request content type will be returned.
*/
public function requestedWith($type = null) {
if (!$this->isPost() && !$this->isPut()) {
if (!$this->request->is('post') && !$this->request->is('put')) {
return null;
}
list($contentType) = explode(';', env('CONTENT_TYPE'));
if ($type == null) {
return $this->mapType($contentType);
} elseif (is_array($type)) {
foreach ($type as $t) {
if ($this->requestedWith($t)) {
return $this->mapType($t);
return $t;
}
}
return false;
@ -567,52 +459,33 @@ class RequestHandlerComponent extends Component {
* @see RequestHandlerComponent::setContent()
*/
function prefers($type = null) {
$this->__initializeTypes();
$accept = $this->accepts();
$accepts = $this->accepts();
if ($type == null) {
if (empty($this->ext)) {
if (is_array($accept)) {
return $accept[0];
if (is_array($accepts)) {
return $accepts[0];
}
return $accept;
return $accepts;
}
return $this->ext;
}
$types = $type;
if (is_string($type)) {
$types = array($type);
}
$types = (array)$type;
if (count($types) === 1) {
if (!empty($this->ext)) {
return ($types[0] == $this->ext);
}
return ($types[0] == $accept[0]);
}
$accepts = array();
foreach ($types as $type) {
if (in_array($type, $accept)) {
$accepts[] = $type;
}
return ($types[0] == $accepts[0]);
}
if (count($accepts) === 0) {
$intersect = array_values(array_intersect($accepts, $types));
if (empty($intersect)) {
return false;
} elseif (count($types) === 1) {
return ($types[0] === $accepts[0]);
} elseif (count($accepts) === 1) {
return $accepts[0];
}
$acceptedTypes = array();
foreach ($this->__acceptTypes as $type) {
$acceptedTypes[] = $this->mapType($type);
}
$accepts = array_intersect($acceptedTypes, $accepts);
return $accepts[0];
return $intersect[0];
}
/**
@ -626,7 +499,6 @@ class RequestHandlerComponent extends Component {
* @see RequestHandlerComponent::respondAs()
*/
function renderAs(&$controller, $type) {
$this->__initializeTypes();
$options = array('charset' => 'UTF-8');
if (Configure::read('App.encoding') !== null) {
@ -648,7 +520,7 @@ class RequestHandlerComponent extends Component {
$this->__renderType = $type;
$controller->layoutPath = $type;
if (isset($this->__requestContent[$type])) {
if ($this->response->getMimeType($type)) {
$this->respondAs($type, $options);
}
@ -680,25 +552,18 @@ class RequestHandlerComponent extends Component {
* @see RequestHandlerComponent::setContent()
*/
function respondAs($type, $options = array()) {
$this->__initializeTypes();
if (!array_key_exists($type, $this->__requestContent) && strpos($type, '/') === false) {
return false;
}
$defaults = array('index' => 0, 'charset' => null, 'attachment' => false);
$options = array_merge($defaults, $options);
$defaults = array('index' => null, 'charset' => null, 'attachment' => false);
$options = $options + $defaults;
if (strpos($type, '/') === false && isset($this->__requestContent[$type])) {
$cType = null;
if (is_array($this->__requestContent[$type]) && isset($this->__requestContent[$type][$options['index']])) {
$cType = $this->__requestContent[$type][$options['index']];
} elseif (is_array($this->__requestContent[$type]) && isset($this->__requestContent[$type][0])) {
$cType = $this->__requestContent[$type][0];
} elseif (isset($this->__requestContent[$type])) {
$cType = $this->__requestContent[$type];
} else {
$cType = null;
if (strpos($type, '/') === false) {
$cType = $this->response->getMimeType($type);
if ($cType === false) {
return false;
}
if (is_array($cType) && isset($cType[$options['index']])) {
$cType = $cType[$options['index']];
}
if (is_array($cType)) {
if ($this->prefers($cType)) {
$cType = $this->prefers($cType);
@ -711,94 +576,58 @@ class RequestHandlerComponent extends Component {
}
if ($cType != null) {
$header = 'Content-type: ' . $cType;
$this->response->type($cType);
if (!empty($options['charset'])) {
$header .= '; charset=' . $options['charset'];
$this->response->charset($options['charset']);
}
if (!empty($options['attachment'])) {
$this->_header("Content-Disposition: attachment; filename=\"{$options['attachment']}\"");
$this->response->download($options['attachment']);
}
if (Configure::read('debug') < 2 && !defined('CAKEPHP_SHELL')) {
$this->_header($header);
}
$this->__responseTypeSet = $cType;
return true;
}
return false;
}
/**
* Wrapper for header() so calls can be easily tested.
*
* @param string $header The header to be sent.
* @return void
*/
protected function _header($header) {
header($header);
}
/**
* Returns the current response type (Content-type header), or null if none has been set
* Returns the current response type (Content-type header), or null if not alias exists
*
* @return mixed A string content type alias, or raw content type if no alias map exists,
* otherwise null
* otherwise null
*/
public function responseType() {
if ($this->__responseTypeSet == null) {
return null;
}
return $this->mapType($this->__responseTypeSet);
return $this->mapType($this->response->type());
}
/**
* Maps a content-type back to an alias
*
* @param mixed $type Content type
* @return mixed Alias
* @param mixed $cType Either a string content type to map, or an array of types.
* @return mixed Aliases for the types provided.
*/
public function mapType($ctype) {
if (is_array($ctype)) {
$out = array();
foreach ($ctype as $t) {
$out[] = $this->mapType($t);
}
return $out;
} else {
$keys = array_keys($this->__requestContent);
$count = count($keys);
for ($i = 0; $i < $count; $i++) {
$name = $keys[$i];
$type = $this->__requestContent[$name];
if (is_array($type) && in_array($ctype, $type)) {
return $name;
} elseif (!is_array($type) && $type == $ctype) {
return $name;
}
}
return $ctype;
}
public function mapType($cType) {
return $this->response->mapType($cType);
}
/**
* Initializes MIME types
* Maps a content type alias back to its mime-type(s)
*
* @return void
* @access private
* @param mixed $alias String alias to convert back into a content type. Or an array of aliases to map.
* @return mixed Null on an undefined alias. String value of the mapped alias type. If an
* alias maps to more than one content type, the first one will be returned.
*/
function __initializeTypes() {
if ($this->__typesInitialized) {
return;
public function mapAlias($alias) {
if (is_array($alias)) {
return array_map(array($this, 'mapAlias'), $alias);
}
if (isset($this->__requestContent[$this->ext])) {
$content = $this->__requestContent[$this->ext];
if (is_array($content)) {
$content = $content[0];
$type = $this->response->getMimeType($alias);
if ($type) {
if (is_array($type)) {
return $type[0];
}
array_unshift($this->__acceptTypes, $content);
return $type;
}
$this->__typesInitialized = true;
return null;
}
}

View file

@ -160,7 +160,7 @@ class SecurityComponent extends Component {
* @var array
* @access public
*/
public $components = array('RequestHandler', 'Session');
public $components = array('Session');
/**
* Holds the current action of the controller
@ -169,6 +169,24 @@ class SecurityComponent extends Component {
*/
protected $_action = null;
/**
* Request object
*
* @var CakeRequest
*/
public $request;
/**
* Initialize the SecurityComponent
*
* @param object $controller Controller instance for the request
* @param array $settings Settings to set to the component
* @return void
*/
public function initialize(&$controller, $settings = array()) {
$this->_set($settings);
}
/**
* Component startup. All security checking happens here.
*
@ -176,16 +194,17 @@ class SecurityComponent extends Component {
* @return void
*/
public function startup(&$controller) {
$this->_action = strtolower($controller->action);
$this->request = $controller->request;
$this->_action = strtolower($this->request->params['action']);
$this->_methodsRequired($controller);
$this->_secureRequired($controller);
$this->_authRequired($controller);
$this->_loginRequired($controller);
$isPost = ($this->RequestHandler->isPost() || $this->RequestHandler->isPut());
$isPost = ($this->request->is('post') || $this->request->is('put'));
$isRequestAction = (
!isset($controller->params['requested']) ||
$controller->params['requested'] != 1
!isset($controller->request->params['requested']) ||
$controller->request->params['requested'] != 1
);
if ($isPost && $isRequestAction && $this->validatePost) {
@ -439,9 +458,8 @@ class SecurityComponent extends Component {
$property = 'require' . $method;
if (is_array($this->$property) && !empty($this->$property)) {
$require = array_map('strtolower', $this->$property);
if (in_array($this->_action, $require) || $this->$property == array('*')) {
if (!$this->RequestHandler->{'is' . $method}()) {
if (!$this->request->is(strtolower($method))) {
if (!$this->blackHole($controller, strtolower($method))) {
return null;
}
@ -463,7 +481,7 @@ class SecurityComponent extends Component {
$requireSecure = array_map('strtolower', $this->requireSecure);
if (in_array($this->_action, $requireSecure) || $this->requireSecure == array('*')) {
if (!$this->RequestHandler->isSSL()) {
if (!$this->request->is('ssl')) {
if (!$this->blackHole($controller, 'secure')) {
return null;
}
@ -480,11 +498,11 @@ class SecurityComponent extends Component {
* @return bool true if authentication required
*/
protected function _authRequired(&$controller) {
if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($controller->data)) {
if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($this->request->data)) {
$requireAuth = array_map('strtolower', $this->requireAuth);
if (in_array($this->_action, $requireAuth) || $this->requireAuth == array('*')) {
if (!isset($controller->data['_Token'] )) {
if (in_array($this->request->params['action'], $requireAuth) || $this->requireAuth == array('*')) {
if (!isset($controller->request->data['_Token'] )) {
if (!$this->blackHole($controller, 'auth')) {
return null;
}
@ -493,7 +511,7 @@ class SecurityComponent extends Component {
if ($this->Session->check('_Token')) {
$tData = unserialize($this->Session->read('_Token'));
if (!empty($tData['allowedControllers']) && !in_array($controller->params['controller'], $tData['allowedControllers']) || !empty($tData['allowedActions']) && !in_array($controller->params['action'], $tData['allowedActions'])) {
if (!empty($tData['allowedControllers']) && !in_array($this->request->params['controller'], $tData['allowedControllers']) || !empty($tData['allowedActions']) && !in_array($this->request->params['action'], $tData['allowedActions'])) {
if (!$this->blackHole($controller, 'auth')) {
return null;
}
@ -562,10 +580,10 @@ class SecurityComponent extends Component {
* @return bool true if submitted form is valid
*/
protected function _validatePost(&$controller) {
if (empty($controller->data)) {
if (empty($controller->request->data)) {
return true;
}
$data = $controller->data;
$data = $controller->request->data;
if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['key'])) {
return false;
@ -581,7 +599,7 @@ class SecurityComponent extends Component {
}
$locked = null;
$check = $controller->data;
$check = $controller->request->data;
$token = urldecode($check['_Token']['fields']);
if (strpos($token, ':')) {
@ -659,8 +677,8 @@ class SecurityComponent extends Component {
'disabledFields' => $this->disabledFields
);
if (!isset($controller->data)) {
$controller->data = array();
if (!isset($controller->request->data)) {
$controller->request->data = array();
}
if ($this->Session->check('_Token')) {
@ -675,7 +693,7 @@ class SecurityComponent extends Component {
$token['key'] = $tokenData['key'];
}
}
$controller->params['_Token'] = $token;
$controller->request->params['_Token'] = $token;
$this->Session->write('_Token', serialize($token));
return true;
}

View file

@ -49,6 +49,7 @@ class Controller extends Object {
* Stores the current URL, relative to the webroot of the application.
*
* @var string
* @deprecated Will be removed in future versions. Use $this->request->here instead
*/
public $here = null;
@ -56,6 +57,7 @@ class Controller extends Object {
* The webroot of the application.
*
* @var string
* @deprecated Will be removed in future versions. Use $this->request->webroot instead
*/
public $webroot = null;
@ -96,6 +98,7 @@ class Controller extends Object {
*
* @var array
* @link http://book.cakephp.org/view/963/The-Parameters-Attribute-params
* @deprecated Will be removed in future versions. Use $this->request instead
*/
public $params = array();
@ -104,9 +107,17 @@ class Controller extends Object {
* using the `$this->data['ModelName']['fieldName']` pattern.
*
* @var array
* @deprecated Will be removed in future versions. Use $this->request->data instead
*/
public $data = array();
/**
* An instance of a CakeRequest object that contains information about the current request.
*
* @var CakeRequest
*/
public $request;
/**
* Holds pagination defaults for controller actions. The keys that can be included
* in this array are: 'conditions', 'fields', 'order', 'limit', 'page', and 'recursive',
@ -159,6 +170,7 @@ class Controller extends Object {
* Base URL path.
*
* @var string
* @deprecated Will be removed in future versions. Use $this->request->base instead
*/
public $base = null;
@ -226,15 +238,6 @@ class Controller extends Object {
*/
public $ext = '.ctp';
/**
* The output of the requested action. Contains either a variable
* returned from the action, or the data of the rendered view;
* You can use this var in child controllers' afterFilter() callbacks to alter output.
*
* @var string
*/
public $output = null;
/**
* Automatically set to the name of a plugin.
*
@ -321,20 +324,14 @@ class Controller extends Object {
*/
public $validationErrors = null;
/**
* Contains a list of the HTTP codes that CakePHP recognizes. These may be
* queried and/or modified through Controller::httpCodes(), which is also
* tasked with their lazy-loading.
*
* @var array Associative array of HTTP codes and their associated messages.
*/
private $__httpCodes = null;
/**
* Constructor.
*
* @param CakeRequest $request Request object for this controller can be null for testing.
* But expect that features that use the params will not work.
* @param CakeResponse $response Response object for this controller
*/
public function __construct() {
public function __construct($request = null, $response = null) {
if ($this->name === null) {
$r = null;
if (!preg_match('/(.*)Controller/i', get_class($this), $r)) {
@ -355,9 +352,44 @@ class Controller extends Object {
$parentMethods = get_class_methods('Controller');
$this->methods = array_diff($childMethods, $parentMethods);
if ($request instanceof CakeRequest) {
$this->_setRequest($request);
}
$this->response = $response;
parent::__construct();
}
/**
* Sets the request objects and configures a number of controller properties
* based on the contents of the request.
*
* @param CakeRequest $request
* @return void
*/
protected function _setRequest(CakeRequest $request) {
$this->base = $request->base;
$this->here = $request->here;
$this->webroot = $request->webroot;
$this->plugin = isset($request->params['plugin']) ? $request->params['plugin'] : null;
$this->params = $this->request = $request;
$this->action =& $request->params['action'];
if (isset($request->params['pass']) && isset($request->params['named'])) {
$this->passedArgs = array_merge($request->params['pass'], $request->params['named']);
}
$this->data = null;
if (!empty($request->params['data'])) {
$this->data =& $request->params['data'];
}
if (array_key_exists('return', $request->params) && $request->params['return'] == 1) {
$this->autoRender = false;
}
if (!empty($request->params['bare'])) {
$this->autoLayout = false;
}
}
/**
* Merge components, helpers, and uses vars from AppController and PluginAppController.
*
@ -523,43 +555,10 @@ class Controller extends Object {
*
* @return mixed Associative array of the HTTP codes as keys, and the message
* strings as values, or null of the given $code does not exist.
* @deprecated
*/
public function httpCodes($code = null) {
if (empty($this->__httpCodes)) {
$this->__httpCodes = array(
100 => 'Continue', 101 => 'Switching Protocols',
200 => 'OK', 201 => 'Created', 202 => 'Accepted',
203 => 'Non-Authoritative Information', 204 => 'No Content',
205 => 'Reset Content', 206 => 'Partial Content',
300 => 'Multiple Choices', 301 => 'Moved Permanently',
302 => 'Found', 303 => 'See Other',
304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required',
403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed',
406 => 'Not Acceptable', 407 => 'Proxy Authentication Required',
408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone',
411 => 'Length Required', 412 => 'Precondition Failed',
413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable',
417 => 'Expectation Failed', 500 => 'Internal Server Error',
501 => 'Not Implemented', 502 => 'Bad Gateway',
503 => 'Service Unavailable', 504 => 'Gateway Time-out'
);
}
if (empty($code)) {
return $this->__httpCodes;
}
if (is_array($code)) {
$this->__httpCodes = $code + $this->__httpCodes;
return true;
}
if (!isset($this->__httpCodes[$code])) {
return null;
}
return array($code => $this->__httpCodes[$code]);
return $this->response->httpCodes($code);
}
/**
@ -652,51 +651,36 @@ class Controller extends Object {
session_write_close();
}
if (!empty($status)) {
$codes = $this->httpCodes();
if (is_string($status)) {
$codes = array_flip($codes);
}
if (!empty($status) && is_string($status)) {
$codes = array_flip($this->response->httpCodes());
if (isset($codes[$status])) {
$code = $msg = $codes[$status];
if (is_numeric($status)) {
$code = $status;
}
if (is_string($status)) {
$msg = $status;
}
$status = "HTTP/1.1 {$code} {$msg}";
} else {
$status = null;
$status = $codes[$status];
}
$this->header($status);
}
if ($url !== null) {
$this->header('Location: ' . Router::url($url, true));
$this->response->header('Location', Router::url($url, true));
}
if (!empty($status) && ($status >= 300 && $status < 400)) {
$this->header($status);
$this->response->statusCode($status);
}
if ($exit) {
$this->response->send();
$this->_stop();
}
}
/**
* Convenience and object wrapper method for header(). Useful when doing tests and
* asserting that particular headers have been set.
* Convenience and object wrapper method for CakeResponse::header().
*
* @param string $status The header message that is being set.
* @return void
* @deprecated
*/
public function header($status) {
header($status);
$this->response->header($status);
}
/**
@ -853,10 +837,8 @@ class Controller extends Object {
}
$this->autoRender = false;
$this->output .= $View->render($action, $layout, $file);
$this->View = $View;
return $this->output;
return $this->response->body($View->render($action, $layout, $file));
}
/**
@ -868,23 +850,12 @@ class Controller extends Object {
* @link http://book.cakephp.org/view/987/referer
*/
public function referer($default = null, $local = false) {
$ref = env('HTTP_REFERER');
if (!empty($ref) && defined('FULL_BASE_URL')) {
$base = FULL_BASE_URL . $this->webroot;
if (strpos($ref, $base) === 0) {
$return = substr($ref, strlen($base));
if ($return[0] != '/') {
$return = '/'.$return;
}
return $return;
} elseif (!$local) {
return $ref;
if ($this->request) {
$referer = $this->request->referer($local);
if ($referer == '/' && $default != null) {
return Router::url($default, true);
}
}
if ($default != null) {
$url = Router::url($default, true);
return $url;
return $referer;
}
return '/';
}
@ -894,13 +865,10 @@ class Controller extends Object {
*
* @return void
* @link http://book.cakephp.org/view/988/disableCache
* @deprecated
*/
public function disableCache() {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$this->response->disableCache();
}
/**
@ -921,7 +889,7 @@ class Controller extends Object {
$this->set('message', $message);
$this->set('pause', $pause);
$this->set('page_title', $message);
$this->render(false, $layout);
$this->response->body($this->render(false, $layout));
}
/**
@ -1043,7 +1011,7 @@ class Controller extends Object {
), E_USER_WARNING);
return array();
}
$options = array_merge($this->params, $this->params['url'], $this->passedArgs);
$options = array_merge($this->request->params, $this->params['url'], $this->passedArgs);
if (isset($this->paginate[$object->alias])) {
$defaults = $this->paginate[$object->alias];
@ -1174,7 +1142,13 @@ class Controller extends Object {
'defaults' => array_merge(array('limit' => 20, 'step' => 1), $defaults),
'options' => $options
);
$this->params['paging'][$object->alias] = $paging;
if (!isset($this->request['paging'])) {
$this->request['paging'] = array();
}
$this->request['paging'] = array_merge(
(array)$this->request['paging'],
array($object->alias => $paging)
);
if (!in_array('Paginator', $this->helpers) && !array_key_exists('Paginator', $this->helpers)) {
$this->helpers[] = 'Paginator';

View file

@ -31,13 +31,12 @@
* @package cake
* @subpackage cake.cake.libs.controller
*/
class Scaffold extends Object {
class Scaffold {
/**
* Controller object
*
* @var Controller
* @access public
*/
public $controller = null;
@ -45,23 +44,13 @@ class Scaffold extends Object {
* Name of the controller to scaffold
*
* @var string
* @access public
*/
public $name = null;
/**
* Action to be performed.
*
* @var string
* @access public
*/
public $action = null;
/**
* Name of current model this view context is attached to
*
* @var string
* @access public
*/
public $model = null;
@ -69,57 +58,22 @@ class Scaffold extends Object {
* Path to View.
*
* @var string
* @access public
*/
public $viewPath;
/**
* Path parts for creating links in views.
*
* @var string Base URL
* @access public
*/
public $base = null;
/**
* Name of layout to use with this View.
*
* @var string
* @access public
*/
public $layout = 'default';
/**
* Array of parameter data
* Request object
*
* @var array
* @access public
* @var CakeRequest
*/
public $params;
/**
* File extension. Defaults to Cake's template ".ctp".
*
* @var array
* @access public
*/
public $ext = '.ctp';
/**
* Sub-directory for this view file.
*
* @var string
* @access public
*/
public $subDir = null;
/**
* Plugin name.
*
* @var string
* @access public
*/
public $plugin = null;
public $request;
/**
* valid session.
@ -136,8 +90,7 @@ class Scaffold extends Object {
* @access private
*/
private $__passedVars = array(
'action', 'base', 'webroot', 'layout', 'name',
'viewPath', 'ext', 'params', 'data', 'plugin', 'cacheAction'
'layout', 'name', 'viewPath', 'request'
);
/**
@ -151,11 +104,11 @@ class Scaffold extends Object {
/**
* Construct and set up given controller with given parameters.
*
* @param string $controller_class Name of controller
* @param array $params Parameters for scaffolding
* @param Controller $controller Controller to scaffold
* @param CakeRequest $request Request parameters.
*/
function __construct(&$controller, $params) {
$this->controller =& $controller;
function __construct(Controller $controller, CakeRequest $request) {
$this->controller = $controller;
$count = count($this->__passedVars);
for ($j = 0; $j < $count; $j++) {
@ -170,14 +123,16 @@ class Scaffold extends Object {
if (!is_object($this->controller->{$this->modelClass})) {
return $this->cakeError('missingModel', array(array(
'className' => $this->modelClass, 'webroot' => '', 'base' => $controller->base
'className' => $this->modelClass,
'webroot' => $request->webroot,
'base' => $request->base
)));
}
$this->ScaffoldModel =& $this->controller->{$this->modelClass};
$this->ScaffoldModel = $this->controller->{$this->modelClass};
$this->scaffoldTitle = Inflector::humanize($this->viewPath);
$this->scaffoldActions = $controller->scaffold;
$title_for_layout = __('Scaffold :: ') . Inflector::humanize($this->action) . ' :: ' . $this->scaffoldTitle;
$title_for_layout = __('Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle;
$modelClass = $this->controller->modelClass;
$primaryKey = $this->ScaffoldModel->primaryKey;
$displayField = $this->ScaffoldModel->displayField;
@ -186,7 +141,7 @@ class Scaffold extends Object {
$singularHumanName = Inflector::humanize(Inflector::underscore($modelClass));
$pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name));
$scaffoldFields = array_keys($this->ScaffoldModel->schema());
$associations = $this->__associations();
$associations = $this->_associations();
$this->controller->set(compact(
'title_for_layout', 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
@ -199,7 +154,7 @@ class Scaffold extends Object {
$this->_validSession = (
isset($this->controller->Session) && $this->controller->Session->valid() != false
);
$this->__scaffold($params);
$this->_scaffold($request);
}
/**
@ -215,32 +170,27 @@ class Scaffold extends Object {
/**
* Renders a view action of scaffolded model.
*
* @param array $params Parameters for scaffolding
* @param CakeRequest $request Request Object for scaffolding
* @return mixed A rendered view of a row from Models database table
* @access private
*/
function __scaffoldView($params) {
protected function _scaffoldView(CakeRequest $request) {
if ($this->controller->_beforeScaffold('view')) {
$message = __(sprintf("No id set for %s::view()", Inflector::humanize($this->modelKey)));
if (isset($params['pass'][0])) {
$this->ScaffoldModel->id = $params['pass'][0];
} elseif ($this->_validSession) {
$this->controller->Session->setFlash($message);
$this->controller->redirect($this->redirect);
if (isset($request->params['pass'][0])) {
$this->ScaffoldModel->id = $request->params['pass'][0];
} else {
return $this->controller->flash($message, '/' . Inflector::underscore($this->controller->viewPath));
return $this->_sendMessage($message);
}
$this->ScaffoldModel->recursive = 1;
$this->controller->data = $this->ScaffoldModel->read();
$this->controller->request->data = $this->controller->data = $this->ScaffoldModel->read();
$this->controller->set(
Inflector::variable($this->controller->modelClass), $this->controller->data
Inflector::variable($this->controller->modelClass), $this->request->data
);
$this->controller->render($this->action, $this->layout);
$this->controller->render($this->request['action'], $this->layout);
$this->_output();
} elseif ($this->controller->_scaffoldError('view') === false) {
return $this->__scaffoldError();
return $this->_scaffoldError();
}
}
@ -249,18 +199,17 @@ class Scaffold extends Object {
*
* @param array $params Parameters for scaffolding
* @return mixed A rendered view listing rows from Models database table
* @access private
*/
function __scaffoldIndex($params) {
protected function _scaffoldIndex($params) {
if ($this->controller->_beforeScaffold('index')) {
$this->ScaffoldModel->recursive = 0;
$this->controller->set(
Inflector::variable($this->controller->name), $this->controller->paginate()
);
$this->controller->render($this->action, $this->layout);
$this->controller->render($this->request['action'], $this->layout);
$this->_output();
} elseif ($this->controller->_scaffoldError('index') === false) {
return $this->__scaffoldError();
return $this->_scaffoldError();
}
}
@ -269,9 +218,8 @@ class Scaffold extends Object {
*
* @param string $action Action (add or edit)
* @return mixed A rendered view with a form to edit or add a record in the Models database table
* @access private
*/
function __scaffoldForm($action = 'edit') {
protected function _scaffoldForm($action = 'edit') {
$this->controller->viewVars['scaffoldFields'] = array_merge(
$this->controller->viewVars['scaffoldFields'],
array_keys($this->ScaffoldModel->hasAndBelongsToMany)
@ -283,12 +231,11 @@ class Scaffold extends Object {
/**
* Saves or updates the scaffolded model.
*
* @param array $params Parameters for scaffolding
* @param CakeRequest $request Request Object for scaffolding
* @param string $action add or edt
* @return mixed Success on save/update, add/edit form if data is empty or error if save or update fails
* @access private
*/
function __scaffoldSave($params = array(), $action = 'edit') {
protected function _scaffoldSave(CakeRequest $request, $action = 'edit') {
$formAction = 'edit';
$success = __('updated');
if ($action === 'add') {
@ -298,39 +245,27 @@ class Scaffold extends Object {
if ($this->controller->_beforeScaffold($action)) {
if ($action == 'edit') {
if (isset($params['pass'][0])) {
$this->ScaffoldModel->id = $params['pass'][0];
if (isset($request->params['pass'][0])) {
$this->ScaffoldModel->id = $request['pass'][0];
}
if (!$this->ScaffoldModel->exists()) {
$message = __(sprintf("Invalid id for %s::edit()", Inflector::humanize($this->modelKey)));
if ($this->_validSession) {
$this->controller->Session->setFlash($message);
$this->controller->redirect($this->redirect);
} else {
$this->controller->flash($message, $this->redirect);
$this->_output();
}
return $this->_sendMessage($message);
}
}
if (!empty($this->controller->data)) {
if (!empty($request->data)) {
if ($action == 'create') {
$this->ScaffoldModel->create();
}
if ($this->ScaffoldModel->save($this->controller->data)) {
if ($this->ScaffoldModel->save($request->data)) {
if ($this->controller->_afterScaffoldSave($action)) {
$message = __(
sprintf('The %1$s has been %2$s', Inflector::humanize($this->modelKey), $success)
);
if ($this->_validSession) {
$this->controller->Session->setFlash($message);
$this->controller->redirect($this->redirect);
} else {
$this->controller->flash($message, $this->redirect);
return $this->_output();
}
return $this->_sendMessage($message);
} else {
return $this->controller->_afterScaffoldSaveError($action);
}
@ -341,11 +276,11 @@ class Scaffold extends Object {
}
}
if (empty($this->controller->data)) {
if (empty($request->data)) {
if ($this->ScaffoldModel->id) {
$this->controller->data = $this->ScaffoldModel->read();
$this->controller->data = $request->data = $this->ScaffoldModel->read();
} else {
$this->controller->data = $this->ScaffoldModel->create();
$this->controller->data = $request->data = $this->ScaffoldModel->create();
}
}
@ -360,9 +295,9 @@ class Scaffold extends Object {
$this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
}
return $this->__scaffoldForm($formAction);
return $this->_scaffoldForm($formAction);
} elseif ($this->controller->_scaffoldError($action) === false) {
return $this->__scaffoldError();
return $this->_scaffoldError();
}
}
@ -371,49 +306,49 @@ class Scaffold extends Object {
*
* @param array $params Parameters for scaffolding
* @return mixed Success on delete, error if delete fails
* @access private
*/
function __scaffoldDelete($params = array()) {
protected function _scaffoldDelete(CakeRequest $request) {
if ($this->controller->_beforeScaffold('delete')) {
$message = __(
sprintf("No id set for %s::delete()", Inflector::humanize($this->modelKey))
);
if (isset($params['pass'][0])) {
$id = $params['pass'][0];
} elseif ($this->_validSession) {
$this->controller->Session->setFlash($message);
$this->controller->redirect($this->redirect);
if (isset($request->params['pass'][0])) {
$id = $request->params['pass'][0];
} else {
$this->controller->flash($message, $this->redirect);
return $this->_output();
return $this->_sendMessage($message);
}
if ($this->ScaffoldModel->delete($id)) {
$message = __(
sprintf('The %1$s with id: %2$d has been deleted.', Inflector::humanize($this->modelClass), $id)
);
if ($this->_validSession) {
$this->controller->Session->setFlash($message);
$this->controller->redirect($this->redirect);
} else {
$this->controller->flash($message, $this->redirect);
return $this->_output();
}
return $this->_sendMessage($message);
} else {
$message = __(sprintf(
'There was an error deleting the %1$s with id: %2$d',
Inflector::humanize($this->modelClass), $id
));
if ($this->_validSession) {
$this->controller->Session->setFlash($message);
$this->controller->redirect($this->redirect);
} else {
$this->controller->flash($message, $this->redirect);
return $this->_output();
}
return $this->_sendMessage($message);
}
} elseif ($this->controller->_scaffoldError('delete') === false) {
return $this->__scaffoldError();
return $this->_scaffoldError();
}
}
/**
* Sends a message to the user. Either uses Sessions or flash messages depending
* on the availability of a session
*
* @param string $message Message to display
* @return void
*/
protected function _sendMessage($message) {
if ($this->_validSession) {
$this->controller->Session->setFlash($message);
$this->controller->redirect($this->redirect);
} else {
$this->controller->flash($message, $this->redirect);
$this->_output();
}
}
@ -421,9 +356,8 @@ class Scaffold extends Object {
* Show a scaffold error
*
* @return mixed A rendered view showing the error
* @access private
*/
function __scaffoldError() {
protected function _scaffoldError() {
return $this->controller->render('error', $this->layout);
$this->_output();
}
@ -433,12 +367,11 @@ class Scaffold extends Object {
* scaffoldView is used to call default Scaffold methods if:
* `public $scaffold;` is placed in the controller's class definition.
*
* @param array $params Parameters for scaffolding
* @param CakeRequest $request Request object for scaffolding
* @return mixed A rendered view of scaffold action, or showing the error
* @access private
*/
function __scaffold($params) {
$db = &ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
protected function _scaffold(CakeRequest $request) {
$db = ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig);
$prefixes = Configure::read('Routing.prefixes');
$scaffoldPrefix = $this->scaffoldActions;
@ -460,41 +393,41 @@ class Scaffold extends Object {
);
}
if (in_array($params['action'], $this->scaffoldActions)) {
if (in_array($request->params['action'], $this->scaffoldActions)) {
if (!empty($prefixes)) {
$params['action'] = str_replace($scaffoldPrefix . '_', '', $params['action']);
$request->params['action'] = str_replace($scaffoldPrefix . '_', '', $request->params['action']);
}
switch ($params['action']) {
switch ($request->params['action']) {
case 'index':
case 'list':
$this->__scaffoldIndex($params);
$this->_scaffoldIndex($request);
break;
case 'view':
$this->__scaffoldView($params);
$this->_scaffoldView($request);
break;
case 'add':
case 'create':
$this->__scaffoldSave($params, 'add');
$this->_scaffoldSave($request, 'add');
break;
case 'edit':
case 'update':
$this->__scaffoldSave($params, 'edit');
$this->_scaffoldSave($request, 'edit');
break;
case 'delete':
$this->__scaffoldDelete($params);
$this->_scaffoldDelete($request);
break;
}
} else {
return $this->cakeError('missingAction', array(array(
'className' => $this->controller->name . "Controller",
'base' => $this->controller->base,
'action' => $this->action,
'webroot' => $this->controller->webroot
'base' => $request->base,
'action' => $request->action,
'webroot' => $request->webroot
)));
}
} else {
return $this->cakeError('missingDatabase', array(array(
'webroot' => $this->controller->webroot
'webroot' => $request->webroot
)));
}
}
@ -503,9 +436,8 @@ class Scaffold extends Object {
* Returns associations for controllers models.
*
* @return array Associations for model
* @access private
*/
function __associations() {
protected function _associations() {
$keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
$associations = array();

View file

@ -48,7 +48,7 @@ class CakeErrorController extends AppController {
function __construct() {
parent::__construct();
$this->_set(Router::getPaths());
$this->params = Router::getParams();
$this->request = $this->params = Router::getRequest();
$this->constructClasses();
$this->Component->initialize($this);
$this->_set(array('cacheAction' => false, 'viewPath' => 'errors'));
@ -87,9 +87,9 @@ class ErrorHandler extends Object {
if ($__previousError != array($method, $messages)) {
$__previousError = array($method, $messages);
$this->controller =& new CakeErrorController();
$this->controller = new CakeErrorController();
} else {
$this->controller =& new Controller();
$this->controller = new Controller();
$this->controller->viewPath = 'errors';
}
$options = array('escape' => false);
@ -158,7 +158,7 @@ class ErrorHandler extends Object {
'code' => '404',
'name' => __('Not Found'),
'message' => h($url),
'base' => $this->controller->base
'base' => $this->controller->request->base
));
$this->_outputMessage('error404');
}
@ -172,7 +172,7 @@ class ErrorHandler extends Object {
extract($params, EXTR_OVERWRITE);
if (!isset($url)) {
$url = $this->controller->here;
$url = $this->controller->request->here;
}
$url = Router::normalize($url);
$this->controller->header("HTTP/1.0 500 Internal Server Error");
@ -180,7 +180,7 @@ class ErrorHandler extends Object {
'code' => '500',
'name' => __('An Internal Error Has Occurred'),
'message' => h($url),
'base' => $this->controller->base
'base' => $this->controller->request->base
));
$this->_outputMessage('error500');
}

View file

@ -0,0 +1,371 @@
<?php
/**
* A single Route used by the Router to connect requests to
* parameter maps.
*
* Not normally created as a standalone. Use Router::connect() to create
* Routes for your application.
*
* PHP5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class CakeRoute {
/**
* An array of named segments in a Route.
* `/:controller/:action/:id` has 3 key elements
*
* @var array
* @access public
*/
public $keys = array();
/**
* An array of additional parameters for the Route.
*
* @var array
* @access public
*/
public $options = array();
/**
* Default parameters for a Route
*
* @var array
* @access public
*/
public $defaults = array();
/**
* The routes template string.
*
* @var string
* @access public
*/
public $template = null;
/**
* Is this route a greedy route? Greedy routes have a `/*` in their
* template
*
* @var string
* @access protected
*/
protected $_greedy = false;
/**
* The compiled route regular expresssion
*
* @var string
* @access protected
*/
protected $_compiledRoute = null;
/**
* HTTP header shortcut map. Used for evaluating header-based route expressions.
*
* @var array
* @access private
*/
private $__headerMap = array(
'type' => 'content_type',
'method' => 'request_method',
'server' => 'server_name'
);
/**
* Constructor for a Route
*
* @param string $template Template string with parameter placeholders
* @param array $defaults Array of defaults for the route.
* @param string $params Array of parameters and additional options for the Route
* @return void
*/
public function __construct($template, $defaults = array(), $options = array()) {
$this->template = $template;
$this->defaults = (array)$defaults;
$this->options = (array)$options;
}
/**
* Check if a Route has been compiled into a regular expression.
*
* @return boolean
*/
public function compiled() {
return !empty($this->_compiledRoute);
}
/**
* Compiles the route's regular expression. Modifies defaults property so all necessary keys are set
* and populates $this->names with the named routing elements.
*
* @return array Returns a string regular expression of the compiled route.
*/
public function compile() {
if ($this->compiled()) {
return $this->_compiledRoute;
}
$this->_writeRoute();
return $this->_compiledRoute;
}
/**
* Builds a route regular expression. Uses the template, defaults and options
* properties to compile a regular expression that can be used to parse request strings.
*
* @return void
*/
protected function _writeRoute() {
if (empty($this->template) || ($this->template === '/')) {
$this->_compiledRoute = '#^/*$#';
$this->keys = array();
return;
}
$route = $this->template;
$names = $routeParams = array();
$parsed = preg_quote($this->template, '#');
preg_match_all('#:([A-Za-z0-9_-]+[A-Z0-9a-z])#', $route, $namedElements);
foreach ($namedElements[1] as $i => $name) {
$search = '\\' . $namedElements[0][$i];
if (isset($this->options[$name])) {
$option = null;
if ($name !== 'plugin' && array_key_exists($name, $this->defaults)) {
$option = '?';
}
$slashParam = '/\\' . $namedElements[0][$i];
if (strpos($parsed, $slashParam) !== false) {
$routeParams[$slashParam] = '(?:/(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option;
} else {
$routeParams[$search] = '(?:(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option;
}
} else {
$routeParams[$search] = '(?:(?P<' . $name . '>[^/]+))';
}
$names[] = $name;
}
if (preg_match('#\/\*$#', $route, $m)) {
$parsed = preg_replace('#/\\\\\*$#', '(?:/(?P<_args_>.*))?', $parsed);
$this->_greedy = true;
}
krsort($routeParams);
$parsed = str_replace(array_keys($routeParams), array_values($routeParams), $parsed);
$this->_compiledRoute = '#^' . $parsed . '[/]*$#';
$this->keys = $names;
}
/**
* Checks to see if the given URL can be parsed by this route.
* If the route can be parsed an array of parameters will be returned if not
* false will be returned. String urls are parsed if they match a routes regular expression.
*
* @param string $url The url to attempt to parse.
* @return mixed Boolean false on failure, otherwise an array or parameters
*/
public function parse($url) {
if (!$this->compiled()) {
$this->compile();
}
if (!preg_match($this->_compiledRoute, $url, $route)) {
return false;
} else {
foreach ($this->defaults as $key => $val) {
if ($key[0] === '[' && preg_match('/^\[(\w+)\]$/', $key, $header)) {
if (isset($this->__headerMap[$header[1]])) {
$header = $this->__headerMap[$header[1]];
} else {
$header = 'http_' . $header[1];
}
$val = (array)$val;
$h = false;
foreach ($val as $v) {
if (env(strtoupper($header)) === $v) {
$h = true;
}
}
if (!$h) {
return false;
}
}
}
array_shift($route);
$count = count($this->keys);
for ($i = 0; $i <= $count; $i++) {
unset($route[$i]);
}
$route['pass'] = $route['named'] = array();
$route += $this->defaults;
//move numerically indexed elements from the defaults into pass.
foreach ($route as $key => $value) {
if (is_integer($key)) {
$route['pass'][] = $value;
unset($route[$key]);
}
}
return $route;
}
}
/**
* Apply persistent parameters to a url array. Persistant parameters are a special
* key used during route creation to force route parameters to persist when omitted from
* a url array.
*
* @param array $url The array to apply persistent parameters to.
* @param array $params An array of persistent values to replace persistent ones.
* @return array An array with persistent parameters applied.
*/
public function persistParams($url, $params) {
foreach ($this->options['persist'] as $persistKey) {
if (array_key_exists($persistKey, $params) && !isset($url[$persistKey])) {
$url[$persistKey] = $params[$persistKey];
}
}
return $url;
}
/**
* Attempt to match a url array. If the url matches the route parameters + settings, then
* return a generated string url. If the url doesn't match the route parameters false will be returned.
* This method handles the reverse routing or conversion of url arrays into string urls.
*
* @param array $url An array of parameters to check matching with.
* @return mixed Either a string url for the parameters if they match or false.
*/
public function match($url) {
if (!$this->compiled()) {
$this->compile();
}
$defaults = $this->defaults;
if (isset($defaults['prefix'])) {
$url['prefix'] = $defaults['prefix'];
}
//check that all the key names are in the url
$keyNames = array_flip($this->keys);
if (array_intersect_key($keyNames, $url) != $keyNames) {
return false;
}
$diffUnfiltered = Set::diff($url, $defaults);
$diff = array();
foreach ($diffUnfiltered as $key => $var) {
if ($var === 0 || $var === '0' || !empty($var)) {
$diff[$key] = $var;
}
}
//if a not a greedy route, no extra params are allowed.
if (!$this->_greedy && array_diff_key($diff, $keyNames) != array()) {
return false;
}
//remove defaults that are also keys. They can cause match failures
foreach ($this->keys as $key) {
unset($defaults[$key]);
}
$filteredDefaults = array_filter($defaults);
//if the difference between the url diff and defaults contains keys from defaults its not a match
if (array_intersect_key($filteredDefaults, $diffUnfiltered) !== array()) {
return false;
}
$passedArgsAndParams = array_diff_key($diff, $filteredDefaults, $keyNames);
list($named, $params) = Router::getNamedElements($passedArgsAndParams, $url['controller'], $url['action']);
//remove any pass params, they have numeric indexes, skip any params that are in the defaults
$pass = array();
$i = 0;
while (isset($url[$i])) {
if (!isset($diff[$i])) {
$i++;
continue;
}
$pass[] = $url[$i];
unset($url[$i], $params[$i]);
$i++;
}
//still some left over parameters that weren't named or passed args, bail.
if (!empty($params)) {
return false;
}
//check patterns for routed params
if (!empty($this->options)) {
foreach ($this->options as $key => $pattern) {
if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) {
return false;
}
}
}
return $this->_writeUrl(array_merge($url, compact('pass', 'named')));
}
/**
* Converts a matching route array into a url string. Composes the string url using the template
* used to create the route.
*
* @param array $params The params to convert to a string url.
* @return string Composed route string.
*/
protected function _writeUrl($params) {
if (isset($params['prefix'], $params['action'])) {
$params['action'] = str_replace($params['prefix'] . '_', '', $params['action']);
unset($params['prefix']);
}
if (is_array($params['pass'])) {
$params['pass'] = implode('/', $params['pass']);
}
$separator = Router::$named['separator'];
if (!empty($params['named']) && is_array($params['named'])) {
$named = array();
foreach ($params['named'] as $key => $value) {
$named[] = $key . $separator . $value;
}
$params['pass'] = $params['pass'] . '/' . implode('/', $named);
}
$out = $this->template;
$search = $replace = array();
foreach ($this->keys as $key) {
$string = null;
if (isset($params[$key])) {
$string = $params[$key];
} elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
$key .= '/';
}
$search[] = ':' . $key;
$replace[] = $string;
}
$out = str_replace($search, $replace, $out);
if (strpos($this->template, '*')) {
$out = str_replace('*', $params['pass'], $out);
}
$out = str_replace('//', '/', $out);
return $out;
}
}

View file

@ -0,0 +1,56 @@
<?php
App::import('Core', 'route/CakeRoute');
/**
* Plugin short route, that copies the plugin param to the controller parameters
* It is used for supporting /:plugin routes.
*
* PHP5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class PluginShortRoute extends CakeRoute {
/**
* Parses a string url into an array. If a plugin key is found, it will be copied to the
* controller parameter
*
* @param string $url The url to parse
* @return mixed false on failure, or an array of request parameters
*/
public function parse($url) {
$params = parent::parse($url);
if (!$params) {
return false;
}
$params['controller'] = $params['plugin'];
return $params;
}
/**
* Reverse route plugin shortcut urls. If the plugin and controller
* are not the same the match is an auto fail.
*
* @param array $url Array of parameters to convert to a string.
* @return mixed either false or a string url.
*/
public function match($url) {
if (isset($url['controller']) && isset($url['plugin']) && $url['plugin'] != $url['controller']) {
return false;
}
$this->defaults['controller'] = $url['controller'];
$result = parent::match($url);
unset($this->defaults['controller']);
return $result;
}
}

File diff suppressed because it is too large Load diff

View file

@ -17,7 +17,7 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<h2><?php __('Missing Behavior Class'); ?></h2>
<h2><?php echo __('Missing Behavior Class'); ?></h2>
<p class="error">
<strong><?php echo __('Error'); ?>: </strong>
<?php printf(__('The behavior class <em>%s</em> can not be found or does not exist.'), $behaviorClass); ?>

View file

@ -50,6 +50,7 @@ class Helper extends Object {
/**
* Base URL
*
* @deprecated use $request->base instead
* @var string
*/
public $base = null;
@ -57,6 +58,7 @@ class Helper extends Object {
/**
* Webroot path
*
* @deprecated use $request->webroot instead
* @var string
*/
public $webroot = null;
@ -71,6 +73,7 @@ class Helper extends Object {
/**
* URL to current action.
*
* @deprecated use $request->here instead
* @var string
*/
public $here = null;
@ -78,13 +81,22 @@ class Helper extends Object {
/**
* Parameter array.
*
* @deprecated use $request instead
* @var array
*/
public $params = array();
/**
* Request object
*
* @var CakeRequest
*/
public $request = null;
/**
* Current action.
*
* @deprecated use $request->action instead
* @var string
*/
public $action = null;
@ -99,24 +111,11 @@ class Helper extends Object {
/**
* POST data for models
*
* @deprecated use $request->data instead
* @var array
*/
public $data = null;
/**
* List of named arguments
*
* @var array
*/
public $namedArgs = null;
/**
* URL argument separator character
*
* @var string
*/
public $argSeparator = null;
/**
* Contains model validation errors of form post-backs
*
@ -238,7 +237,7 @@ class Helper extends Object {
public function webroot($file) {
$asset = explode('?', $file);
$asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
$webPath = "{$this->webroot}" . $asset[0];
$webPath = "{$this->request->webroot}" . $asset[0];
$file = $asset[0];
if (!empty($this->theme)) {
@ -250,7 +249,7 @@ class Helper extends Object {
}
if (file_exists(Configure::read('App.www_root') . 'theme' . DS . $this->theme . DS . $file)) {
$webPath = "{$this->webroot}theme/" . $theme . $asset[0];
$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
} else {
$viewPaths = App::path('views');
@ -258,7 +257,7 @@ class Helper extends Object {
$path = $viewPath . 'themed'. DS . $this->theme . DS . 'webroot' . DS . $file;
if (file_exists($path)) {
$webPath = "{$this->webroot}theme/" . $theme . $asset[0];
$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
break;
}
}
@ -284,7 +283,7 @@ class Helper extends Object {
Configure::read('Asset.timestamp') === 'force'
);
if (strpos($path, '?') === false && $timestampEnabled) {
$filepath = preg_replace('/^' . preg_quote($this->webroot, '/') . '/', '', $path);
$filepath = preg_replace('/^' . preg_quote($this->request->webroot, '/') . '/', '', $path);
$webrootPath = WWW_ROOT . str_replace('/', DS, $filepath);
if (file_exists($webrootPath)) {
return $path . '?' . @filemtime($webrootPath);
@ -720,6 +719,7 @@ class Helper extends Object {
$this->setEntity($field);
}
$result = null;
$data = $this->request->data;
$entity = $this->_View->entity();
if (!empty($this->data) && !empty($entity)) {
@ -727,12 +727,12 @@ class Helper extends Object {
}
$habtmKey = $this->field();
if (empty($result) && isset($this->data[$habtmKey][$habtmKey])) {
if (empty($result) && isset($data[$habtmKey][$habtmKey])) {
$result = $this->data[$habtmKey][$habtmKey];
} elseif (empty($result) && isset($this->data[$habtmKey]) && is_array($this->data[$habtmKey])) {
} elseif (empty($result) && isset($data[$habtmKey]) && is_array($data[$habtmKey])) {
if (ClassRegistry::isKeySet($habtmKey)) {
$model =& ClassRegistry::getObject($habtmKey);
$result = $this->__selectedArray($this->data[$habtmKey], $model->primaryKey);
$result = $this->__selectedArray($data[$habtmKey], $model->primaryKey);
}
}
@ -863,11 +863,11 @@ class Helper extends Object {
function __selectedArray($data, $key = 'id') {
if (!is_array($data)) {
$model = $data;
if (!empty($this->data[$model][$model])) {
return $this->data[$model][$model];
if (!empty($this->request->data[$model][$model])) {
return $this->request->data[$model][$model];
}
if (!empty($this->data[$model])) {
$data = $this->data[$model];
if (!empty($this->request->data[$model])) {
$data = $this->request->data[$model];
}
}
$array = array();

View file

@ -72,13 +72,13 @@ class CacheHelper extends AppHelper {
$index = null;
foreach ($keys as $action) {
if ($action == $this->params['action']) {
if ($action == $this->request->params['action']) {
$index = $action;
break;
}
}
if (!isset($index) && $this->action == 'index') {
if (!isset($index) && $this->request->params['action'] == 'index') {
$index = 'index';
}
@ -201,7 +201,7 @@ class CacheHelper extends AppHelper {
} else {
$cacheTime = strtotime($timestamp, $now);
}
$path = $this->here;
$path = $this->request->here;
if ($this->here == '/') {
$path = 'home';
}
@ -230,11 +230,12 @@ class CacheHelper extends AppHelper {
$controller->layout = $this->layout = \'' . $this->layout. '\';
$controller->webroot = $this->webroot = \'' . $this->webroot . '\';
$controller->here = $this->here = \'' . $this->here . '\';
$controller->params = $this->params = unserialize(stripslashes(\'' . addslashes(serialize($this->params)) . '\'));
$controller->params = $this->params = unserialize(\'' . str_replace("'", "\\'", serialize($this->params)) . '\');
$controller->request = $this->request = unserialize(\'' . str_replace("'", "\\'", serialize($this->request)) . '\');
$controller->action = $this->action = unserialize(\'' . serialize($this->action) . '\');
$controller->data = $this->data = unserialize(stripslashes(\'' . addslashes(serialize($this->data)) . '\'));
$controller->data = $this->data = unserialize(\'' . str_replace("'", "\\'", serialize($this->data)) . '\');
$controller->theme = $this->theme = \'' . $this->theme . '\';
Router::setRequestInfo(array($this->params, array(\'base\' => $this->base, \'webroot\' => $this->webroot)));';
Router::setRequestInfo($this->params);';
if ($useCallbacks == true) {
$file .= '

View file

@ -193,10 +193,10 @@ class FormHelper extends AppHelper {
$options = $model;
$model = null;
}
if (empty($model) && $model !== false && !empty($this->params['models'])) {
$model = $this->params['models'][0];
$this->defaultModel = $this->params['models'][0];
} elseif (empty($model) && empty($this->params['models'])) {
if (empty($model) && $model !== false && !empty($this->request['models'])) {
$model = $this->request['models'][0];
$this->defaultModel = $this->request['models'][0];
} elseif (empty($model) && empty($this->request['models'])) {
$model = false;
}
@ -217,13 +217,13 @@ class FormHelper extends AppHelper {
if (isset($this->fieldset[$modelEntity]['key'])) {
$data = $this->fieldset[$modelEntity];
$recordExists = (
isset($this->data[$model]) &&
!empty($this->data[$model][$data['key']])
isset($this->request->data[$model]) &&
!empty($this->request->data[$model][$data['key']])
);
if ($recordExists) {
$created = true;
$id = $this->data[$model][$data['key']];
$id = $this->request->data[$model][$data['key']];
}
}
@ -242,12 +242,12 @@ class FormHelper extends AppHelper {
if (empty($options['url']['controller'])) {
if (!empty($model) && $model != $this->defaultModel) {
$options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
} elseif (!empty($this->params['controller'])) {
$options['url']['controller'] = Inflector::underscore($this->params['controller']);
} elseif (!empty($this->request['controller'])) {
$options['url']['controller'] = Inflector::underscore($this->request['controller']);
}
}
if (empty($options['action'])) {
$options['action'] = $this->params['action'];
$options['action'] = $this->request['action'];
}
$actionDefaults = array(
@ -304,9 +304,9 @@ class FormHelper extends AppHelper {
$htmlAttributes = array_merge($options, $htmlAttributes);
$this->fields = array();
if (isset($this->params['_Token']) && !empty($this->params['_Token'])) {
if (isset($this->request['_Token']) && !empty($this->request['_Token'])) {
$append .= $this->hidden('_Token.key', array(
'value' => $this->params['_Token']['key'], 'id' => 'Token' . mt_rand())
'value' => $this->request['_Token']['key'], 'id' => 'Token' . mt_rand())
);
}
@ -341,8 +341,8 @@ class FormHelper extends AppHelper {
* @link http://book.cakephp.org/view/1389/Closing-the-Form
*/
public function end($options = null) {
if (!empty($this->params['models'])) {
$models = $this->params['models'][0];
if (!empty($this->request['models'])) {
$models = $this->request['models'][0];
}
$out = null;
$submit = null;
@ -364,7 +364,7 @@ class FormHelper extends AppHelper {
}
$out .= $this->submit($submit, $submitOptions);
}
if (isset($this->params['_Token']) && !empty($this->params['_Token'])) {
if (isset($this->request['_Token']) && !empty($this->request['_Token'])) {
$out .= $this->secure($this->fields);
$this->fields = array();
}
@ -382,7 +382,7 @@ class FormHelper extends AppHelper {
* @return string A hidden input field with a security hash
*/
public function secure($fields = array()) {
if (!isset($this->params['_Token']) || empty($this->params['_Token'])) {
if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
return;
}
$locked = array();
@ -424,8 +424,8 @@ class FormHelper extends AppHelper {
$field = Set::filter(explode('.', $field), true);
}
if (!empty($this->params['_Token']['disabledFields'])) {
foreach ((array)$this->params['_Token']['disabledFields'] as $disabled) {
if (!empty($this->request['_Token']['disabledFields'])) {
foreach ((array)$this->request['_Token']['disabledFields'] as $disabled) {
$disabled = explode('.', $disabled);
if (array_values(array_intersect($field, $disabled)) === $disabled) {
return;
@ -619,8 +619,8 @@ class FormHelper extends AppHelper {
if ($legend === true) {
$actionName = __('New %s');
$isEdit = (
strpos($this->action, 'update') !== false ||
strpos($this->action, 'edit') !== false
strpos($this->request->params['action'], 'update') !== false ||
strpos($this->request->params['action'], 'edit') !== false
);
if ($isEdit) {
$actionName = __('Edit %s');
@ -2169,7 +2169,7 @@ class FormHelper extends AppHelper {
$secure = $options['secure'];
unset($options['secure']);
} else {
$secure = (isset($this->params['_Token']) && !empty($this->params['_Token']));
$secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
}
$result = parent::_initInputField($field, $options);

View file

@ -202,7 +202,8 @@ class JsHelper extends AppHelper {
* scripts null will be returned.
*/
public function writeBuffer($options = array()) {
$domReady = isset($this->params['isAjax']) ? !$this->params['isAjax'] : true;
$domReady = $this->request->is('ajax');
// $domReady = isset($this->params['isAjax']) ? !$this->params['isAjax'] : true;
$defaults = array(
'onDomReady' => $domReady, 'inline' => true,
'cache' => false, 'clear' => true, 'safe' => true

View file

@ -111,7 +111,7 @@ class PaginatorHelper extends AppHelper {
* @return void
*/
public function beforeRender() {
$this->options['url'] = array_merge($this->params['pass'], $this->params['named']);
$this->options['url'] = array_merge($this->request->params['pass'], $this->request->params['named']);
parent::beforeRender();
}
@ -126,10 +126,10 @@ class PaginatorHelper extends AppHelper {
if (empty($model)) {
$model = $this->defaultModel();
}
if (!isset($this->params['paging']) || empty($this->params['paging'][$model])) {
if (!isset($this->request->params['paging']) || empty($this->request->params['paging'][$model])) {
return null;
}
return $this->params['paging'][$model];
return $this->request->params['paging'][$model];
}
/**
@ -145,20 +145,20 @@ class PaginatorHelper extends AppHelper {
}
if (!empty($options['paging'])) {
if (!isset($this->params['paging'])) {
$this->params['paging'] = array();
if (!isset($this->request->params['paging'])) {
$this->request->params['paging'] = array();
}
$this->params['paging'] = array_merge($this->params['paging'], $options['paging']);
$this->request->params['paging'] = array_merge($this->request->params['paging'], $options['paging']);
unset($options['paging']);
}
$model = $this->defaultModel();
if (!empty($options[$model])) {
if (!isset($this->params['paging'][$model])) {
$this->params['paging'][$model] = array();
if (!isset($this->request->params['paging'][$model])) {
$this->request->params['paging'][$model] = array();
}
$this->params['paging'][$model] = array_merge(
$this->params['paging'][$model], $options[$model]
$this->request->params['paging'][$model] = array_merge(
$this->request->params['paging'][$model], $options[$model]
);
unset($options[$model]);
}
@ -487,10 +487,10 @@ class PaginatorHelper extends AppHelper {
if ($this->__defaultModel != null) {
return $this->__defaultModel;
}
if (empty($this->params['paging'])) {
if (empty($this->request->params['paging'])) {
return null;
}
list($this->__defaultModel) = array_keys($this->params['paging']);
list($this->__defaultModel) = array_keys($this->request->params['paging']);
return $this->__defaultModel;
}

View file

@ -278,7 +278,7 @@ class View extends Object {
private $__passedVars = array(
'viewVars', 'action', 'autoLayout', 'autoRender', 'ext', 'base', 'webroot',
'helpers', 'here', 'layout', 'name', 'layoutPath', 'viewPath',
'params', 'data', 'plugin', 'passedArgs', 'cacheAction'
'params', 'request', 'data', 'plugin', 'passedArgs', 'cacheAction'
);
/**

File diff suppressed because it is too large Load diff

View file

@ -37,6 +37,8 @@ class AllRoutingTest extends PHPUnit_Framework_TestSuite {
$suite = new PHPUnit_Framework_TestSuite('All Router and Dispatcher class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'router.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'route' . DS . 'cake_route.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'route' . DS . 'plugin_short_route.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'dispatcher.test.php');
return $suite;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,352 @@
<?php
App::import('Core', 'CakeResponse');
class CakeResponseTestCase extends CakeTestCase {
/**
* Tests the request object constructor
*
*/
public function testConstruct() {
$response = new CakeResponse();
$this->assertNull($response->body());
$this->assertEquals($response->charset(), 'UTF-8');
$this->assertEquals($response->type(), 'text/html');
$this->assertEquals($response->statusCode(), 200);
$options = array(
'body' => 'This is the body',
'charset' => 'my-custom-charset',
'type' => 'mp3',
'status' => '203'
);
$response = new CakeResponse($options);
$this->assertEquals($response->body(), 'This is the body');
$this->assertEquals($response->charset(), 'my-custom-charset');
$this->assertEquals($response->type(), 'audio/mpeg');
$this->assertEquals($response->statusCode(), 203);
}
/**
* Tests the body method
*
*/
public function testBody() {
$response = new CakeResponse();
$this->assertNull($response->body());
$response->body('Response body');
$this->assertEquals($response->body(), 'Response body');
$this->assertEquals($response->body('Changed Body'), 'Changed Body');
}
/**
* Tests the charset method
*
*/
public function testCharset() {
$response = new CakeResponse();
$this->assertEquals($response->charset(), 'UTF-8');
$response->charset('iso-8859-1');
$this->assertEquals($response->charset(), 'iso-8859-1');
$this->assertEquals($response->charset('UTF-16'), 'UTF-16');
}
/**
* Tests the statusCode method
*
* @expectedException OutOfRangeException
*/
public function testStatusCode() {
$response = new CakeResponse();
$this->assertEquals($response->statusCode(), 200);
$response->statusCode(404);
$this->assertEquals($response->statusCode(), 404);
$this->assertEquals($response->statusCode(500), 500);
//Throws exception
$response->statusCode(1001);
}
/**
* Tests the type method
*
*/
public function testType() {
$response = new CakeResponse();
$this->assertEquals($response->type(), 'text/html');
$response->type('pdf');
$this->assertEquals($response->type(), 'application/pdf');
$this->assertEquals($response->type('application/crazy-mime'), 'application/crazy-mime');
$this->assertEquals($response->type('json'), 'application/json');
$this->assertEquals($response->type('wap'), 'text/vnd.wap.wml');
$this->assertEquals($response->type('xhtml-mobile'), 'application/vnd.wap.xhtml+xml');
$this->assertEquals($response->type('csv'), 'text/csv');
$response->type(array('keynote' => 'application/keynote'));
$this->assertEquals($response->type('keynote'), 'application/keynote');
$this->assertFalse($response->type('wackytype'));
}
/**
* Tests the header method
*
*/
public function testHeader() {
$response = new CakeResponse();
$headers = array();
$this->assertEquals($response->header(), $headers);
$response->header('Location', 'http://example.com');
$headers += array('Location' => 'http://example.com');
$this->assertEquals($response->header(), $headers);
//Headers with the same name are overwritten
$response->header('Location', 'http://example2.com');
$headers = array('Location' => 'http://example2.com');
$this->assertEquals($response->header(), $headers);
$response->header(array('WWW-Authenticate' => 'Negotiate'));
$headers += array('WWW-Authenticate' => 'Negotiate');
$this->assertEquals($response->header(), $headers);
$response->header(array('WWW-Authenticate' => 'Not-Negotiate'));
$headers['WWW-Authenticate'] = 'Not-Negotiate';
$this->assertEquals($response->header(), $headers);
$response->header(array('Age' => 12, 'Allow' => 'GET, HEAD'));
$headers += array('Age' => 12, 'Allow' => 'GET, HEAD');
$this->assertEquals($response->header(), $headers);
// String headers are allowed
$response->header('Content-Language: da');
$headers += array('Content-Language' => 'da');
$this->assertEquals($response->header(), $headers);
$response->header('Content-Language: da');
$headers += array('Content-Language' => 'da');
$this->assertEquals($response->header(), $headers);
$response->header(array('Content-Encoding: gzip', 'Vary: *', 'Pragma' => 'no-cache'));
$headers += array('Content-Encoding' => 'gzip', 'Vary' => '*', 'Pragma' => 'no-cache');
$this->assertEquals($response->header(), $headers);
}
/**
* Tests the send method
*
*/
public function testSend() {
$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
$response->header(array(
'Content-Language' => 'es',
'WWW-Authenticate' => 'Negotiate'
));
$response->body('the response body');
$response->expects($this->once())->method('_sendContent')->with('the response body');
$response->expects($this->at(0))
->method('_sendHeader')->with('HTTP/1.1 200 OK');
$response->expects($this->at(1))
->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8');
$response->expects($this->at(2))
->method('_sendHeader')->with('Content-Language', 'es');
$response->expects($this->at(3))
->method('_sendHeader')->with('WWW-Authenticate', 'Negotiate');
$response->send();
}
/**
* Tests the send method and changing the content type
*
*/
public function testSendChangingContentYype() {
$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
$response->type('mp3');
$response->body('the response body');
$response->expects($this->once())->method('_sendContent')->with('the response body');
$response->expects($this->at(0))
->method('_sendHeader')->with('HTTP/1.1 200 OK');
$response->expects($this->at(1))
->method('_sendHeader')->with('Content-Type', 'audio/mpeg; charset=UTF-8');
$response->send();
}
/**
* Tests the send method and changing the content type
*
*/
public function testSendChangingContentType() {
$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
$response->type('mp3');
$response->body('the response body');
$response->expects($this->once())->method('_sendContent')->with('the response body');
$response->expects($this->at(0))
->method('_sendHeader')->with('HTTP/1.1 200 OK');
$response->expects($this->at(1))
->method('_sendHeader')->with('Content-Type', 'audio/mpeg; charset=UTF-8');
$response->send();
}
/**
* Tests the send method and changing the content type
*
*/
public function testSendWithLocation() {
$response = $this->getMock('CakeResponse', array('_sendHeader', '_sendContent'));
$response->header('Location', 'http://www.example.com');
$response->expects($this->at(0))
->method('_sendHeader')->with('HTTP/1.1 302 Found');
$response->expects($this->at(1))
->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8');
$response->expects($this->at(2))
->method('_sendHeader')->with('Location', 'http://www.example.com');
$response->send();
}
/**
* Tests the disableCache method
*
*/
public function testDisableCache() {
$response = new CakeResponse();
$expected = array(
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
'Last-Modified' => gmdate("D, d M Y H:i:s") . " GMT",
'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
'Pragma' => 'no-cache'
);
$response->disableCache();
$this->assertEquals($response->header(), $expected);
}
/**
* Tests the cache method
*
*/
public function testCache() {
$response = new CakeResponse();
$since = time();
$time = '+1 day';
$expected = array(
'Date' => date("D, j M Y G:i:s ", $since) . 'GMT',
'Expires' => gmdate("D, j M Y H:i:s", strtotime($time)) . " GMT",
'Cache-Control' => 'cache',
'Pragma' => 'cache'
);
$response->cache($since);
$this->assertEquals($response->header(), $expected);
$response = new CakeResponse();
$since = time();
$time = '+5 day';
$expected = array(
'Date' => date("D, j M Y G:i:s ", $since) . 'GMT',
'Expires' => gmdate("D, j M Y H:i:s", strtotime($time)) . " GMT",
'Cache-Control' => 'cache',
'Pragma' => 'cache'
);
$response->cache($since, $time);
$this->assertEquals($response->header(), $expected);
$response = new CakeResponse();
$since = time();
$time = time();
$expected = array(
'Date' => date("D, j M Y G:i:s ", $since) . 'GMT',
'Expires' => gmdate("D, j M Y H:i:s", $time) . " GMT",
'Cache-Control' => 'cache',
'Pragma' => 'cache'
);
$response->cache($since, $time);
$this->assertEquals($response->header(), $expected);
}
/**
* Tests the compress method
*
*/
public function testCompress() {
$this->skipIf(php_sapi_name() !== 'cli', 'The response compression can only be tested in cli');
$response = new CakeResponse();
if (ini_get("zlib.output_compression") === '1' || !extension_loaded("zlib")) {
$this->assertFalse($response->compress());
$this->markTestSkipped('Is not possible to test output compression');
}
$_SERVER['HTTP_ACCEPT_ENCODING'] = '';
$result = $response->compress();
$this->assertFalse($result);
$_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
$result = $response->compress();
$this->assertTrue($result);
$this->assertTrue(in_array('ob_gzhandler', ob_list_handlers()));
}
/**
* Tests the httpCodes method
*
*/
public function testHttpCodes() {
$response = new CakeResponse();
$result = $response->httpCodes();
$this->assertEqual(count($result), 39);
$result = $response->httpCodes(100);
$expected = array(100 => 'Continue');
$this->assertEqual($result, $expected);
$codes = array(
1337 => 'Undefined Unicorn',
1729 => 'Hardy-Ramanujan Located'
);
$result = $response->httpCodes($codes);
$this->assertTrue($result);
$this->assertEqual(count($response->httpCodes()), 41);
$result = $response->httpCodes(1337);
$expected = array(1337 => 'Undefined Unicorn');
$this->assertEqual($result, $expected);
$codes = array(404 => 'Sorry Bro');
$result = $response->httpCodes($codes);
$this->assertTrue($result);
$this->assertEqual(count($response->httpCodes()), 41);
$result = $response->httpCodes(404);
$expected = array(404 => 'Sorry Bro');
$this->assertEqual($result, $expected);
}
/**
* Tests the download method
*
*/
public function testDownload() {
$response = new CakeResponse();
$expected = array(
'Content-Disposition' => 'attachment; filename="myfile.mp3"'
);
$response->download('myfile.mp3');
$this->assertEquals($response->header(), $expected);
}
/**
* Tests the mapType method
*
*/
public function testMapType() {
$response = new CakeResponse();
$this->assertEquals('wav', $response->mapType('audio/x-wav'));
$this->assertEquals('pdf', $response->mapType('application/pdf'));
$this->assertEquals('xml', $response->mapType('text/xml'));
$this->assertEquals('html', $response->mapType('*/*'));
$this->assertEquals('csv', $response->mapType('application/vnd.ms-excel'));
$expected = array('json', 'xhtml', 'css');
$result = $response->mapType(array('application/json', 'application/xhtml+xml', 'text/css'));
$this->assertEquals($expected, $result);
}
}

View file

@ -251,10 +251,12 @@ class AuthTestController extends Controller {
* @access private
* @return void
*/
function __construct() {
$this->params = Router::parse('/auth_test');
Router::setRequestInfo(array($this->params, array('base' => null, 'here' => '/auth_test', 'webroot' => '/', 'passedArgs' => array(), 'argSeparator' => ':', 'namedArgs' => array())));
parent::__construct();
function __construct($request) {
$request->addParams(Router::parse('/auth_test'));
$request->here = '/auth_test';
$request->webroot = '/';
Router::setRequestInfo($request);
parent::__construct($request);
}
/**
@ -336,7 +338,7 @@ class AuthTestController extends Controller {
* @return void
*/
function isAuthorized() {
if (isset($this->params['testControllerAuth'])) {
if (isset($this->request['testControllerAuth'])) {
return false;
}
return true;
@ -488,9 +490,11 @@ class AuthTest extends CakeTestCase {
Configure::write('Acl.database', 'test_suite');
Configure::write('Acl.classname', 'DbAcl');
$this->Controller = new AuthTestController();
$this->Controller->Components->init($this->Controller);
$this->Controller->Components->trigger('initialize', array(&$this->Controller));
$request = new CakeRequest(null, false);
$this->Controller = new AuthTestController($request);
$this->Controller->Component->init($this->Controller);
$this->Controller->Component->initialize($this->Controller);
$this->Controller->beforeFilter();
ClassRegistry::addObject('view', new View($this->Controller));
@ -545,11 +549,11 @@ class AuthTest extends CakeTestCase {
$this->assertTrue($this->Controller->Auth->startup($this->Controller));
$this->Controller->name = 'Post';
$this->Controller->params['action'] = 'thisdoesnotexist';
$this->Controller->request['action'] = 'thisdoesnotexist';
$this->assertTrue($this->Controller->Auth->startup($this->Controller));
$this->Controller->scaffold = null;
$this->Controller->params['action'] = 'index';
$this->Controller->request['action'] = 'index';
$this->assertFalse($this->Controller->Auth->startup($this->Controller));
}
@ -568,11 +572,12 @@ class AuthTest extends CakeTestCase {
$authUser = $this->AuthUser->find();
$this->Controller->data['AuthUser']['username'] = $authUser['AuthUser']['username'];
$this->Controller->data['AuthUser']['password'] = 'cake';
$this->Controller->request->data['AuthUser'] = array(
'username' => $authUser['AuthUser']['username'], 'password' => 'cake'
);
$this->Controller->params = Router::parse('auth_test/login');
$this->Controller->params['url']['url'] = 'auth_test/login';
$this->Controller->request->addParams(Router::parse('auth_test/login'));
$this->Controller->request->query['url'] = 'auth_test/login';
$this->Controller->Auth->initialize($this->Controller);
@ -587,8 +592,9 @@ class AuthTest extends CakeTestCase {
$this->assertEqual($user, $expected);
$this->Controller->Session->delete('Auth');
$this->Controller->data['AuthUser']['username'] = 'blah';
$this->Controller->data['AuthUser']['password'] = '';
$this->Controller->request->data['AuthUser'] = array(
'username' => 'blah', 'password' => ''
);
$this->Controller->Auth->startup($this->Controller);
@ -596,8 +602,9 @@ class AuthTest extends CakeTestCase {
$this->assertNull($user);
$this->Controller->Session->delete('Auth');
$this->Controller->data['AuthUser']['username'] = 'now() or 1=1 --';
$this->Controller->data['AuthUser']['password'] = '';
$this->Controller->request->data['AuthUser'] = array(
'username' => 'now() or 1=1 --', 'password' => ''
);
$this->Controller->Auth->startup($this->Controller);
@ -605,8 +612,9 @@ class AuthTest extends CakeTestCase {
$this->assertNull($user);
$this->Controller->Session->delete('Auth');
$this->Controller->data['AuthUser']['username'] = 'now() or 1=1 # something';
$this->Controller->data['AuthUser']['password'] = '';
$this->Controller->request->data['AuthUser'] = array(
'username' => 'now() or 1=1 #something', 'password' => ''
);
$this->Controller->Auth->startup($this->Controller);
@ -637,8 +645,8 @@ class AuthTest extends CakeTestCase {
$_SERVER['HTTP_REFERER'] = '/pages/display/about';
$this->Controller->data = array();
$this->Controller->params = Router::parse('auth_test/login');
$this->Controller->params['url']['url'] = 'auth_test/login';
$this->Controller->request->addParams(Router::parse('auth_test/login'));
$this->Controller->request->query['url'] = 'auth_test/login';
$this->Controller->Session->delete('Auth');
$this->Controller->Auth->loginRedirect = '/users/dashboard';
@ -662,7 +670,7 @@ class AuthTest extends CakeTestCase {
$this->Controller->Session->write('Auth', $user);
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->authorize = false;
$this->Controller->params = Router::parse('auth_test/add');
$this->Controller->request->addParams(Router::parse('auth_test/add'));
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertTrue($result);
@ -671,7 +679,7 @@ class AuthTest extends CakeTestCase {
$this->assertFalse($result);
$this->assertTrue($this->Controller->Session->check('Message.auth'));
$this->Controller->params = Router::parse('auth_test/camelCase');
$this->Controller->request->addParams(Router::parse('auth_test/camelCase'));
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertFalse($result);
}
@ -688,11 +696,11 @@ class AuthTest extends CakeTestCase {
$this->Controller->Session->write('Auth', $user);
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->authorize = 'controller';
$this->Controller->params = Router::parse('auth_test/add');
$this->Controller->request->addParams(Router::parse('auth_test/add'));
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertTrue($result);
$this->Controller->params['testControllerAuth'] = 1;
$this->Controller->request['testControllerAuth'] = 1;
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertTrue($this->Controller->Session->check('Message.auth'));
$this->assertFalse($result);
@ -711,8 +719,8 @@ class AuthTest extends CakeTestCase {
$user = $this->AuthUser->find();
$this->Controller->Session->write('Auth', $user);
$this->Controller->params['controller'] = 'auth_test';
$this->Controller->params['action'] = 'add';
$this->Controller->request['controller'] = 'auth_test';
$this->Controller->request['action'] = 'add';
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->authorize = array('model'=>'AuthUser');
@ -737,8 +745,8 @@ class AuthTest extends CakeTestCase {
$user = $this->AuthUser->find();
$this->Controller->Session->write('Auth', $user);
$this->Controller->params['controller'] = 'auth_test';
$this->Controller->params['action'] = 'add';
$this->Controller->request['controller'] = 'auth_test';
$this->Controller->request['action'] = 'add';
$this->Controller->Acl->name = 'DbAclTest';
@ -797,8 +805,8 @@ class AuthTest extends CakeTestCase {
$this->AuthUser = new AuthUser();
$user = $this->AuthUser->find();
$this->Controller->Session->write('Auth', $user);
$this->Controller->params['controller'] = 'auth_test';
$this->Controller->params['action'] = 'add';
$this->Controller->request['controller'] = 'auth_test';
$this->Controller->request['action'] = 'add';
$this->Controller->Acl = $this->getMock('AclComponent', array(), array(), '', false);
$this->Controller->Acl->expects($this->atLeastOnce())->method('check')->will($this->returnValue(true));
@ -827,20 +835,19 @@ class AuthTest extends CakeTestCase {
$this->Controller->Auth->allow('*');
$this->Controller->Auth->deny('add', 'camelCase');
$this->Controller->params['action'] = 'delete';
$this->Controller->request['action'] = 'delete';
$this->assertTrue($this->Controller->Auth->startup($this->Controller));
$this->Controller->params['action'] = 'add';
$this->Controller->request['action'] = 'add';
$this->assertFalse($this->Controller->Auth->startup($this->Controller));
$this->Controller->params['action'] = 'camelCase';
$this->Controller->request['action'] = 'camelCase';
$this->assertFalse($this->Controller->Auth->startup($this->Controller));
$this->Controller->Auth->allow('*');
$this->Controller->Auth->deny(array('add', 'camelCase'));
$this->Controller->params['action'] = 'camelCase';
$this->Controller->request['action'] = 'camelCase';
$this->assertFalse($this->Controller->Auth->startup($this->Controller));
}
@ -850,8 +857,8 @@ class AuthTest extends CakeTestCase {
* @return void
*/
function testActionMethod() {
$this->Controller->params['controller'] = 'auth_test';
$this->Controller->params['action'] = 'add';
$this->Controller->request['controller'] = 'auth_test';
$this->Controller->request['action'] = 'add';
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->actionPath = 'ROOT/';
@ -865,9 +872,9 @@ class AuthTest extends CakeTestCase {
$result = $this->Controller->Auth->action(':controller');
$this->assertEqual($result, 'ROOT/AuthTest');
$this->Controller->params['plugin'] = 'test_plugin';
$this->Controller->params['controller'] = 'auth_test';
$this->Controller->params['action'] = 'add';
$this->Controller->request['plugin'] = 'test_plugin';
$this->Controller->request['controller'] = 'auth_test';
$this->Controller->request['action'] = 'add';
$this->Controller->Auth->initialize($this->Controller);
$result = $this->Controller->Auth->action();
$this->assertEqual($result, 'ROOT/TestPlugin/AuthTest/add');
@ -884,8 +891,8 @@ class AuthTest extends CakeTestCase {
$this->Controller->Auth->deny('add', 'camelCase');
$url = '/auth_test/camelCase';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = Router::normalize($url);
$this->assertFalse($this->Controller->Auth->startup($this->Controller));
}
@ -897,8 +904,8 @@ class AuthTest extends CakeTestCase {
*/
function testAllowedActionsWithCamelCaseMethods() {
$url = '/auth_test/camelCase';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -907,8 +914,8 @@ class AuthTest extends CakeTestCase {
$this->assertTrue($result, 'startup() should return true, as action is allowed. %s');
$url = '/auth_test/camelCase';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -921,8 +928,8 @@ class AuthTest extends CakeTestCase {
$this->assertFalse($result, 'startup() should return false, as action is not allowed. %s');
$url = '/auth_test/delete';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -934,8 +941,8 @@ class AuthTest extends CakeTestCase {
function testAllowedActionsSetWithAllowMethod() {
$url = '/auth_test/action_name';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->allow('action_name', 'anotherAction');
$this->assertEqual($this->Controller->Auth->allowedActions, array('action_name', 'anotherAction'));
@ -948,20 +955,18 @@ class AuthTest extends CakeTestCase {
* @return void
*/
function testLoginRedirect() {
$backup = null;
if (isset($_SERVER['HTTP_REFERER'])) {
$backup = $_SERVER['HTTP_REFERER'];
} else {
$backup = null;
}
$_SERVER['HTTP_REFERER'] = false;
$this->Controller->Session->write('Auth', array(
'AuthUser' => array('id' => '1', 'username' => 'nate')
));
$this->Controller->params = Router::parse('users/login');
$this->Controller->params['url']['url'] = 'users/login';
$this->Controller->request->addParams(Router::parse('users/login'));
$this->Controller->request->query['url'] = 'users/login';
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->userModel = 'AuthUser';
@ -974,7 +979,7 @@ class AuthTest extends CakeTestCase {
$this->Controller->Session->delete('Auth');
$this->Controller->params['url']['url'] = 'admin/';
$this->Controller->request->query['url'] = 'admin/';
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->loginRedirect = null;
@ -995,12 +1000,12 @@ class AuthTest extends CakeTestCase {
'AuthUser' => array('id' => '1', 'username' => 'nate'))
);
$this->Controller->testUrl = null;
$this->Controller->params = Router::parse($url);
$this->Controller->request->addParams(Router::parse($url));
array_push($this->Controller->methods, 'view', 'edit', 'index');
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->authorize = 'controller';
$this->Controller->params['testControllerAuth'] = true;
$this->Controller->request['testControllerAuth'] = true;
$this->Controller->Auth->loginAction = array(
'controller' => 'AuthTest', 'action' => 'login'
@ -1012,12 +1017,12 @@ class AuthTest extends CakeTestCase {
$this->Controller->Session->delete('Auth');
$_SERVER['HTTP_REFERER'] = Router::url('/admin/', true);
$_SERVER['HTTP_REFERER'] = Router::url('/admin', true);
$this->Controller->Session->write('Auth', array(
'AuthUser' => array('id'=>'1', 'username'=>'nate'))
);
$this->Controller->params['url']['url'] = 'auth_test/login';
'AuthUser' => array('id'=>'1', 'username' => 'nate')
));
$this->Controller->request->query['url'] = 'auth_test/login';
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = 'auth_test/login';
$this->Controller->Auth->userModel = 'AuthUser';
@ -1030,8 +1035,8 @@ class AuthTest extends CakeTestCase {
//named params
$this->Controller->Session->delete('Auth');
$url = '/posts/index/year:2008/month:feb';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -1042,8 +1047,8 @@ class AuthTest extends CakeTestCase {
//passed args
$this->Controller->Session->delete('Auth');
$url = '/posts/view/1';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -1059,8 +1064,8 @@ class AuthTest extends CakeTestCase {
'refer' => 'menu'
);
$this->Controller->Session->delete('Auth');
$url = '/posts/index/29?print=true&refer=menu';
$this->Controller->params = Dispatcher::parseParams($url);
$url = '/posts/index/29';
$this->Controller->request = Dispatcher::parseParams(new CakeRequest($url));
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -1075,8 +1080,8 @@ class AuthTest extends CakeTestCase {
'ext' => 'html'
);
$this->Controller->Session->delete('Auth');
$url = '/posts/index/29?print=true&refer=menu';
$this->Controller->params = Dispatcher::parseParams($url);
$url = '/posts/index/29';
$this->Controller->request = Dispatcher::parseParams(new CakeRequest($url));
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -1089,8 +1094,8 @@ class AuthTest extends CakeTestCase {
$_SERVER['HTTP_REFERER'] = 'http://webmail.example.com/view/message';
$this->Controller->Session->delete('Auth');
$url = '/posts/edit/1';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query = array('url' => Router::normalize($url));
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -1102,8 +1107,8 @@ class AuthTest extends CakeTestCase {
$_SERVER['HTTP_REFERER'] = 'http://webmail.example.com/view/message';
$this->Controller->Session->delete('Auth');
$url = '/AuthTest/login';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -1124,7 +1129,7 @@ class AuthTest extends CakeTestCase {
function testNoRedirectOn404() {
$this->Controller->Session->delete('Auth');
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->params = Router::parse('auth_test/something_totally_wrong');
$this->Controller->request->addParams(Router::parse('auth_test/something_totally_wrong'));
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertTrue($result, 'Auth redirected a missing action %s');
}
@ -1144,11 +1149,12 @@ class AuthTest extends CakeTestCase {
$authUser = $this->AuthUser->find();
$this->Controller->data['AuthUser']['username'] = '';
$this->Controller->data['AuthUser']['password'] = '';
$this->Controller->request->data['AuthUser'] = array(
'username' => '', 'password' => ''
);
$this->Controller->params = Router::parse('auth_test/login');
$this->Controller->params['url']['url'] = 'auth_test/login';
$this->Controller->request->addParams(Router::parse('auth_test/login'));
$this->Controller->request->query['url'] = 'auth_test/login';
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = 'auth_test/login';
$this->Controller->Auth->userModel = 'AuthUser';
@ -1171,10 +1177,12 @@ class AuthTest extends CakeTestCase {
$this->AuthUser->id = 2;
$this->AuthUser->saveField('password', Security::hash(Configure::read('Security.salt') . 'cake'));
$this->Controller->data['AuthUser']['username'] = 'nate';
$this->Controller->data['AuthUser']['password'] = 'cake';
$this->Controller->params = Router::parse('auth_test/login');
$this->Controller->params['url']['url'] = 'auth_test/login';
$this->Controller->request->data['AuthUser'] = array(
'username' => 'nate', 'password' => 'cake'
);
$this->Controller->request->addParams(Router::parse('auth_test/login'));
$this->Controller->request->query['url'] = 'auth_test/login';
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = 'auth_test/login';
@ -1186,7 +1194,7 @@ class AuthTest extends CakeTestCase {
$this->Controller->data['AuthUser']['username'] = 'nate';
$this->Controller->data['AuthUser']['password'] = 'cake1';
$this->Controller->params['url']['url'] = 'auth_test/login';
$this->Controller->request->query['url'] = 'auth_test/login';
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = 'auth_test/login';
@ -1240,6 +1248,7 @@ class AuthTest extends CakeTestCase {
$expected = $data;
$expected['AuthUser']['password'] = Security::hash($expected['AuthUser']['password'], null, true);
$this->assertEqual($return, $expected);
$xml = array(
'User' => array(
'username' => 'batman@batcave.com',
@ -1267,11 +1276,8 @@ class AuthTest extends CakeTestCase {
);
$url = '/en/users/login';
$this->Controller->params = Router::parse($url);
Router::setRequestInfo(array($this->Controller->passedArgs, array(
'base' => null, 'here' => $url, 'webroot' => '/', 'passedArgs' => array(),
'argSeparator' => ':', 'namedArgs' => array()
)));
$this->Controller->request->addParams(Router::parse($url));
Router::setRequestInfo($this->Controller->request);
$this->AuthUser = new AuthUser();
$user = array(
@ -1280,8 +1286,8 @@ class AuthTest extends CakeTestCase {
));
$user = $this->AuthUser->save($user, false);
$this->Controller->data['AuthUser'] = array('username' => 'felix', 'password' => 'cake');
$this->Controller->params['url']['url'] = substr($url, 1);
$this->Controller->request->data['AuthUser'] = array('username' => 'felix', 'password' => 'cake');
$this->Controller->request->query['url'] = substr($url, 1);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('lang' => 'en', 'controller' => 'users', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -1294,13 +1300,13 @@ class AuthTest extends CakeTestCase {
Router::reload();
Router::connect('/', array('controller' => 'people', 'action' => 'login'));
$url = '/';
$this->Controller->params = Router::parse($url);
$this->Controller->request->addParams(Router::parse($url));
Router::setRequestInfo(array($this->Controller->passedArgs, array(
'base' => null, 'here' => $url, 'webroot' => '/', 'passedArgs' => array(),
'argSeparator' => ':', 'namedArgs' => array()
)));
$this->Controller->data['AuthUser'] = array('username' => 'felix', 'password' => 'cake');
$this->Controller->params['url']['url'] = substr($url, 1);
$this->Controller->request->data['AuthUser'] = array('username' => 'felix', 'password' => 'cake');
$this->Controller->request->query['url'] = substr($url, 1);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'people', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -1328,13 +1334,12 @@ class AuthTest extends CakeTestCase {
Router::connect('/', array('controller' => 'people', 'action' => 'login'));
$url = '/';
$this->Controller->params = Router::parse($url);
Router::setRequestInfo(array($this->Controller->passedArgs, array(
'base' => null, 'here' => $url, 'webroot' => '/', 'passedArgs' => array(),
'argSeparator' => ':', 'namedArgs' => array()
)));
$this->Controller->data['AuthUserCustomField'] = array('email' => 'harking@example.com', 'password' => 'cake');
$this->Controller->params['url']['url'] = substr($url, 1);
$this->Controller->request->addParams(Router::parse($url));
Router::setRequestInfo($this->Controller->request);
$this->Controller->request->data['AuthUserCustomField'] = array(
'email' => 'harking@example.com', 'password' => 'cake'
);
$this->Controller->request->query['url'] = substr($url, 1);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->fields = array('username' => 'email', 'password' => 'password');
$this->Controller->Auth->loginAction = array('controller' => 'people', 'action' => 'login');
@ -1357,19 +1362,10 @@ class AuthTest extends CakeTestCase {
Router::reload();
$url = '/admin/auth_test/add';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = ltrim($url, '/');
Router::setRequestInfo(array(
array(
'pass' => array(), 'action' => 'add', 'plugin' => null,
'controller' => 'auth_test', 'admin' => true,
'url' => array('url' => $this->Controller->params['url']['url'])
),
array(
'base' => null, 'here' => $url,
'webroot' => '/', 'passedArgs' => array(),
)
));
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = ltrim($url, '/');
$this->Controller->request->base = '';
Router::setRequestInfo($this->Controller->request);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array(
@ -1406,11 +1402,12 @@ class AuthTest extends CakeTestCase {
$authUser = $PluginModel->find();
$this->Controller->data['TestPluginAuthUser']['username'] = $authUser['TestPluginAuthUser']['username'];
$this->Controller->data['TestPluginAuthUser']['password'] = 'cake';
$this->Controller->request->data['TestPluginAuthUser'] = array(
'username' => $authUser['TestPluginAuthUser']['username'], 'password' => 'cake'
);
$this->Controller->params = Router::parse('auth_test/login');
$this->Controller->params['url']['url'] = 'auth_test/login';
$this->Controller->request->addParams(Router::parse('auth_test/login'));
$this->Controller->request->query['url'] = 'auth_test/login';
$this->Controller->Auth->initialize($this->Controller);
@ -1476,12 +1473,12 @@ class AuthTest extends CakeTestCase {
Router::reload();
$url = '/admin/auth_test/login';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = ltrim($url, '/');
$this->Controller->request->addParams(Router::parse($url));
$this->Controller->request->query['url'] = ltrim($url, '/');
Router::setRequestInfo(array(
array(
'pass' => array(), 'action' => 'admin_login', 'plugin' => null, 'controller' => 'auth_test',
'admin' => true, 'url' => array('url' => $this->Controller->params['url']['url']),
'admin' => true, 'url' => array('url' => $this->Controller->request->query['url']),
),
array(
'base' => null, 'here' => $url,
@ -1508,8 +1505,10 @@ class AuthTest extends CakeTestCase {
* @return void
*/
function testShutDown() {
$this->Controller->Auth->initialize($this->Controller, array('_loggedIn' => true));
$this->Controller->Session->write('Auth.redirect', 'foo');
$this->Controller->Auth->loggedIn(true);
$this->Controller->Auth->shutdown($this->Controller);
$this->assertNull($this->Controller->Session->read('Auth.redirect'));
}
@ -1541,7 +1540,10 @@ class AuthTest extends CakeTestCase {
* @return void
*/
function testComponentSettings() {
$this->Controller = new AuthTestController();
$request = new CakeRequest(null, false);
$this->Controller = new AuthTestController($request);
$this->Controller->components = array(
'Auth' => array(
'fields' => array('username' => 'email', 'password' => 'password'),
@ -1564,13 +1566,12 @@ class AuthTest extends CakeTestCase {
Router::connect('/', array('controller' => 'people', 'action' => 'login'));
$url = '/';
$this->Controller->params = Router::parse($url);
Router::setRequestInfo(array($this->Controller->passedArgs, array(
'base' => null, 'here' => $url, 'webroot' => '/', 'passedArgs' => array(),
'argSeparator' => ':', 'namedArgs' => array()
)));
$this->Controller->data['AuthUserCustomField'] = array('email' => 'harking@example.com', 'password' => 'cake');
$this->Controller->params['url']['url'] = substr($url, 1);
$this->Controller->request->addParams(Router::parse($url));
Router::setRequestInfo($this->Controller->request);
$this->Controller->request->data['AuthUserCustomField'] = array(
'email' => 'harking@example.com', 'password' => 'cake'
);
$this->Controller->request->query['url'] = substr($url, 1);
$this->Controller->Auth->startup($this->Controller);
$user = $this->Controller->Auth->user();

View file

@ -19,6 +19,7 @@
*/
App::import('Controller', 'Controller', false);
App::import('Component', array('RequestHandler'));
App::import('Core', array('CakeRequest', 'CakeResponse'));
/**
* RequestHandlerTestController class
@ -44,20 +45,6 @@ class RequestHandlerTestController extends Controller {
*/
public $uses = null;
/**
* construct method
*
* @param array $params
* @access private
* @return void
*/
function __construct($params = array()) {
foreach ($params as $key => $val) {
$this->{$key} = $val;
}
parent::__construct();
}
/**
* test method for ajax redirection
*
@ -106,20 +93,6 @@ class RequestHandlerTestDisabledController extends Controller {
*/
public $uses = null;
/**
* construct method
*
* @param array $params
* @access private
* @return void
*/
function __construct($params = array()) {
foreach ($params as $key => $val) {
$this->{$key} = $val;
}
parent::__construct();
}
/**
* beforeFilter method
*
@ -155,12 +128,13 @@ class RequestHandlerComponentTest extends CakeTestCase {
public $RequestHandler;
/**
* startTest method
* setUp method
*
* @access public
* @return void
*/
function startTest() {
function setUp() {
$this->_server = $_SERVER;
$this->_init();
}
@ -171,9 +145,12 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function _init() {
$this->Controller = new RequestHandlerTestController(array('components' => array('RequestHandler')));
$this->Controller->constructClasses();
$this->RequestHandler =& $this->Controller->RequestHandler;
$request = new CakeRequest('controller_posts/index');
$response = new CakeResponse();
$this->Controller = new RequestHandlerTestController($request, $response);
$this->RequestHandler = new RequestHandlerComponent($this->Controller->Components);
$this->RequestHandler->request = $request;
$this->RequestHandler->response = $response;
}
/**
@ -182,12 +159,13 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @access public
* @return void
*/
function endTest() {
function tearDown() {
unset($this->RequestHandler);
unset($this->Controller);
if (!headers_sent()) {
header('Content-type: text/html'); //reset content type.
}
$_SERVER = $this->_server;
App::build();
}
@ -213,13 +191,50 @@ class RequestHandlerComponentTest extends CakeTestCase {
*/
function testInitializeCallback() {
$this->assertNull($this->RequestHandler->ext);
$this->_init();
$this->Controller->params['url']['ext'] = 'rss';
$this->Controller->request->params['url']['ext'] = 'rss';
$this->RequestHandler->initialize($this->Controller);
$this->assertEqual($this->RequestHandler->ext, 'rss');
}
/**
* test that a mapped Accept-type header will set $this->ext correctly.
*
* @return void
*/
function testInitializeContentTypeSettingExt() {
$this->assertNull($this->RequestHandler->ext);
$extensions = Router::extensions();
Router::parseExtensions('json');
$this->Controller->request = $this->getMock('CakeRequest');
$this->Controller->request->expects($this->any())->method('accepts')
->will($this->returnValue(array('application/json')));
$this->RequestHandler->initialize($this->Controller);
$this->assertEquals('json', $this->RequestHandler->ext);
call_user_func_array(array('Router', 'parseExtensions'), $extensions);
}
/**
* Test that a type mismatch doesn't incorrectly set the ext
*
* @return void
*/
function testInitializeContentTypeAndExtensionMismatch() {
$this->assertNull($this->RequestHandler->ext);
$extensions = Router::extensions();
Router::parseExtensions('xml');
$this->Controller->request = $this->getMock('CakeRequest');
$this->Controller->request->expects($this->any())->method('accepts')
->will($this->returnValue(array('application/json')));
$this->RequestHandler->initialize($this->Controller);
$this->assertNull($this->RequestHandler->ext);
call_user_func_array(array('Router', 'parseExtensions'), $extensions);
}
/**
* testDisabling method
*
@ -229,18 +244,10 @@ class RequestHandlerComponentTest extends CakeTestCase {
function testDisabling() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->_init();
$this->Controller->Components->trigger('initialize', array(&$this->Controller));
$this->RequestHandler->initialize($this->Controller);
$this->Controller->beforeFilter();
$this->Controller->Components->trigger('startup', array(&$this->Controller));
$this->assertEqual($this->Controller->params, array('isAjax' => true));
$this->Controller = new RequestHandlerTestDisabledController(array('components' => array('RequestHandler')));
$this->Controller->constructClasses();
$this->Controller->Components->trigger('initialize', array(&$this->Controller));
$this->Controller->beforeFilter();
$this->Controller->Components->trigger('startup', array(&$this->Controller));
$this->assertEqual($this->Controller->params, array());
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
$this->RequestHandler->startup($this->Controller);
$this->assertEqual($this->Controller->params['isAjax'], true);
}
/**
@ -251,7 +258,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
*/
function testAutoResponseType() {
$this->Controller->ext = '.thtml';
$this->Controller->params['url']['ext'] = 'rss';
$this->Controller->request->params['url']['ext'] = 'rss';
$this->RequestHandler->initialize($this->Controller);
$this->RequestHandler->startup($this->Controller);
$this->assertEqual($this->Controller->ext, '.ctp');
@ -318,22 +325,17 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testRespondAs() {
$debug = Configure::read('debug');
Configure::write('debug', 0);
$this->RequestHandler->response = $this->getMock('CakeResponse', array('type'));
$this->RequestHandler->response->expects($this->at(0))->method('type')
->with('application/json');
$this->RequestHandler->response->expects($this->at(1))->method('type')
->with('text/xml');
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_header'), array(&$this->Controller->Components));
$RequestHandler->expects($this->at(0))->method('_header')
->with('Content-type: application/json');
$RequestHandler->expects($this->at(1))->method('_header')
->with('Content-type: text/xml');
$result = $RequestHandler->respondAs('json');
$result = $this->RequestHandler->respondAs('json');
$this->assertTrue($result);
$result = $RequestHandler->respondAs('text/xml');
$result = $this->RequestHandler->respondAs('text/xml');
$this->assertTrue($result);
Configure::write('debug', $debug);
}
/**
@ -342,19 +344,17 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testRespondAsWithAttachment() {
$debug = Configure::read('debug');
Configure::write('debug', 0);
$this->RequestHandler = $this->getMock('RequestHandlerComponent', array('_header'), array(&$this->Controller->Components));
$this->RequestHandler->response = $this->getMock('CakeResponse', array('type', 'download'));
$this->RequestHandler->request = $this->getMock('CakeRequest');
$this->RequestHandler->response->expects($this->once())->method('download')
->with('myfile.xml');
$this->RequestHandler->response->expects($this->once())->method('type')
->with('application/xml');
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_header'), array(&$this->Controller->Components));
$RequestHandler->expects($this->at(0))->method('_header')
->with('Content-Disposition: attachment; filename="myfile.xml"');
$RequestHandler->expects($this->at(1))->method('_header')
->with('Content-type: application/xml');
$result = $RequestHandler->respondAs('xml', array('attachment' => 'myfile.xml'));
$result = $this->RequestHandler->respondAs('xml', array('attachment' => 'myfile.xml'));
$this->assertTrue($result);
Configure::write('debug', $debug);
}
/**
@ -383,19 +383,10 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testRequestClientTypes() {
$this->assertFalse($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Shockwave Flash';
$this->assertTrue($this->RequestHandler->isFlash());
unset($_SERVER['HTTP_USER_AGENT'], $_SERVER['HTTP_X_REQUESTED_WITH']);
$this->assertFalse($this->RequestHandler->isAjax());
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$_SERVER['HTTP_X_PROTOTYPE_VERSION'] = '1.5';
$this->assertTrue($this->RequestHandler->isAjax());
$this->assertEqual($this->RequestHandler->getAjaxVersion(), '1.5');
unset($_SERVER['HTTP_X_REQUESTED_WITH'], $_SERVER['HTTP_X_PROTOTYPE_VERSION']);
$this->assertFalse($this->RequestHandler->isAjax());
$this->assertFalse($this->RequestHandler->getAjaxVersion());
}
@ -406,23 +397,13 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testFlashDetection() {
$_agent = env('HTTP_USER_AGENT');
$_SERVER['HTTP_USER_AGENT'] = 'Shockwave Flash';
$request = $this->getMock('CakeRequest');
$request->expects($this->once())->method('is')
->with('flash')
->will($this->returnValue(true));
$this->RequestHandler->request = $request;
$this->assertTrue($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Adobe Flash';
$this->assertTrue($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Adobe Flash Player 9';
$this->assertTrue($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Adobe Flash Player 10';
$this->assertTrue($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Shock Flash';
$this->assertFalse($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = $_agent;
}
/**
@ -446,24 +427,20 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->assertFalse($result);
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertTrue($this->RequestHandler->isXml());
$this->assertFalse($this->RequestHandler->isAtom());
$this->assertFalse($this->RequestHandler->isRSS());
$_SERVER['HTTP_ACCEPT'] = 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertTrue($this->RequestHandler->isAtom());
$this->assertFalse($this->RequestHandler->isRSS());
$_SERVER['HTTP_ACCEPT'] = 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertFalse($this->RequestHandler->isAtom());
$this->assertTrue($this->RequestHandler->isRSS());
$this->assertFalse($this->RequestHandler->isWap());
$_SERVER['HTTP_ACCEPT'] = 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertTrue($this->RequestHandler->isWap());
$_SERVER['HTTP_ACCEPT'] = 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
@ -476,7 +453,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testResponseContentType() {
$this->assertNull($this->RequestHandler->responseType());
$this->assertEquals('html', $this->RequestHandler->responseType());
$this->assertTrue($this->RequestHandler->respondAs('atom'));
$this->assertEqual($this->RequestHandler->responseType(), 'atom');
}
@ -488,15 +465,13 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testMobileDeviceDetection() {
$this->assertFalse($this->RequestHandler->isMobile());
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3';
$request = $this->getMock('CakeRequest');
$request->expects($this->once())->method('is')
->with('mobile')
->will($this->returnValue(true));
$this->RequestHandler->request = $request;
$this->assertTrue($this->RequestHandler->isMobile());
$_SERVER['HTTP_USER_AGENT'] = 'Some imaginary UA';
$this->RequestHandler->mobileUA []= 'imaginary';
$this->assertTrue($this->RequestHandler->isMobile());
array_pop($this->RequestHandler->mobileUA);
}
/**
@ -506,17 +481,13 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testRequestProperties() {
$_SERVER['HTTPS'] = 'on';
$this->assertTrue($this->RequestHandler->isSSL());
unset($_SERVER['HTTPS']);
$this->assertFalse($this->RequestHandler->isSSL());
$_ENV['SCRIPT_URI'] = 'https://localhost/';
$s = $_SERVER;
$_SERVER = array();
$this->assertTrue($this->RequestHandler->isSSL());
$_SERVER = $s;
$request = $this->getMock('CakeRequest');
$request->expects($this->once())->method('is')
->with('ssl')
->will($this->returnValue(true));
$this->RequestHandler->request = $request;
$this->assertTrue($this->RequestHandler->isSsl());
}
/**
@ -526,58 +497,87 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testRequestMethod() {
$_SERVER['REQUEST_METHOD'] = 'GET';
$request = $this->getMock('CakeRequest');
$request->expects($this->at(0))->method('is')
->with('get')
->will($this->returnValue(true));
$request->expects($this->at(1))->method('is')
->with('post')
->will($this->returnValue(false));
$request->expects($this->at(2))->method('is')
->with('delete')
->will($this->returnValue(true));
$request->expects($this->at(3))->method('is')
->with('put')
->will($this->returnValue(false));
$this->RequestHandler->request = $request;
$this->assertTrue($this->RequestHandler->isGet());
$this->assertFalse($this->RequestHandler->isPost());
$this->assertFalse($this->RequestHandler->isPut());
$this->assertFalse($this->RequestHandler->isDelete());
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->assertFalse($this->RequestHandler->isGet());
$this->assertTrue($this->RequestHandler->isPost());
$this->assertFalse($this->RequestHandler->isPut());
$this->assertFalse($this->RequestHandler->isDelete());
$_SERVER['REQUEST_METHOD'] = 'PUT';
$this->assertFalse($this->RequestHandler->isGet());
$this->assertFalse($this->RequestHandler->isPost());
$this->assertTrue($this->RequestHandler->isPut());
$this->assertFalse($this->RequestHandler->isDelete());
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$this->assertFalse($this->RequestHandler->isGet());
$this->assertFalse($this->RequestHandler->isPost());
$this->assertFalse($this->RequestHandler->isPut());
$this->assertTrue($this->RequestHandler->isDelete());
$this->assertFalse($this->RequestHandler->isPut());
}
/**
* testClientContentPreference method
* test that map alias converts aliases to content types.
*
* @return void
*/
function testMapAlias() {
$result = $this->RequestHandler->mapAlias('xml');
$this->assertEquals('application/xml', $result);
$result = $this->RequestHandler->mapAlias('text/html');
$this->assertNull($result);
$result = $this->RequestHandler->mapAlias('wap');
$this->assertEquals('text/vnd.wap.wml', $result);
$result = $this->RequestHandler->mapAlias(array('xml', 'js', 'json'));
$expected = array('application/xml', 'text/javascript', 'application/json');
$this->assertEquals($expected, $result);
}
/**
* test accepts() on the component
*
* @return void
*/
function testAccepts() {
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$this->assertEqual($this->RequestHandler->accepts(array('js', 'xml', 'html')), 'xml');
$this->assertFalse($this->RequestHandler->accepts(array('gif', 'jpeg', 'foo')));
$_SERVER['HTTP_ACCEPT'] = '*/*;q=0.5';
$this->assertFalse($this->RequestHandler->accepts('rss'));
}
/**
* test accepts and prefers methods.
*
* @access public
* @return void
*/
function testClientContentPreference() {
function testPrefers() {
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertNotEqual($this->RequestHandler->prefers(), 'rss');
$this->RequestHandler->ext = 'rss';
$this->assertEqual($this->RequestHandler->prefers(), 'rss');
$this->assertFalse($this->RequestHandler->prefers('xml'));
$this->assertEqual($this->RequestHandler->prefers(array('js', 'xml', 'xhtml')), 'xml');
$this->assertTrue($this->RequestHandler->accepts('xml'));
$this->assertFalse($this->RequestHandler->prefers(array('red', 'blue')));
$this->assertEqual($this->RequestHandler->prefers(array('js', 'json', 'xhtml')), 'xhtml');
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$this->_init();
$this->assertEqual($this->RequestHandler->prefers(), 'xml');
$this->assertEqual($this->RequestHandler->accepts(array('js', 'xml', 'html')), 'xml');
$this->assertFalse($this->RequestHandler->accepts(array('gif', 'jpeg', 'foo')));
$_SERVER['HTTP_ACCEPT'] = '*/*;q=0.5';
$this->_init();
$this->assertEqual($this->RequestHandler->prefers(), 'html');
$this->assertFalse($this->RequestHandler->prefers('rss'));
$this->assertFalse($this->RequestHandler->accepts('rss'));
}
/**
@ -588,15 +588,9 @@ class RequestHandlerComponentTest extends CakeTestCase {
*/
function testCustomContent() {
$_SERVER['HTTP_ACCEPT'] = 'text/x-mobile,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5';
$this->_init();
$this->RequestHandler->setContent('mobile', 'text/x-mobile');
$this->RequestHandler->startup($this->Controller);
$this->assertEqual($this->RequestHandler->prefers(), 'mobile');
$this->_init();
$this->RequestHandler->setContent(array('mobile' => 'text/x-mobile'));
$this->RequestHandler->startup($this->Controller);
$this->assertEqual($this->RequestHandler->prefers(), 'mobile');
}
/**
@ -606,26 +600,14 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testClientProperties() {
$_SERVER['HTTP_HOST'] = 'localhost:80';
$this->assertEqual($this->RequestHandler->getReferer(), 'localhost');
$_SERVER['HTTP_HOST'] = null;
$_SERVER['HTTP_X_FORWARDED_HOST'] = 'cakephp.org';
$this->assertEqual($this->RequestHandler->getReferer(), 'cakephp.org');
$request = $this->getMock('CakeRequest');
$request->expects($this->once())->method('referer');
$request->expects($this->once())->method('clientIp')->will($this->returnValue(false));
$_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.1.5, 10.0.1.1, proxy.com';
$_SERVER['HTTP_CLIENT_IP'] = '192.168.1.2';
$_SERVER['REMOTE_ADDR'] = '192.168.1.3';
$this->assertEqual($this->RequestHandler->getClientIP(false), '192.168.1.5');
$this->assertEqual($this->RequestHandler->getClientIP(), '192.168.1.2');
$this->RequestHandler->request = $request;
unset($_SERVER['HTTP_X_FORWARDED_FOR']);
$this->assertEqual($this->RequestHandler->getClientIP(), '192.168.1.2');
unset($_SERVER['HTTP_CLIENT_IP']);
$this->assertEqual($this->RequestHandler->getClientIP(), '192.168.1.3');
$_SERVER['HTTP_CLIENTADDRESS'] = '10.0.1.2, 10.0.1.1';
$this->assertEqual($this->RequestHandler->getClientIP(), '10.0.1.2');
$this->RequestHandler->getReferer();
$this->RequestHandler->getClientIP(false);
}
/**
@ -634,13 +616,16 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testAjaxRedirectAsRequestAction() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->_init();
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
), true);
$this->Controller->RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$this->Controller->request = $this->getMock('CakeRequest');
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
$this->Controller->RequestHandler->request = $this->Controller->request;
$this->Controller->RequestHandler->response = $this->Controller->response;
$this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
$this->Controller->RequestHandler->expects($this->once())->method('_stop');
ob_start();
@ -650,7 +635,6 @@ class RequestHandlerComponentTest extends CakeTestCase {
$result = ob_get_clean();
$this->assertPattern('/posts index/', $result, 'RequestAction redirect failed.');
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
App::build();
}
@ -661,13 +645,16 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testAjaxRedirectAsRequestActionStillRenderingLayout() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->_init();
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
), true);
$this->Controller->RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$this->Controller->request = $this->getMock('CakeRequest');
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
$this->Controller->RequestHandler->request = $this->Controller->request;
$this->Controller->RequestHandler->response = $this->Controller->response;
$this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
$this->Controller->RequestHandler->expects($this->once())->method('_stop');
ob_start();
@ -678,7 +665,6 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->assertPattern('/posts index/', $result, 'RequestAction redirect failed.');
$this->assertPattern('/Ajax!/', $result, 'Layout was not rendered.');
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
App::build();
}
@ -699,6 +685,9 @@ class RequestHandlerComponentTest extends CakeTestCase {
));
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader'));
$RequestHandler->request = new CakeRequest('posts/index');
$RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader'));
ob_start();
$RequestHandler->beforeRedirect(
@ -719,8 +708,13 @@ class RequestHandlerComponentTest extends CakeTestCase {
$controller = $this->getMock('Controller', array('header'));
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader','statusCode'));
$RequestHandler->request = $this->getMock('CakeRequest');
$RequestHandler->request->expects($this->once())->method('is')
->with('ajax')
->will($this->returnValue(true));
$controller->expects($this->once())->method('header')->with('HTTP/1.1 403 Forbidden');
$RequestHandler->response->expects($this->once())->method('statusCode')->with(403);
ob_start();
$RequestHandler->beforeRedirect($controller, 'request_handler_test/param_method/first/second', 403);

View file

@ -17,6 +17,7 @@
* @since CakePHP(tm) v 1.2.0.5435
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Controller', 'Controller', false);
App::import('Component', 'Security');
/**
@ -143,9 +144,9 @@ class SecurityComponentTest extends CakeTestCase {
* @return void
*/
function startTest() {
$this->Controller =& new SecurityTestController();
$this->Controller = new SecurityTestController(new CakeRequest(null, false));
$this->Controller->Components->init($this->Controller);
$this->Controller->Security =& $this->Controller->TestSecurity;
$this->Controller->Security = $this->Controller->TestSecurity;
$this->Controller->Security->blackHoleCallback = 'fail';
$this->oldSalt = Configure::read('Security.salt');
Configure::write('Security.salt', 'foo!');
@ -212,7 +213,7 @@ class SecurityComponentTest extends CakeTestCase {
*/
function testRequirePostFail() {
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requirePost(array('posted'));
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
@ -226,7 +227,7 @@ class SecurityComponentTest extends CakeTestCase {
*/
function testRequirePostSucceed() {
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requirePost('posted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -241,7 +242,7 @@ class SecurityComponentTest extends CakeTestCase {
function testRequireSecureFail() {
$_SERVER['HTTPS'] = 'off';
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireSecure(array('posted'));
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
@ -255,7 +256,7 @@ class SecurityComponentTest extends CakeTestCase {
*/
function testRequireSecureSucceed() {
$_SERVER['REQUEST_METHOD'] = 'Secure';
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$_SERVER['HTTPS'] = 'on';
$this->Controller->Security->requireSecure('posted');
$this->Controller->Security->startup($this->Controller);
@ -270,15 +271,15 @@ class SecurityComponentTest extends CakeTestCase {
*/
function testRequireAuthFail() {
$_SERVER['REQUEST_METHOD'] = 'AUTH';
$this->Controller->action = 'posted';
$this->Controller->data = array('username' => 'willy', 'password' => 'somePass');
$this->Controller->request['action'] = 'posted';
$this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass');
$this->Controller->Security->requireAuth(array('posted'));
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
$this->Controller->Session->write('_Token', serialize(array('allowedControllers' => array())));
$this->Controller->data = array('username' => 'willy', 'password' => 'somePass');
$this->Controller->action = 'posted';
$this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass');
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireAuth('posted');
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
@ -286,8 +287,8 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Session->write('_Token', serialize(array(
'allowedControllers' => array('SecurityTest'), 'allowedActions' => array('posted2')
)));
$this->Controller->data = array('username' => 'willy', 'password' => 'somePass');
$this->Controller->action = 'posted';
$this->Controller->request->data = array('username' => 'willy', 'password' => 'somePass');
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireAuth('posted');
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
@ -301,7 +302,7 @@ class SecurityComponentTest extends CakeTestCase {
*/
function testRequireAuthSucceed() {
$_SERVER['REQUEST_METHOD'] = 'AUTH';
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireAuth('posted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -309,10 +310,10 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->Session->write('_Token', serialize(array(
'allowedControllers' => array('SecurityTest'), 'allowedActions' => array('posted')
)));
$this->Controller->params['controller'] = 'SecurityTest';
$this->Controller->params['action'] = 'posted';
$this->Controller->request['controller'] = 'SecurityTest';
$this->Controller->request['action'] = 'posted';
$this->Controller->data = array(
$this->Controller->request->data = array(
'username' => 'willy', 'password' => 'somePass', '_Token' => ''
);
$this->Controller->action = 'posted';
@ -329,7 +330,7 @@ class SecurityComponentTest extends CakeTestCase {
*/
function testRequirePostSucceedWrongMethod() {
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->Controller->action = 'getted';
$this->Controller->request['action'] = 'getted';
$this->Controller->Security->requirePost('posted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -343,7 +344,7 @@ class SecurityComponentTest extends CakeTestCase {
*/
function testRequireGetFail() {
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->action = 'getted';
$this->Controller->request['action'] = 'getted';
$this->Controller->Security->requireGet(array('getted'));
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
@ -357,7 +358,7 @@ class SecurityComponentTest extends CakeTestCase {
*/
function testRequireGetSucceed() {
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->Controller->action = 'getted';
$this->Controller->request['action'] = 'getted';
$this->Controller->Security->requireGet('getted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -370,7 +371,7 @@ class SecurityComponentTest extends CakeTestCase {
* @return void
*/
function testRequireLogin() {
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireLogin(
'posted',
array('type' => 'basic', 'users' => array('admin' => 'password'))
@ -381,7 +382,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->assertFalse($this->Controller->failed);
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireLogin(
array('posted'),
array('type' => 'basic', 'users' => array('admin' => 'password'))
@ -391,7 +392,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireLogin(
'posted',
array('type' => 'basic', 'users' => array('admin' => 'password'))
@ -417,7 +418,7 @@ class SecurityComponentTest extends CakeTestCase {
return;
}
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$_SERVER['PHP_AUTH_DIGEST'] = $digest = <<<DIGEST
Digest username="Mufasa",
realm="testrealm@host.com",
@ -445,7 +446,7 @@ DIGEST;
*/
function testRequireGetSucceedWrongMethod() {
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireGet('getted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -459,7 +460,7 @@ DIGEST;
*/
function testRequirePutFail() {
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->action = 'putted';
$this->Controller->request['action'] = 'putted';
$this->Controller->Security->requirePut(array('putted'));
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
@ -473,7 +474,7 @@ DIGEST;
*/
function testRequirePutSucceed() {
$_SERVER['REQUEST_METHOD'] = 'PUT';
$this->Controller->action = 'putted';
$this->Controller->request['action'] = 'putted';
$this->Controller->Security->requirePut('putted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -487,7 +488,7 @@ DIGEST;
*/
function testRequirePutSucceedWrongMethod() {
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requirePut('putted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -501,7 +502,7 @@ DIGEST;
*/
function testRequireDeleteFail() {
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->action = 'deleted';
$this->Controller->request['action'] = 'deleted';
$this->Controller->Security->requireDelete(array('deleted', 'other_method'));
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed);
@ -515,7 +516,7 @@ DIGEST;
*/
function testRequireDeleteSucceed() {
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$this->Controller->action = 'deleted';
$this->Controller->request['action'] = 'deleted';
$this->Controller->Security->requireDelete('deleted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -529,7 +530,7 @@ DIGEST;
*/
function testRequireDeleteSucceedWrongMethod() {
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->action = 'posted';
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireDelete('deleted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
@ -572,11 +573,11 @@ DIGEST;
*/
function testValidatePost() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3An%3A1%3A%7Bv%3A0%3B';
$fields .= 'f%3A11%3A%22Zbqry.inyvq%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'),
'_Token' => compact('key', 'fields')
);
@ -594,14 +595,14 @@ DIGEST;
$fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3An%3A1%3A%7Bv%3A0%3B';
$fields .= 'f%3A11%3A%22Zbqry.inyvq%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'),
'_Token' => compact('key')
);
$result = $this->Controller->Security->validatePost($this->Controller);
$this->assertFalse($result, 'validatePost passed when fields were missing. %s');
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'),
'_Token' => compact('fields')
);
@ -616,10 +617,10 @@ DIGEST;
*/
function testValidatePostArray() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'f7d573650a295b94e0938d32b323fde775e5f32b%3An%3A0%3A%7B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array('multi_field' => array('1', '3')),
'_Token' => compact('key', 'fields')
);
@ -634,10 +635,10 @@ DIGEST;
*/
function testValidatePostNoModel() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '540ac9c60d323c22bafe997b72c0790f39a8bdef%3An%3A0%3A%7B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'anything' => 'some_data',
'_Token' => compact('key', 'fields')
);
@ -654,10 +655,10 @@ DIGEST;
*/
function testValidatePostSimple() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '69f493434187b867ea14b901fdf58b55d27c935d%3An%3A0%3A%7B%7D';
$this->Controller->data = $data = array(
$this->Controller->request->data = $data = array(
'Model' => array('username' => '', 'password' => ''),
'_Token' => compact('key', 'fields')
);
@ -674,11 +675,11 @@ DIGEST;
*/
function testValidatePostComplex() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'c9118120e680a7201b543f562e5301006ccfcbe2%3An%3A2%3A%7Bv%3A0%3Bf%3A14%3A%';
$fields .= '22Nqqerffrf.0.vq%22%3Bv%3A1%3Bf%3A14%3A%22Nqqerffrf.1.vq%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Addresses' => array(
'0' => array(
'id' => '123456', 'title' => '', 'first_name' => '', 'last_name' => '',
@ -702,24 +703,24 @@ DIGEST;
*/
function testValidatePostMultipleSelect() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '422cde416475abc171568be690a98cad20e66079%3An%3A0%3A%7B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Tag' => array('Tag' => array(1, 2)),
'_Token' => compact('key', 'fields'),
);
$result = $this->Controller->Security->validatePost($this->Controller);
$this->assertTrue($result);
$this->Controller->data = array(
$this->Controller->request->data = array(
'Tag' => array('Tag' => array(1, 2, 3)),
'_Token' => compact('key', 'fields'),
);
$result = $this->Controller->Security->validatePost($this->Controller);
$this->assertTrue($result);
$this->Controller->data = array(
$this->Controller->request->data = array(
'Tag' => array('Tag' => array(1, 2, 3, 4)),
'_Token' => compact('key', 'fields'),
);
@ -727,7 +728,7 @@ DIGEST;
$this->assertTrue($result);
$fields = '19464422eafe977ee729c59222af07f983010c5f%3An%3A0%3A%7B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'User.password' => 'bar', 'User.name' => 'foo', 'User.is_valid' => '1',
'Tag' => array('Tag' => array(1)), '_Token' => compact('key', 'fields'),
);
@ -746,11 +747,11 @@ DIGEST;
*/
function testValidatePostCheckbox() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3An%3A1%3A%7Bv%3A0%';
$fields .= '3Bf%3A11%3A%22Zbqry.inyvq%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
'_Token' => compact('key', 'fields')
);
@ -760,7 +761,7 @@ DIGEST;
$fields = '874439ca69f89b4c4a5f50fb9c36ff56a28f5d42%3An%3A0%3A%7B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
'_Token' => compact('key', 'fields')
);
@ -769,11 +770,11 @@ DIGEST;
$this->assertTrue($result);
$this->Controller->data = array();
$this->Controller->request->data = array();
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$this->Controller->data = $data = array(
$this->Controller->request->data = $data = array(
'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
'_Token' => compact('key', 'fields')
);
@ -790,11 +791,11 @@ DIGEST;
*/
function testValidatePostHidden() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '51ccd8cb0997c7b3d4523ecde5a109318405ef8c%3An%3A2%3A%7Bv%3A0%3Bf%3A12%3A';
$fields .= '%22Zbqry.uvqqra%22%3Bv%3A1%3Bf%3A18%3A%22Zbqry.bgure_uvqqra%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array(
'username' => '', 'password' => '', 'hidden' => '0',
'other_hidden' => 'some hidden value'
@ -814,11 +815,11 @@ DIGEST;
function testValidatePostWithDisabledFields() {
$this->Controller->Security->disabledFields = array('Model.username', 'Model.password');
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'ef1082968c449397bcd849f963636864383278b1%3An%3A1%3A%7Bv%';
$fields .= '3A0%3Bf%3A12%3A%22Zbqry.uvqqra%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array(
'username' => '', 'password' => '', 'hidden' => '0'
),
@ -837,12 +838,12 @@ DIGEST;
*/
function testValidateHiddenMultipleModel() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'a2d01072dc4660eea9d15007025f35a7a5b58e18%3An%3A3%3A%7Bv%3A0%3Bf%3A11';
$fields .= '%3A%22Zbqry.inyvq%22%3Bv%3A1%3Bf%3A12%3A%22Zbqry2.inyvq%22%3Bv%3A2%';
$fields .= '3Bf%3A12%3A%22Zbqry3.inyvq%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
'Model2' => array('valid' => '0'),
'Model3' => array('valid' => '0'),
@ -870,12 +871,12 @@ DIGEST;
*/
function testValidateHasManyModel() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '51e3b55a6edd82020b3f29c9ae200e14bbeb7ee5%3An%3A4%3A%7Bv%3A0%3Bf%3A14%3A%2';
$fields .= '2Zbqry.0.uvqqra%22%3Bv%3A1%3Bf%3A13%3A%22Zbqry.0.inyvq%22%3Bv%3A2%3Bf%3';
$fields .= 'A14%3A%22Zbqry.1.uvqqra%22%3Bv%3A3%3Bf%3A13%3A%22Zbqry.1.inyvq%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Model' => array(
array(
'username' => 'username', 'password' => 'password',
@ -901,12 +902,12 @@ DIGEST;
*/
function testValidateHasManyRecordsPass() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3An%3A4%3A%7Bv%3A0%3Bf%3A12%3A%2';
$fields .= '2Nqqerff.0.vq%22%3Bv%3A1%3Bf%3A17%3A%22Nqqerff.0.cevznel%22%3Bv%3A2%3Bf%';
$fields .= '3A12%3A%22Nqqerff.1.vq%22%3Bv%3A3%3Bf%3A17%3A%22Nqqerff.1.cevznel%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Address' => array(
0 => array(
'id' => '123',
@ -946,12 +947,12 @@ DIGEST;
*/
function testValidateHasManyRecordsFail() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3An%3A4%3A%7Bv%3A0%3Bf%3A12%3A%2';
$fields .= '2Nqqerff.0.vq%22%3Bv%3A1%3Bf%3A17%3A%22Nqqerff.0.cevznel%22%3Bv%3A2%3Bf%';
$fields .= '3A12%3A%22Nqqerff.1.vq%22%3Bv%3A3%3Bf%3A17%3A%22Nqqerff.1.cevznel%22%3B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'Address' => array(
0 => array(
'id' => '123',
@ -1121,10 +1122,10 @@ DIGEST;
*/
function testFormDisabledFields() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '11842060341b9d0fc3808b90ba29fdea7054d6ad%3An%3A0%3A%7B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'MyModel' => array('name' => 'some data'),
'_Token' => compact('key', 'fields')
);
@ -1133,9 +1134,9 @@ DIGEST;
$this->Controller->Security->startup($this->Controller);
$this->Controller->Security->disabledFields = array('MyModel.name');
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$this->Controller->data = array(
$this->Controller->request->data = array(
'MyModel' => array('name' => 'some data'),
'_Token' => compact('key', 'fields')
);
@ -1152,30 +1153,30 @@ DIGEST;
*/
function testRadio() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$fields = '575ef54ca4fc8cab468d6d898e9acd3a9671c17e%3An%3A0%3A%7B%7D';
$this->Controller->data = array(
$this->Controller->request->data = array(
'_Token' => compact('key', 'fields')
);
$result = $this->Controller->Security->validatePost($this->Controller);
$this->assertFalse($result);
$this->Controller->data = array(
$this->Controller->request->data = array(
'_Token' => compact('key', 'fields'),
'Test' => array('test' => '')
);
$result = $this->Controller->Security->validatePost($this->Controller);
$this->assertTrue($result);
$this->Controller->data = array(
$this->Controller->request->data = array(
'_Token' => compact('key', 'fields'),
'Test' => array('test' => '1')
);
$result = $this->Controller->Security->validatePost($this->Controller);
$this->assertTrue($result);
$this->Controller->data = array(
$this->Controller->request->data = array(
'_Token' => compact('key', 'fields'),
'Test' => array('test' => '2')
);
@ -1212,13 +1213,13 @@ DIGEST;
*/
function testSettingTokenForRequestAction() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->params['_Token']['key'];
$key = $this->Controller->request->params['_Token']['key'];
$this->Controller->params['requested'] = 1;
unset($this->Controller->params['_Token']);
unset($this->Controller->request->params['_Token']);
$this->Controller->Security->startup($this->Controller);
$this->assertEqual($this->Controller->params['_Token']['key'], $key);
$this->assertEqual($this->Controller->request->params['_Token']['key'], $key);
}
/**

View file

@ -18,6 +18,7 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Controller', 'Controller', false);
App::import('Core', array('CakeRequest', 'CakeResponse'));
App::import('Component', 'Security');
App::import('Component', 'Cookie');
@ -458,7 +459,8 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testLoadModel() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$this->assertFalse(isset($Controller->ControllerPost));
@ -507,7 +509,9 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testConstructClasses() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->modelClass = 'ControllerPost';
$Controller->passedArgs[] = '1';
$Controller->constructClasses();
@ -515,7 +519,7 @@ class ControllerTest extends CakeTestCase {
unset($Controller);
$Controller = new Controller();
$Controller = new Controller($request);
$Controller->uses = array('ControllerPost', 'ControllerComment');
$Controller->passedArgs[] = '1';
$Controller->constructClasses();
@ -528,7 +532,7 @@ class ControllerTest extends CakeTestCase {
App::build(array('plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)));
$Controller = new Controller();
$Controller = new Controller($request);
$Controller->uses = array('TestPlugin.TestPluginPost');
$Controller->constructClasses();
@ -546,7 +550,8 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testAliasName() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->uses = array('NameTest');
$Controller->constructClasses();
@ -586,7 +591,10 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testPaginate() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$request->params['pass'] = $request->params['named'] = array();
$Controller = new Controller($request);
$Controller->uses = array('ControllerPost', 'ControllerComment');
$Controller->passedArgs[] = '1';
$Controller->params['url'] = array();
@ -672,7 +680,11 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testPaginateExtraParams() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$request->params['pass'] = $request->params['named'] = array();
$Controller = new Controller($request);
$Controller->uses = array('ControllerPost', 'ControllerComment');
$Controller->passedArgs[] = '1';
$Controller->params['url'] = array();
@ -704,7 +716,7 @@ class ControllerTest extends CakeTestCase {
$this->assertEqual($Controller->ControllerPost->lastQuery['limit'], 12);
$this->assertEqual($paging['options']['limit'], 12);
$Controller = new Controller();
$Controller = new Controller($request);
$Controller->uses = array('ControllerPaginateModel');
$Controller->params['url'] = array();
$Controller->constructClasses();
@ -731,7 +743,10 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
public function testPaginatePassedArgs() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$request->params['pass'] = $request->params['named'] = array();
$Controller = new Controller($request);
$Controller->uses = array('ControllerPost');
$Controller->passedArgs[] = array('1', '2', '3');
$Controller->params['url'] = array();
@ -764,7 +779,10 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testPaginateSpecialType() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$request->params['pass'] = $request->params['named'] = array();
$Controller = new Controller($request);
$Controller->uses = array('ControllerPost', 'ControllerComment');
$Controller->passedArgs[] = '1';
$Controller->params['url'] = array();
@ -786,7 +804,10 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testDefaultPaginateParams() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$request->params['pass'] = $request->params['named'] = array();
$Controller = new Controller($request);
$Controller->modelClass = 'ControllerPost';
$Controller->params['url'] = array();
$Controller->paginate = array('order' => 'ControllerPost.id DESC');
@ -803,7 +824,10 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testPaginateOrderVirtualField() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$request->params['pass'] = $request->params['named'] = array();
$Controller = new Controller($request);
$Controller->uses = array('ControllerPost', 'ControllerComment');
$Controller->params['url'] = array();
$Controller->constructClasses();
@ -830,9 +854,11 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testFlash() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request, $this->getMock('CakeResponse', array('_sendHeader')));
$Controller->flash('this should work', '/flash');
$result = $Controller->output;
$result = $Controller->response->body();
$expected = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
@ -854,9 +880,9 @@ class ControllerTest extends CakeTestCase {
$this->assertEqual($result, $expected);
App::build(array('views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)));
$Controller = new Controller();
$Controller = new Controller(null, $this->getMock('CakeResponse', array('_sendHeader')));
$Controller->flash('this should work', '/flash', 1, 'ajax2');
$result = $Controller->output;
$result = $Controller->response->body();
$this->assertPattern('/Ajax!/', $result);
App::build();
}
@ -868,7 +894,9 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testControllerSet() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->set('variable_with_underscores', null);
$this->assertTrue(array_key_exists('variable_with_underscores', $Controller->viewVars));
@ -906,8 +934,10 @@ class ControllerTest extends CakeTestCase {
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
), true);
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller();
$Controller = new Controller($request, $this->getMock('CakeResponse'));
$Controller->viewPath = 'posts';
$result = $Controller->render('index');
@ -916,7 +946,7 @@ class ControllerTest extends CakeTestCase {
$result = $Controller->render('/elements/test_element');
$this->assertPattern('/this is the test element/', $result);
$Controller = new TestController();
$Controller = new TestController($request);
$Controller->constructClasses();
$Controller->ControllerComment->validationErrors = array('title' => 'tooShort');
$expected = $Controller->ControllerComment->validationErrors;
@ -947,7 +977,7 @@ class ControllerTest extends CakeTestCase {
$core[0]
)
), true);
$Controller =& new Controller();
$Controller =& new Controller(null, $this->getMock('CakeResponse'));
$Controller->uses = array();
$Controller->components = array('Test');
$Controller->constructClasses();
@ -966,7 +996,9 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testToBeInheritedGuardmethods() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$this->assertTrue($Controller->_beforeScaffold(''));
$this->assertTrue($Controller->_afterScaffoldSave(''));
$this->assertTrue($Controller->_afterScaffoldSaveError(''));
@ -980,45 +1012,13 @@ class ControllerTest extends CakeTestCase {
*/
public static function statusCodeProvider() {
return array(
array(100, "Continue"),
array(101, "Switching Protocols"),
array(200, "OK"),
array(201, "Created"),
array(202, "Accepted"),
array(203, "Non-Authoritative Information"),
array(204, "No Content"),
array(205, "Reset Content"),
array(206, "Partial Content"),
array(300, "Multiple Choices"),
array(301, "Moved Permanently"),
array(302, "Found"),
array(303, "See Other"),
array(304, "Not Modified"),
array(305, "Use Proxy"),
array(307, "Temporary Redirect"),
array(400, "Bad Request"),
array(401, "Unauthorized"),
array(402, "Payment Required"),
array(403, "Forbidden"),
array(404, "Not Found"),
array(405, "Method Not Allowed"),
array(406, "Not Acceptable"),
array(407, "Proxy Authentication Required"),
array(408, "Request Time-out"),
array(409, "Conflict"),
array(410, "Gone"),
array(411, "Length Required"),
array(412, "Precondition Failed"),
array(413, "Request Entity Too Large"),
array(414, "Request-URI Too Large"),
array(415, "Unsupported Media Type"),
array(416, "Requested range not satisfiable"),
array(417, "Expectation Failed"),
array(500, "Internal Server Error"),
array(501, "Not Implemented"),
array(502, "Bad Gateway"),
array(503, "Service Unavailable"),
array(504, "Gateway Time-out"),
array(307, "Temporary Redirect")
);
}
@ -1030,16 +1030,14 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testRedirectByCode($code, $msg) {
$Controller = $this->getMock('Controller', array('header'));
$Controller = new Controller(null, $this->getMock('CakeResponse', array('header', 'statusCode')));
$Controller->Components = $this->getMock('ComponentCollection');
$Controller->expects($this->at(0))->method('header')
->with("HTTP/1.1 {$code} {$msg}");
$Controller->expects($this->at(1))->method('header')
->with('Location: http://cakephp.org');
$Controller->expects($this->exactly(2))->method('header');
$Controller->Component = new Component();
$Controller->Component->init($Controller);
$Controller->response->expects($this->once())->method('statusCode')
->with($code);
$Controller->response->expects($this->once())->method('header')
->with('Location', 'http://cakephp.org');
$Controller->redirect('http://cakephp.org', (int)$code, false);
$this->assertFalse($Controller->autoRender);
@ -1052,17 +1050,16 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testRedirectByMessage($code, $msg) {
$Controller = $this->getMock('Controller', array('header'));
$Controller = new Controller(null, $this->getMock('CakeResponse', array('header', 'statusCode')));
$Controller->Components = $this->getMock('ComponentCollection');
$Controller->expects($this->at(0))->method('header')
->with("HTTP/1.1 {$code} {$msg}");
$Controller->response->expects($this->once())->method('statusCode')
->with($code);
$Controller->expects($this->at(1))->method('header')
->with('Location: http://cakephp.org');
$Controller->response->expects($this->once())->method('header')
->with('Location', 'http://cakephp.org');
$Controller->expects($this->exactly(2))->method('header');
$Controller->redirect('http://cakephp.org', $msg, false);
$this->assertFalse($Controller->autoRender);
}
@ -1073,17 +1070,17 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testRedirectTriggeringComponentsReturnNull() {
$Controller = $this->getMock('Controller', array('header'));
$Controller->Components = $this->getMock('ComponentCollection');
$Controller = new Controller(null, $this->getMock('CakeResponse', array('header', 'statusCode')));
$Controller->Component = $this->getMock('Component');
$Controller->Components->expects($this->once())->method('trigger')
->will($this->returnValue(null));
$Controller->expects($this->at(0))->method('header')
->with('HTTP/1.1 301 Moved Permanently');
$Controller->response->expects($this->once())->method('statusCode')
->with(301);
$Controller->expects($this->at(1))->method('header')
->with('Location: http://cakephp.org');
$Controller->response->expects($this->once())->method('header')
->with('Location', 'http://cakephp.org');
$Controller->redirect('http://cakephp.org', 301, false);
}
@ -1094,17 +1091,17 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testRedirectBeforeRedirectModifyingParams() {
$Controller = $this->getMock('Controller', array('header'));
$Controller->Components = $this->getMock('ComponentCollection');
$Controller = new Controller(null, $this->getMock('CakeResponse', array('header', 'statusCode')));
$Controller->Component = $this->getMock('Component');
$Controller->Components->expects($this->once())->method('trigger')
->will($this->returnValue(array('http://book.cakephp.org')));
$Controller->expects($this->at(0))->method('header')
->with('HTTP/1.1 301 Moved Permanently');
$Controller->response->expects($this->once())->method('statusCode')
->with(301);
$Controller->expects($this->at(1))->method('header')
->with('Location: http://book.cakephp.org');
$Controller->response->expects($this->once())->method('header')
->with('Location', 'http://book.cakephp.org');
$Controller->redirect('http://cakephp.org', 301, false);
}
@ -1116,6 +1113,7 @@ class ControllerTest extends CakeTestCase {
*/
function testRedirectBeforeRedirectModifyingParamsArrayReturn() {
$Controller = $this->getMock('Controller', array('header', '_stop'));
$Controller->response = $this->getMock('CakeResponse');
$Controller->Components = $this->getMock('ComponentCollection');
$return = array(
@ -1151,8 +1149,10 @@ class ControllerTest extends CakeTestCase {
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
$request = new CakeRequest('controller_posts/index');
$TestController = new TestController();
$TestController = new TestController($request);
$TestController->constructClasses();
$testVars = get_class_vars('TestController');
@ -1175,7 +1175,8 @@ class ControllerTest extends CakeTestCase {
$this->assertEqual(count(array_diff($TestController->uses, $uses)), 0);
$this->assertEqual(count(array_diff_assoc(Set::normalize($TestController->components), Set::normalize($components))), 0);
$TestController = new AnotherTestController();
$TestController = new AnotherTestController($request);
$TestController->constructClasses();
$appVars = get_class_vars('AppController');
@ -1188,7 +1189,7 @@ class ControllerTest extends CakeTestCase {
$this->assertFalse(isset($TestController->ControllerPost));
$TestController = new ControllerCommentsController();
$TestController = new ControllerCommentsController($request);
$TestController->constructClasses();
$appVars = get_class_vars('AppController');
@ -1212,7 +1213,10 @@ class ControllerTest extends CakeTestCase {
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
$TestController = new TestController();
$request = new CakeRequest('controller_posts/index');
$TestController = new TestController($request);
$expected = array('foo');
$TestController->components = array('Cookie' => $expected);
$TestController->constructClasses();
@ -1226,7 +1230,9 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testMergeVarsNotGreedy() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->components = array();
$Controller->uses = array();
$Controller->constructClasses();
@ -1241,54 +1247,34 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testReferer() {
$Controller = new Controller();
$_SERVER['HTTP_REFERER'] = 'http://cakephp.org';
$result = $Controller->referer(null, false);
$expected = 'http://cakephp.org';
$this->assertIdentical($result, $expected);
$request = $this->getMock('CakeRequest');
$_SERVER['HTTP_REFERER'] = '';
$result = $Controller->referer('http://cakephp.org', false);
$expected = 'http://cakephp.org';
$this->assertIdentical($result, $expected);
$request->expects($this->any())->method('referer')
->with(true)
->will($this->returnValue('/posts/index'));
$_SERVER['HTTP_REFERER'] = '';
$referer = array(
'controller' => 'pages',
'action' => 'display',
'home'
);
$result = $Controller->referer($referer, false);
$expected = 'http://' . env('HTTP_HOST') . '/pages/display/home';
$this->assertIdentical($result, $expected);
$Controller = new Controller($request);
$result = $Controller->referer(null, true);
$this->assertEqual($result, '/posts/index');
$_SERVER['HTTP_REFERER'] = '';
$result = $Controller->referer(null, false);
$expected = '/';
$this->assertIdentical($result, $expected);
$Controller = new Controller($request);
$request->setReturnValue('referer', '/', array(true));
$result = $Controller->referer(array('controller' => 'posts', 'action' => 'index'), true);
$this->assertEqual($result, '/posts/index');
$_SERVER['HTTP_REFERER'] = FULL_BASE_URL.$Controller->webroot.'/some/path';
$result = $Controller->referer(null, false);
$expected = '/some/path';
$this->assertIdentical($result, $expected);
$request = $this->getMock('CakeRequest');
$request->expects($this->any())->method('referer')
->with(false)
->will($this->returnValue('http://localhost/posts/index'));
$Controller->webroot .= '/';
$_SERVER['HTTP_REFERER'] = FULL_BASE_URL.$Controller->webroot.'/some/path';
$result = $Controller->referer(null, false);
$expected = '/some/path';
$this->assertIdentical($result, $expected);
$_SERVER['HTTP_REFERER'] = FULL_BASE_URL.$Controller->webroot.'some/path';
$result = $Controller->referer(null, false);
$expected = '/some/path';
$this->assertIdentical($result, $expected);
$Controller->webroot = '/recipe/';
$_SERVER['HTTP_REFERER'] = FULL_BASE_URL.$Controller->webroot.'recipes/add';
$Controller = new Controller($request);
$result = $Controller->referer();
$expected = '/recipes/add';
$this->assertIdentical($result, $expected);
$this->assertEqual($result, 'http://localhost/posts/index');
$Controller = new Controller(null);
$result = $Controller->referer();
$this->assertEqual($result, '/');
}
/**
@ -1298,7 +1284,9 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testSetAction() {
$TestController = new TestController();
$request = new CakeRequest('controller_posts/index');
$TestController = new TestController($request);
$TestController->setAction('index', 1, 2);
$expected = array('testId' => 1, 'test2Id' => 2);
$this->assertidentical($TestController->data, $expected);
@ -1312,7 +1300,9 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testUnimplementedIsAuthorized() {
$TestController = new TestController();
$request = new CakeRequest('controller_posts/index');
$TestController = new TestController($request);
$TestController->isAuthorized();
}
@ -1323,14 +1313,17 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testValidateErrors() {
$TestController = new TestController();
$request = new CakeRequest('controller_posts/index');
$TestController = new TestController($request);
$TestController->constructClasses();
$this->assertFalse($TestController->validateErrors());
$this->assertEqual($TestController->validate(), 0);
$TestController->ControllerComment->invalidate('some_field', 'error_message');
$TestController->ControllerComment->invalidate('some_field2', 'error_message2');
$comment =& new ControllerComment();
$comment = new ControllerComment($request);
$comment->set('someVar', 'data');
$result = $TestController->validateErrors($comment);
$expected = array('some_field' => 'error_message', 'some_field2' => 'error_message2');
@ -1362,8 +1355,9 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testPostConditions() {
$Controller = new Controller();
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$data = array(
'Model1' => array('field1' => '23'),
@ -1421,41 +1415,43 @@ class ControllerTest extends CakeTestCase {
}
/**
* testRequestHandlerPrefers method
*
* @access public
* @return void
*/
function testRequestHandlerPrefers(){
Configure::write('debug', 2);
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->components = array("RequestHandler");
$Controller->modelClass='ControllerPost';
$Controller->params['url'] = array('ext' => 'rss');
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$Controller->beforeFilter();
$Controller->Component->startup($Controller);
$this->assertEqual($Controller->RequestHandler->prefers(), 'rss');
unset($Controller);
}
/**
>>>>>>> 2.0-request
* testControllerHttpCodes method
*
* @access public
* @return void
*/
function testControllerHttpCodes() {
$Controller = new Controller();
$result = $Controller->httpCodes();
$this->assertEqual(count($result), 39);
$result = $Controller->httpCodes(100);
$expected = array(100 => 'Continue');
$this->assertEqual($result, $expected);
$codes = array(
1337 => 'Undefined Unicorn',
1729 => 'Hardy-Ramanujan Located'
);
$result = $Controller->httpCodes($codes);
$this->assertTrue($result);
$this->assertEqual(count($Controller->httpCodes()), 41);
$result = $Controller->httpCodes(1337);
$expected = array(1337 => 'Undefined Unicorn');
$this->assertEqual($result, $expected);
$codes = array(404 => 'Sorry Bro');
$result = $Controller->httpCodes($codes);
$this->assertTrue($result);
$this->assertEqual(count($Controller->httpCodes()), 41);
$result = $Controller->httpCodes(404);
$expected = array(404 => 'Sorry Bro');
$this->assertEqual($result, $expected);
$Controller = new Controller(null, $this->getMock('CakeResponse', array('httpCodes')));
$Controller->response->expects($this->at(0))->method('httpCodes')->with(null);
$Controller->response->expects($this->at(1))->method('httpCodes')->with(100);
$Controller->httpCodes();
$Controller->httpCodes(100);
}
/**

View file

@ -56,7 +56,7 @@ class PagesControllerTest extends CakeTestCase {
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS)
));
$Pages =& new PagesController();
$Pages = new PagesController(new CakeRequest(null, false));
$Pages->viewPath = 'posts';
$Pages->display('index');

View file

@ -92,7 +92,7 @@ class TestScaffoldMock extends Scaffold {
*
* @param unknown_type $params
*/
function __scaffold($params) {
function _scaffold($params) {
$this->_params = $params;
}
@ -280,7 +280,8 @@ class ScaffoldViewTest extends CakeTestCase {
* @return void
*/
function startTest() {
$this->Controller =& new ScaffoldMockController();
$this->request = new CakeRequest(null, false);
$this->Controller = new ScaffoldMockController($this->request);
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
@ -310,8 +311,8 @@ class ScaffoldViewTest extends CakeTestCase {
$_admin = Configure::read('Routing.prefixes');
Configure::write('Routing.prefixes', array('admin'));
$this->Controller->action = 'index';
$ScaffoldView =& new TestScaffoldView($this->Controller);
$this->Controller->request->params['action'] = 'index';
$ScaffoldView = new TestScaffoldView($this->Controller);
$result = $ScaffoldView->testGetFilename('index');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'index.ctp';
$this->assertEqual($result, $expected);
@ -348,11 +349,12 @@ class ScaffoldViewTest extends CakeTestCase {
$expected = 'cake' . DS . 'libs' . DS . 'view' . DS . 'errors' . DS . 'scaffold_error.ctp';
$this->assertEqual($result, $expected);
$Controller =& new ScaffoldMockController();
$Controller = new ScaffoldMockController($this->request);
$Controller->scaffold = 'admin';
$Controller->viewPath = 'posts';
$Controller->action = 'admin_edit';
$ScaffoldView =& new TestScaffoldView($Controller);
$Controller->request['action'] = 'admin_edit';
$ScaffoldView = new TestScaffoldView($Controller);
$result = $ScaffoldView->testGetFilename('admin_edit');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' .DS . 'views' . DS . 'posts' . DS . 'scaffold.edit.ctp';
$this->assertEqual($result, $expected);
@ -361,12 +363,17 @@ class ScaffoldViewTest extends CakeTestCase {
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' .DS . 'views' . DS . 'posts' . DS . 'scaffold.edit.ctp';
$this->assertEqual($result, $expected);
$Controller =& new ScaffoldMockController();
$Controller = new ScaffoldMockController($this->request);
$Controller->scaffold = 'admin';
$Controller->viewPath = 'tests';
$Controller->request->addParams(array(
'plugin' => 'test_plugin',
'action' => 'admin_add',
'admin' => true
));
$Controller->plugin = 'test_plugin';
$Controller->action = 'admin_add';
$ScaffoldView =& new TestScaffoldView($Controller);
$ScaffoldView = new TestScaffoldView($Controller);
$result = $ScaffoldView->testGetFilename('admin_add');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins'
. DS .'test_plugin' . DS . 'views' . DS . 'tests' . DS . 'scaffold.edit.ctp';
@ -386,10 +393,10 @@ class ScaffoldViewTest extends CakeTestCase {
* @return void
*/
function testGetViewFileNameWithTheme() {
$this->Controller->action = 'index';
$this->Controller->request['action'] = 'index';
$this->Controller->viewPath = 'posts';
$this->Controller->theme = 'test_theme';
$ScaffoldView =& new TestScaffoldView($this->Controller);
$ScaffoldView = new TestScaffoldView($this->Controller);
$result = $ScaffoldView->testGetFilename('index');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS
@ -404,9 +411,6 @@ class ScaffoldViewTest extends CakeTestCase {
* @return void
*/
function testIndexScaffold() {
$this->Controller->action = 'index';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(),
@ -416,15 +420,18 @@ class ScaffoldViewTest extends CakeTestCase {
'controller' => 'scaffold_mock',
'action' => 'index',
);
$this->Controller->request->addParams($params);
$this->Controller->request->webroot = '/';
$this->Controller->request->base = '';
$this->Controller->request->here = '/scaffold_mock/index';
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertPattern('#<h2>Scaffold Mock</h2>#', $result);
@ -443,28 +450,27 @@ class ScaffoldViewTest extends CakeTestCase {
* @return void
*/
function testViewScaffold() {
$this->Controller->action = 'view';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$this->Controller->request->base = '';
$this->Controller->request->here = '/scaffold_mock';
$this->Controller->request->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'url' => array('url' => 'scaffold_mock/view/1'),
'controller' => 'scaffold_mock',
'action' => 'view',
);
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertPattern('/<h2>View Scaffold Mock<\/h2>/', $result);
@ -486,9 +492,10 @@ class ScaffoldViewTest extends CakeTestCase {
* @return void
*/
function testEditScaffold() {
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock';
$params = array(
'plugin' => null,
'pass' => array(1),
@ -498,15 +505,14 @@ class ScaffoldViewTest extends CakeTestCase {
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertPattern('/<form id="ScaffoldMockEditForm" method="post" action="\/scaffold_mock\/edit\/1"/', $result);
@ -541,20 +547,20 @@ class ScaffoldViewTest extends CakeTestCase {
'action' => 'admin_index',
'admin' => 1,
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/admin/scaffold_mock';
$this->Controller->request->addParams($params);
//reset, and set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/admin/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->action = 'admin_index';
$this->Controller->here = '/tests/admin/scaffold_mock';
$this->Controller->webroot = '/';
Router::setRequestInfo($this->Controller->request);
$this->Controller->scaffold = 'admin';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $params);
$Scaffold = new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertPattern('/<h2>Scaffold Mock<\/h2>/', $result);
@ -586,20 +592,20 @@ class ScaffoldViewTest extends CakeTestCase {
'action' => 'admin_edit',
'admin' => 1,
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/admin/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//reset, and set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/admin/scaffold_mock/edit', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->action = 'admin_index';
$this->Controller->here = '/tests/admin/scaffold_mock';
$this->Controller->webroot = '/';
Router::setRequestInfo($this->Controller->request);
$this->Controller->scaffold = 'admin';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $params);
$Scaffold = new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertPattern('#admin/scaffold_mock/edit/1#', $result);
@ -629,20 +635,20 @@ class ScaffoldViewTest extends CakeTestCase {
'action' => 'member_index',
'member' => 1,
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/member/scaffold_mock';
$this->Controller->request->addParams($params);
//reset, and set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/member/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->action = 'member_index';
$this->Controller->here = '/tests/member/scaffold_mock';
$this->Controller->webroot = '/';
Router::setRequestInfo($this->Controller->request);
$this->Controller->scaffold = 'member';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $params);
$Scaffold = new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertPattern('/<h2>Scaffold Mock<\/h2>/', $result);
@ -685,7 +691,8 @@ class ScaffoldTest extends CakeTestCase {
* @return void
*/
function startTest() {
$this->Controller =& new ScaffoldMockController();
$request = new CakeRequest(null, false);
$this->Controller = new ScaffoldMockController($request);
}
/**
@ -706,9 +713,6 @@ class ScaffoldTest extends CakeTestCase {
* @return void
*/
function testScaffoldParams() {
$this->Controller->action = 'admin_edit';
$this->Controller->here = '/admin/scaffold_mock/edit';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(),
@ -719,14 +723,16 @@ class ScaffoldTest extends CakeTestCase {
'action' => 'admin_edit',
'admin' => true,
);
//set router.
Router::setRequestInfo(array($params, array('base' => '/', 'here' => 'admin/scaffold_mock', 'webroot' => '/')));
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/admin/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::setRequestInfo($this->Controller->request);
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
$Scaffold =& new TestScaffoldMock($this->Controller, $params);
$Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request);
$result = $Scaffold->getParams();
$this->assertEqual($result['action'], 'admin_edit');
}
@ -737,9 +743,6 @@ class ScaffoldTest extends CakeTestCase {
* @return void
*/
function testScaffoldVariableSetting() {
$this->Controller->action = 'admin_edit';
$this->Controller->here = '/admin/scaffold_mock/edit';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(),
@ -750,14 +753,16 @@ class ScaffoldTest extends CakeTestCase {
'action' => 'admin_edit',
'admin' => true,
);
//set router.
Router::setRequestInfo(array($params, array('base' => '/', 'here' => 'admin/scaffold_mock', 'webroot' => '/')));
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/admin/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::setRequestInfo($this->Controller->request);
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
$Scaffold =& new TestScaffoldMock($this->Controller, $params);
$Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request);
$result = $Scaffold->controller->viewVars;
$this->assertEqual($result['title_for_layout'], 'Scaffold :: Admin Edit :: Scaffold Mock');
@ -795,9 +800,6 @@ class ScaffoldTest extends CakeTestCase {
* @return void
*/
function testScaffoldFlashMessages() {
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
@ -807,13 +809,15 @@ class ScaffoldTest extends CakeTestCase {
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->data = array(
Router::setRequestInfo($this->Controller->request);
$this->Controller->request->data = array(
'ScaffoldMock' => array(
'id' => 1,
'title' => 'New title',
@ -824,7 +828,7 @@ class ScaffoldTest extends CakeTestCase {
unset($this->Controller->Session);
ob_start();
new Scaffold($this->Controller, $params);
new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertPattern('/Scaffold Mock has been updated/', $result);
}
@ -835,9 +839,6 @@ class ScaffoldTest extends CakeTestCase {
* @return void
*/
function testHabtmFieldAdditionWithScaffoldForm() {
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
@ -847,15 +848,18 @@ class ScaffoldTest extends CakeTestCase {
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $params);
$Scaffold = new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertPattern('/name="data\[ScaffoldTag\]\[ScaffoldTag\]"/', $result);
@ -868,28 +872,29 @@ class ScaffoldTest extends CakeTestCase {
* @return void
*/
function testEditScaffoldWithScaffoldFields() {
$this->Controller = new ScaffoldMockControllerWithFields();
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$request = new CakeRequest(null, false);
$this->Controller = new ScaffoldMockControllerWithFields($request);
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'url' => array('url' =>'scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
new Scaffold($this->Controller, $this->Controller->request);
$result = ob_get_clean();
$this->assertNoPattern('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result);

View file

@ -261,6 +261,17 @@ class ErrorHandlerTest extends CakeTestCase {
$this->skipIf(PHP_SAPI === 'cli', '%s Cannot be run from console');
}
/**
* setup create a request object to get out of router later.
*
* @return void
*/
function setUp() {
$request = new CakeRequest(null, false);
$request->base = '';
Router::setRequestInfo($request);
}
/**
* test that methods declared in an ErrorHandler subclass are not converted
* into error404 when debug == 0

View file

@ -0,0 +1,405 @@
<?php
App::import('Core', 'route/CakeRoute');
App::import('Core', 'Router');
/**
* Test case for CakeRoute
*
* @package cake.tests.cases.libs.
**/
class CakeRouteTestCase extends CakeTestCase {
/**
* startTest method
*
* @access public
* @return void
*/
function startTest() {
$this->_routing = Configure::read('Routing');
Configure::write('Routing', array('admin' => null, 'prefixes' => array()));
Router::reload();
}
/**
* end the test and reset the environment
*
* @return void
**/
function endTest() {
Configure::write('Routing', $this->_routing);
}
/**
* Test the construction of a CakeRoute
*
* @return void
**/
function testConstruction() {
$route = new CakeRoute('/:controller/:action/:id', array(), array('id' => '[0-9]+'));
$this->assertEqual($route->template, '/:controller/:action/:id');
$this->assertEqual($route->defaults, array());
$this->assertEqual($route->options, array('id' => '[0-9]+'));
$this->assertFalse($route->compiled());
}
/**
* test Route compiling.
*
* @return void
**/
function testBasicRouteCompiling() {
$route = new CakeRoute('/', array('controller' => 'pages', 'action' => 'display', 'home'));
$result = $route->compile();
$expected = '#^/*$#';
$this->assertEqual($result, $expected);
$this->assertEqual($route->keys, array());
$route = new CakeRoute('/:controller/:action', array('controller' => 'posts'));
$result = $route->compile();
$this->assertPattern($result, '/posts/edit');
$this->assertPattern($result, '/posts/super_delete');
$this->assertNoPattern($result, '/posts');
$this->assertNoPattern($result, '/posts/super_delete/1');
$route = new CakeRoute('/posts/foo:id', array('controller' => 'posts', 'action' => 'view'));
$result = $route->compile();
$this->assertPattern($result, '/posts/foo:1');
$this->assertPattern($result, '/posts/foo:param');
$this->assertNoPattern($result, '/posts');
$this->assertNoPattern($result, '/posts/');
$this->assertEqual($route->keys, array('id'));
$route = new CakeRoute('/:plugin/:controller/:action/*', array('plugin' => 'test_plugin', 'action' => 'index'));
$result = $route->compile();
$this->assertPattern($result, '/test_plugin/posts/index');
$this->assertPattern($result, '/test_plugin/posts/edit/5');
$this->assertPattern($result, '/test_plugin/posts/edit/5/name:value/nick:name');
}
/**
* test that route parameters that overlap don't cause errors.
*
* @return void
*/
function testRouteParameterOverlap() {
$route = new CakeRoute('/invoices/add/:idd/:id', array('controller' => 'invoices', 'action' => 'add'));
$result = $route->compile();
$this->assertPattern($result, '/invoices/add/1/3');
$route = new CakeRoute('/invoices/add/:id/:idd', array('controller' => 'invoices', 'action' => 'add'));
$result = $route->compile();
$this->assertPattern($result, '/invoices/add/1/3');
}
/**
* test compiling routes with keys that have patterns
*
* @return void
**/
function testRouteCompilingWithParamPatterns() {
$route = new CakeRoute(
'/:controller/:action/:id',
array(),
array('id' => Router::ID)
);
$result = $route->compile();
$this->assertPattern($result, '/posts/edit/1');
$this->assertPattern($result, '/posts/view/518098');
$this->assertNoPattern($result, '/posts/edit/name-of-post');
$this->assertNoPattern($result, '/posts/edit/4/other:param');
$this->assertEqual($route->keys, array('controller', 'action', 'id'));
$route = new CakeRoute(
'/:lang/:controller/:action/:id',
array('controller' => 'testing4'),
array('id' => Router::ID, 'lang' => '[a-z]{3}')
);
$result = $route->compile();
$this->assertPattern($result, '/eng/posts/edit/1');
$this->assertPattern($result, '/cze/articles/view/1');
$this->assertNoPattern($result, '/language/articles/view/2');
$this->assertNoPattern($result, '/eng/articles/view/name-of-article');
$this->assertEqual($route->keys, array('lang', 'controller', 'action', 'id'));
foreach (array(':', '@', ';', '$', '-') as $delim) {
$route = new CakeRoute('/posts/:id' . $delim . ':title');
$result = $route->compile();
$this->assertPattern($result, '/posts/1' . $delim . 'name-of-article');
$this->assertPattern($result, '/posts/13244' . $delim . 'name-of_Article[]');
$this->assertNoPattern($result, '/posts/11!nameofarticle');
$this->assertNoPattern($result, '/posts/11');
$this->assertEqual($route->keys, array('id', 'title'));
}
$route = new CakeRoute(
'/posts/:id::title/:year',
array('controller' => 'posts', 'action' => 'view'),
array('id' => Router::ID, 'year' => Router::YEAR, 'title' => '[a-z-_]+')
);
$result = $route->compile();
$this->assertPattern($result, '/posts/1:name-of-article/2009/');
$this->assertPattern($result, '/posts/13244:name-of-article/1999');
$this->assertNoPattern($result, '/posts/hey_now:nameofarticle');
$this->assertNoPattern($result, '/posts/:nameofarticle/2009');
$this->assertNoPattern($result, '/posts/:nameofarticle/01');
$this->assertEqual($route->keys, array('id', 'title', 'year'));
$route = new CakeRoute(
'/posts/:url_title-(uuid::id)',
array('controller' => 'posts', 'action' => 'view'),
array('pass' => array('id', 'url_title'), 'id' => Router::ID)
);
$result = $route->compile();
$this->assertPattern($result, '/posts/some_title_for_article-(uuid:12534)/');
$this->assertPattern($result, '/posts/some_title_for_article-(uuid:12534)');
$this->assertNoPattern($result, '/posts/');
$this->assertNoPattern($result, '/posts/nameofarticle');
$this->assertNoPattern($result, '/posts/nameofarticle-12347');
$this->assertEqual($route->keys, array('url_title', 'id'));
}
/**
* test more complex route compiling & parsing with mid route greedy stars
* and optional routing parameters
*
* @return void
*/
function testComplexRouteCompilingAndParsing() {
$route = new CakeRoute(
'/posts/:month/:day/:year/*',
array('controller' => 'posts', 'action' => 'view'),
array('year' => Router::YEAR, 'month' => Router::MONTH, 'day' => Router::DAY)
);
$result = $route->compile();
$this->assertPattern($result, '/posts/08/01/2007/title-of-post');
$result = $route->parse('/posts/08/01/2007/title-of-post');
$this->assertEqual(count($result), 8);
$this->assertEqual($result['controller'], 'posts');
$this->assertEqual($result['action'], 'view');
$this->assertEqual($result['year'], '2007');
$this->assertEqual($result['month'], '08');
$this->assertEqual($result['day'], '01');
$route = new CakeRoute(
"/:extra/page/:slug/*",
array('controller' => 'pages', 'action' => 'view', 'extra' => null),
array("extra" => '[a-z1-9_]*', "slug" => '[a-z1-9_]+', "action" => 'view')
);
$result = $route->compile();
$this->assertPattern($result, '/some_extra/page/this_is_the_slug');
$this->assertPattern($result, '/page/this_is_the_slug');
$this->assertEqual($route->keys, array('extra', 'slug'));
$this->assertEqual($route->options, array('extra' => '[a-z1-9_]*', 'slug' => '[a-z1-9_]+', 'action' => 'view'));
$expected = array(
'controller' => 'pages',
'action' => 'view',
'extra' => null,
);
$this->assertEqual($route->defaults, $expected);
$route = new CakeRoute(
'/:controller/:action/*',
array('project' => false),
array(
'controller' => 'source|wiki|commits|tickets|comments|view',
'action' => 'branches|history|branch|logs|view|start|add|edit|modify'
)
);
$this->assertFalse($route->parse('/chaw_test/wiki'));
$result = $route->compile();
$this->assertNoPattern($result, '/some_project/source');
$this->assertPattern($result, '/source/view');
$this->assertPattern($result, '/source/view/other/params');
$this->assertNoPattern($result, '/chaw_test/wiki');
$this->assertNoPattern($result, '/source/wierd_action');
}
/**
* test that routes match their pattern.
*
* @return void
**/
function testMatchBasic() {
$route = new CakeRoute('/:controller/:action/:id', array('plugin' => null));
$result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null));
$this->assertFalse($result);
$result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 0));
$this->assertFalse($result);
$result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'id' => 1));
$this->assertEqual($result, '/posts/view/1');
$route = new CakeRoute('/', array('controller' => 'pages', 'action' => 'display', 'home'));
$result = $route->match(array('controller' => 'pages', 'action' => 'display', 'home'));
$this->assertEqual($result, '/');
$result = $route->match(array('controller' => 'pages', 'action' => 'display', 'about'));
$this->assertFalse($result);
$route = new CakeRoute('/pages/*', array('controller' => 'pages', 'action' => 'display'));
$result = $route->match(array('controller' => 'pages', 'action' => 'display', 'home'));
$this->assertEqual($result, '/pages/home');
$result = $route->match(array('controller' => 'pages', 'action' => 'display', 'about'));
$this->assertEqual($result, '/pages/about');
$route = new CakeRoute('/blog/:action', array('controller' => 'posts'));
$result = $route->match(array('controller' => 'posts', 'action' => 'view'));
$this->assertEqual($result, '/blog/view');
$result = $route->match(array('controller' => 'nodes', 'action' => 'view'));
$this->assertFalse($result);
$result = $route->match(array('controller' => 'posts', 'action' => 'view', 1));
$this->assertFalse($result);
$result = $route->match(array('controller' => 'posts', 'action' => 'view', 'id' => 2));
$this->assertFalse($result);
$route = new CakeRoute('/foo/:controller/:action', array('action' => 'index'));
$result = $route->match(array('controller' => 'posts', 'action' => 'view'));
$this->assertEqual($result, '/foo/posts/view');
$route = new CakeRoute('/:plugin/:id/*', array('controller' => 'posts', 'action' => 'view'));
$result = $route->match(array('plugin' => 'test', 'controller' => 'posts', 'action' => 'view', 'id' => '1'));
$this->assertEqual($result, '/test/1/');
$result = $route->match(array('plugin' => 'fo', 'controller' => 'posts', 'action' => 'view', 'id' => '1', '0'));
$this->assertEqual($result, '/fo/1/0');
$result = $route->match(array('plugin' => 'fo', 'controller' => 'nodes', 'action' => 'view', 'id' => 1));
$this->assertFalse($result);
$result = $route->match(array('plugin' => 'fo', 'controller' => 'posts', 'action' => 'edit', 'id' => 1));
$this->assertFalse($result);
$route = new CakeRoute('/admin/subscriptions/:action/*', array(
'controller' => 'subscribe', 'admin' => true, 'prefix' => 'admin'
));
$url = array('controller' => 'subscribe', 'admin' => true, 'action' => 'edit', 1);
$result = $route->match($url);
$expected = '/admin/subscriptions/edit/1';
$this->assertEqual($result, $expected);
}
/**
* test match() with greedy routes, named parameters and passed args.
*
* @return void
*/
function testMatchWithNamedParametersAndPassedArgs() {
Router::connectNamed(true);
$route = new CakeRoute('/:controller/:action/*', array('plugin' => null));
$result = $route->match(array('controller' => 'posts', 'action' => 'index', 'plugin' => null, 'page' => 1));
$this->assertEqual($result, '/posts/index/page:1');
$result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null, 5));
$this->assertEqual($result, '/posts/view/5');
$result = $route->match(array('controller' => 'posts', 'action' => 'view', 'plugin' => null, 5, 'page' => 1, 'limit' => 20, 'order' => 'title'));
$this->assertEqual($result, '/posts/view/5/page:1/limit:20/order:title');
$route = new CakeRoute('/test2/*', array('controller' => 'pages', 'action' => 'display', 2));
$result = $route->match(array('controller' => 'pages', 'action' => 'display', 1));
$this->assertFalse($result);
$result = $route->match(array('controller' => 'pages', 'action' => 'display', 2, 'something'));
$this->assertEqual($result, '/test2/something');
$result = $route->match(array('controller' => 'pages', 'action' => 'display', 5, 'something'));
$this->assertFalse($result);
}
/**
* test that match with patterns works.
*
* @return void
*/
function testMatchWithPatterns() {
$route = new CakeRoute('/:controller/:action/:id', array('plugin' => null), array('id' => '[0-9]+'));
$result = $route->match(array('controller' => 'posts', 'action' => 'view', 'id' => 'foo'));
$this->assertFalse($result);
$result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'id' => '9'));
$this->assertEqual($result, '/posts/view/9');
$result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'id' => '922'));
$this->assertEqual($result, '/posts/view/922');
$result = $route->match(array('plugin' => null, 'controller' => 'posts', 'action' => 'view', 'id' => 'a99'));
$this->assertFalse($result);
}
/**
* test persistParams ability to persist parameters from $params and remove params.
*
* @return void
*/
function testPersistParams() {
$route = new CakeRoute(
'/:lang/:color/blog/:action',
array('controller' => 'posts'),
array('persist' => array('lang', 'color'))
);
$url = array('controller' => 'posts', 'action' => 'index');
$params = array('lang' => 'en', 'color' => 'blue');
$result = $route->persistParams($url, $params);
$this->assertEqual($result['lang'], 'en');
$this->assertEqual($result['color'], 'blue');
$url = array('controller' => 'posts', 'action' => 'index', 'color' => 'red');
$params = array('lang' => 'en', 'color' => 'blue');
$result = $route->persistParams($url, $params);
$this->assertEqual($result['lang'], 'en');
$this->assertEqual($result['color'], 'red');
}
/**
* test the parse method of CakeRoute.
*
* @return void
*/
function testParse() {
$route = new CakeRoute(
'/:controller/:action/:id',
array('controller' => 'testing4', 'id' => null),
array('id' => Router::ID)
);
$route->compile();
$result = $route->parse('/posts/view/1');
$this->assertEqual($result['controller'], 'posts');
$this->assertEqual($result['action'], 'view');
$this->assertEqual($result['id'], '1');
$route = new Cakeroute(
'/admin/:controller',
array('prefix' => 'admin', 'admin' => 1, 'action' => 'index')
);
$route->compile();
$result = $route->parse('/admin/');
$this->assertFalse($result);
$result = $route->parse('/admin/posts');
$this->assertEqual($result['controller'], 'posts');
$this->assertEqual($result['action'], 'index');
}
}

View file

@ -0,0 +1,61 @@
<?php
App::import('Core', 'route/PluginShortRoute');
/**
* test case for PluginShortRoute
*
* @package cake.tests.libs
*/
class PluginShortRouteTestCase extends CakeTestCase {
/**
* startTest method
*
* @access public
* @return void
*/
function startTest() {
$this->_routing = Configure::read('Routing');
Configure::write('Routing', array('admin' => null, 'prefixes' => array()));
Router::reload();
}
/**
* end the test and reset the environment
*
* @return void
**/
function endTest() {
Configure::write('Routing', $this->_routing);
}
/**
* test the parsing of routes.
*
* @return void
*/
function testParsing() {
$route = new PluginShortRoute('/:plugin', array('action' => 'index'), array('plugin' => 'foo|bar'));
$result = $route->parse('/foo');
$this->assertEqual($result['plugin'], 'foo');
$this->assertEqual($result['controller'], 'foo');
$this->assertEqual($result['action'], 'index');
$result = $route->parse('/wrong');
$this->assertFalse($result, 'Wrong plugin name matched %s');
}
/**
* test the reverse routing of the plugin shortcut urls.
*
* @return void
*/
function testMatch() {
$route = new PluginShortRoute('/:plugin', array('action' => 'index'), array('plugin' => 'foo|bar'));
$result = $route->match(array('plugin' => 'foo', 'controller' => 'posts', 'action' => 'index'));
$this->assertFalse($result, 'plugin controller mismatch was converted. %s');
$result = $route->match(array('plugin' => 'foo', 'controller' => 'foo', 'action' => 'index'));
$this->assertEqual($result, '/foo');
}
}

File diff suppressed because it is too large Load diff

View file

@ -204,6 +204,8 @@ class HelperTest extends CakeTestCase {
$null = null;
$this->View = new View($null);
$this->Helper = new Helper($this->View);
$this->Helper->request = new CakeRequest(null, false);
ClassRegistry::addObject('HelperTestPost', new HelperTestPost());
ClassRegistry::addObject('HelperTestComment', new HelperTestComment());
ClassRegistry::addObject('HelperTestTag', new HelperTestTag());
@ -363,42 +365,42 @@ class HelperTest extends CakeTestCase {
* @return void
*/
function testValue() {
$this->Helper->data = array('fullname' => 'This is me');
$this->Helper->request->data = array('fullname' => 'This is me');
$this->Helper->setEntity('fullname');
$result = $this->Helper->value('fullname');
$this->assertEqual($result, 'This is me');
$this->Helper->data = array('Post' => array('name' => 'First Post'));
$this->Helper->request->data = array('Post' => array('name' => 'First Post'));
$this->Helper->setEntity('Post.name');
$result = $this->Helper->value('Post.name');
$this->assertEqual($result, 'First Post');
$this->Helper->data = array('Post' => array(2 => array('name' => 'First Post')));
$this->Helper->request->data = array('Post' => array(2 => array('name' => 'First Post')));
$this->Helper->setEntity('Post.2.name');
$result = $this->Helper->value('Post.2.name');
$this->assertEqual($result, 'First Post');
$this->Helper->data = array('Post' => array(2 => array('created' => array('year' => '2008'))));
$this->Helper->request->data = array('Post' => array(2 => array('created' => array('year' => '2008'))));
$this->Helper->setEntity('Post.2.created');
$result = $this->Helper->value('Post.2.created');
$this->assertEqual($result, array('year' => '2008'));
$this->Helper->data = array('Post' => array(2 => array('created' => array('year' => '2008'))));
$this->Helper->request->data = array('Post' => array(2 => array('created' => array('year' => '2008'))));
$this->Helper->setEntity('Post.2.created.year');
$result = $this->Helper->value('Post.2.created.year');
$this->assertEqual($result, '2008');
$this->Helper->data = array('HelperTestTag' => array('HelperTestTag' => ''));
$this->Helper->request->data = array('HelperTestTag' => array('HelperTestTag' => ''));
$this->Helper->setEntity('HelperTestTag.HelperTestTag');
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEqual($result, '');
$this->Helper->data = array('HelperTestTag' => array('HelperTestTag' => array(2, 3, 4)));
$this->Helper->request->data = array('HelperTestTag' => array('HelperTestTag' => array(2, 3, 4)));
$this->Helper->setEntity('HelperTestTag.HelperTestTag');
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEqual($result, array(2, 3, 4));
$this->Helper->data = array(
$this->Helper->request->data = array(
'HelperTestTag' => array(
array('id' => 3),
array('id' => 5)
@ -408,12 +410,12 @@ class HelperTest extends CakeTestCase {
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEqual($result, array(3 => 3, 5 => 5));
$this->Helper->data = array('zero' => 0);
$this->Helper->request->data = array('zero' => 0);
$this->Helper->setEntity('zero');
$result = $this->Helper->value(array('default' => 'something'), 'zero');
$this->assertEqual($result, array('value' => 0));
$this->Helper->data = array('zero' => '0');
$this->Helper->request->data = array('zero' => '0');
$result = $this->Helper->value(array('default' => 'something'), 'zero');
$this->assertEqual($result, array('value' => '0'));
@ -489,7 +491,7 @@ class HelperTest extends CakeTestCase {
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css?someparam');
$this->assertEqual($result, CSS_URL . 'cake.generic.css?someparam');
$this->Helper->webroot = '/some/dir/';
$this->Helper->request->webroot = '/some/dir/';
$result = $this->Helper->assetTimestamp('/some/dir/' . CSS_URL . 'cake.generic.css');
$this->assertPattern('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result);
@ -619,27 +621,27 @@ class HelperTest extends CakeTestCase {
function testMulitDimensionValue() {
$this->Helper->data = array();
for ($i = 0; $i < 2; $i++) {
$this->Helper->data['Model'][$i] = 'what';
$this->Helper->request->data['Model'][$i] = 'what';
$result[] = $this->Helper->value("Model.{$i}");
$this->Helper->data['Model'][$i] = array();
$this->Helper->request->data['Model'][$i] = array();
for ($j = 0; $j < 2; $j++) {
$this->Helper->data['Model'][$i][$j] = 'how';
$this->Helper->request->data['Model'][$i][$j] = 'how';
$result[] = $this->Helper->value("Model.{$i}.{$j}");
}
}
$expected = array('what', 'how', 'how', 'what', 'how', 'how');
$this->assertEqual($result, $expected);
$this->Helper->data['HelperTestComment']['5']['id'] = 'ok';
$this->Helper->request->data['HelperTestComment']['5']['id'] = 'ok';
$result = $this->Helper->value('HelperTestComment.5.id');
$this->assertEqual($result, 'ok');
$this->Helper->setEntity('HelperTestPost', true);
$this->Helper->data['HelperTestPost']['5']['created']['month'] = '10';
$this->Helper->request->data['HelperTestPost']['5']['created']['month'] = '10';
$result = $this->Helper->value('5.created.month');
$this->assertEqual($result, 10);
$this->Helper->data['HelperTestPost']['0']['id'] = 100;
$this->Helper->request->data['HelperTestPost']['0']['id'] = 100;
$result = $this->Helper->value('0.id');
$this->assertEqual($result, 100);
}
@ -709,29 +711,29 @@ class HelperTest extends CakeTestCase {
$this->assertEqual($this->View->modelId,1);
$this->assertEqual($this->View->fieldSuffix,'year');
$this->Helper->data['HelperTestPost'][2]['HelperTestComment'][1]['title'] = 'My Title';
$this->Helper->request->data['HelperTestPost'][2]['HelperTestComment'][1]['title'] = 'My Title';
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.title');
$this->assertEqual($result,'My Title');
$this->Helper->data['HelperTestPost'][2]['HelperTestComment'][1]['created']['year'] = 2008;
$this->Helper->request->data['HelperTestPost'][2]['HelperTestComment'][1]['created']['year'] = 2008;
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.created.year');
$this->assertEqual($result,2008);
$this->Helper->data[2]['HelperTestComment'][1]['created']['year'] = 2008;
$this->Helper->request->data[2]['HelperTestComment'][1]['created']['year'] = 2008;
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.created.year');
$this->assertEqual($result,2008);
$this->Helper->data['HelperTestPost']['title'] = 'My Title';
$this->Helper->request->data['HelperTestPost']['title'] = 'My Title';
$result = $this->Helper->value('title');
$this->assertEqual($result,'My Title');
$this->Helper->data['My']['title'] = 'My Title';
$this->Helper->request->data['My']['title'] = 'My Title';
$result = $this->Helper->value('My.title');
$this->assertEqual($result,'My Title');
}
function testWebrootPaths() {
$this->Helper->webroot = '/';
$this->Helper->request->webroot = '/';
$result = $this->Helper->webroot('/img/cake.power.gif');
$expected = '/img/cake.power.gif';
$this->assertEqual($result, $expected);

View file

@ -75,7 +75,8 @@ class CacheHelperTest extends CakeTestCase {
* @return void
*/
function setUp() {
$this->Controller = new CacheTestController();
$request = new CakeRequest();
$this->Controller = new CacheTestController($request);
$View = new View($this->Controller);
$this->Cache = new CacheHelper($View);
$this->_cacheSettings = Configure::read('Cache');
@ -107,16 +108,16 @@ class CacheHelperTest extends CakeTestCase {
*/
function testLayoutCacheParsingNoTagsInView() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
));
$this->Controller->cacheAction = 21600;
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->request->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
@ -142,15 +143,15 @@ class CacheHelperTest extends CakeTestCase {
*/
function testCacheNonLatinCharactersInRoute() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array('風街ろまん'),
'named' => array()
);
));
$this->Controller->cacheAction = 21600;
$this->Controller->here = '/posts/view/風街ろまん';
$this->Controller->request->here = '/posts/view/風街ろまん';
$this->Controller->action = 'view';
$View = new View($this->Controller);
@ -169,15 +170,15 @@ class CacheHelperTest extends CakeTestCase {
*/
function testLayoutCacheParsingWithTagsInView() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
));
$this->Controller->cacheAction = 21600;
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
@ -204,15 +205,15 @@ class CacheHelperTest extends CakeTestCase {
*/
function testMultipleNoCacheTagsInViewfile() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
));
$this->Controller->cacheAction = 21600;
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
@ -236,15 +237,15 @@ class CacheHelperTest extends CakeTestCase {
*/
public function testComplexNoCache () {
$this->Controller->cache_parsing();
$this->Controller->params = array(
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_complex',
'url' => array(),
'pass' => array(),
'named' => array()
);
));
$this->Controller->cacheAction = array('cache_complex' => 21600);
$this->Controller->here = '/cacheTest/cache_complex';
$this->Controller->request->here = '/cacheTest/cache_complex';
$this->Controller->action = 'cache_complex';
$this->Controller->layout = 'multi_cache';
$this->Controller->viewPath = 'posts';
@ -297,17 +298,17 @@ class CacheHelperTest extends CakeTestCase {
*/
function testCacheActionArray() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
));
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->here = '/cache_test/cache_parsing';
$this->Controller->request->here = '/cache_test/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
@ -325,7 +326,7 @@ class CacheHelperTest extends CakeTestCase {
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
@ -340,17 +341,17 @@ class CacheHelperTest extends CakeTestCase {
$this->Controller->cache_parsing();
$this->Controller->params = array(
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
));
$this->Controller->cacheAction = array(
'some_other_action' => 21600
);
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
@ -409,18 +410,18 @@ class CacheHelperTest extends CakeTestCase {
Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}'));
$this->Controller->cache_parsing();
$this->Controller->params = array(
$this->Controller->request->addParams(array(
'lang' => 'en',
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
));
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->here = '/en/cache_test/cache_parsing';
$this->Controller->request->here = '/en/cache_test/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);

View file

@ -17,7 +17,7 @@
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', array('ClassRegistry', 'Controller', 'View', 'Model', 'Security'));
App::import('Core', array('ClassRegistry', 'Controller', 'View', 'Model', 'Security', 'CakeRequest'));
App::import('Helper', 'Html');
App::import('Helper', 'Form');
@ -672,11 +672,16 @@ class FormHelperTest extends CakeTestCase {
parent::setUp();
Router::reload();
$this->Controller = new ContactTestController();
$this->View = new View($this->Controller);
$this->Form = new FormHelper($this->View);
$this->Form->params['action'] = 'add';
$this->Form->Html = new HtmlHelper($this->View);
$this->Form->request = new CakeRequest(null, false);
$this->Form->request['action'] = 'add';
$this->Form->request->webroot = '';
$this->Form->request->base = '';
ClassRegistry::addObject('Contact', new Contact());
ClassRegistry::addObject('ContactNonStandardPk', new ContactNonStandardPk());
@ -723,7 +728,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testCreateWithSecurity() {
$this->Form->params['_Token'] = array('key' => 'testKey');
$this->Form->request['_Token'] = array('key' => 'testKey');
$encoding = strtolower(Configure::read('App.encoding'));
$result = $this->Form->create('Contact', array('url' => '/contacts/add'));
$expected = array(
@ -760,7 +765,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testValidateHashNoModel() {
$this->Form->params['_Token'] = array('key' => 'foo');
$this->Form->request['_Token'] = array('key' => 'foo');
$result = $this->Form->secure(array('anything'));
$this->assertPattern('/540ac9c60d323c22bafe997b72c0790f39a8bdef/', $result);
}
@ -801,7 +806,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testNoCheckboxLocking() {
$this->Form->params['_Token'] = array('key' => 'foo');
$this->Form->request['_Token'] = array('key' => 'foo');
$this->assertIdentical($this->Form->fields, array());
$this->Form->checkbox('check', array('value' => '1'));
@ -819,7 +824,8 @@ class FormHelperTest extends CakeTestCase {
function testFormSecurityFields() {
$key = 'testKey';
$fields = array('Model.password', 'Model.username', 'Model.valid' => '0');
$this->Form->params['_Token']['key'] = $key;
$this->Form->request['_Token'] = array('key' => $key);
$result = $this->Form->secure($fields);
$expected = Security::hash(serialize($fields) . Configure::read('Security.salt'));
@ -882,7 +888,7 @@ class FormHelperTest extends CakeTestCase {
'Model.0.valid' => '0', 'Model.1.password', 'Model.1.username',
'Model.1.hidden' => 'value', 'Model.1.valid' => '0'
);
$this->Form->params['_Token']['key'] = $key;
$this->Form->request['_Token'] = array('key' => $key);
$result = $this->Form->secure($fields);
$hash = '51e3b55a6edd82020b3f29c9ae200e14bbeb7ee5%3An%3A4%3A%7Bv%3A0%3Bf%3A14%3A%22Zbqry.';
@ -909,7 +915,7 @@ class FormHelperTest extends CakeTestCase {
*/
function testFormSecurityMultipleSubmitButtons() {
$key = 'testKey';
$this->Form->params['_Token']['key'] = $key;
$this->Form->request['_Token'] = array('key' => $key);
$this->Form->create('Addresses');
$this->Form->input('Address.title');
@ -953,7 +959,7 @@ class FormHelperTest extends CakeTestCase {
function testFormSecurityMultipleInputFields() {
$key = 'testKey';
$this->Form->params['_Token']['key'] = $key;
$this->Form->request['_Token'] = array('key' => $key);
$this->Form->create('Addresses');
$this->Form->hidden('Addresses.0.id', array('value' => '123456'));
@ -1000,8 +1006,10 @@ class FormHelperTest extends CakeTestCase {
*/
function testFormSecurityMultipleInputDisabledFields() {
$key = 'testKey';
$this->Form->params['_Token']['key'] = $key;
$this->Form->params['_Token']['disabledFields'] = array('first_name', 'address');
$this->Form->request['_Token'] = array(
'key' => $key,
'disabledFields' => array('first_name', 'address')
);
$this->Form->create();
$this->Form->hidden('Addresses.0.id', array('value' => '123456'));
@ -1044,8 +1052,10 @@ class FormHelperTest extends CakeTestCase {
*/
function testFormSecurityInputDisabledFields() {
$key = 'testKey';
$this->Form->params['_Token']['key'] = $key;
$this->Form->params['_Token']['disabledFields'] = array('first_name', 'address');
$this->Form->request['_Token'] = array(
'key' => $key,
'disabledFields' => array('first_name', 'address')
);
$this->Form->create();
$this->Form->hidden('Addresses.id', array('value' => '123456'));
@ -1087,7 +1097,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testFormSecuredInput() {
$this->Form->params['_Token']['key'] = 'testKey';
$this->Form->request['_Token'] = array('key' => 'testKey');
$result = $this->Form->create('Contact', array('url' => '/contacts/add'));
$encoding = strtolower(Configure::read('App.encoding'));
@ -1192,7 +1202,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testFormSecuredFileInput() {
$this->Form->params['_Token']['key'] = 'testKey';
$this->Form->request['_Token'] = array('key' => 'testKey');
$this->assertEqual($this->Form->fields, array());
$result = $this->Form->file('Attachment.file');
@ -1210,7 +1220,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testFormSecuredMultipleSelect() {
$this->Form->params['_Token']['key'] = 'testKey';
$this->Form->request['_Token'] = array('key' => 'testKey');
$this->assertEqual($this->Form->fields, array());
$options = array('1' => 'one', '2' => 'two');
@ -1230,7 +1240,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testFormSecuredRadio() {
$this->Form->params['_Token']['key'] = 'testKey';
$this->Form->request['_Token'] = array('key' => 'testKey');
$this->assertEqual($this->Form->fields, array());
$options = array('1' => 'option1', '2' => 'option2');
@ -1246,8 +1256,10 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testDisableSecurityUsingForm() {
$this->Form->params['_Token']['key'] = 'testKey';
$this->Form->params['_Token']['disabledFields'] = array();
$this->Form->request['_Token'] = array(
'key' => 'testKey',
'disabledFields' => array()
);
$this->Form->create();
$this->Form->hidden('Addresses.id', array('value' => '123456'));
@ -1661,7 +1673,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Contact' => array('phone' => 'Hello & World > weird chars'));
$this->Form->request->data = array('Contact' => array('phone' => 'Hello & World > weird chars'));
$result = $this->Form->input('Contact.phone');
$expected = array(
'div' => array('class' => 'input text'),
@ -1677,7 +1689,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['0']['OtherModel']['field'] = 'My value';
$this->Form->request->data['Model']['0']['OtherModel']['field'] = 'My value';
$result = $this->Form->input('Model.0.OtherModel.field', array('id' => 'myId'));
$expected = array(
'div' => array('class' => 'input text'),
@ -1692,7 +1704,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
unset($this->Form->data);
unset($this->Form->request->data);
$this->Form->validationErrors['Model']['field'] = 'Badness!';
$result = $this->Form->input('Model.field');
@ -1955,7 +1967,7 @@ class FormHelperTest extends CakeTestCase {
$this->assertPattern('/option value="12"/', $result[0]);
$this->assertNoPattern('/option value="13"/', $result[0]);
$this->Form->data = array('Contact' => array('created' => null));
$this->Form->request->data = array('Contact' => array('created' => null));
$result = $this->Form->input('Contact.created', array('empty' => 'Date Unknown'));
$expected = array(
'div' => array('class' => 'input date'),
@ -1978,11 +1990,11 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Contact' => array('created' => null));
$this->Form->request->data = array('Contact' => array('created' => null));
$result = $this->Form->input('Contact.created', array('type' => 'datetime', 'dateFormat' => 'NONE'));
$this->assertPattern('/for\="ContactCreatedHour"/', $result);
$this->Form->data = array('Contact' => array('created' => null));
$this->Form->request->data = array('Contact' => array('created' => null));
$result = $this->Form->input('Contact.created', array('type' => 'datetime', 'timeFormat' => 'NONE'));
$this->assertPattern('/for\="ContactCreatedMonth"/', $result);
@ -2078,9 +2090,10 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Model' => array('user_id' => 'value'));
$this->View->viewVars['users'] = array('value' => 'good', 'other' => 'bad');
$this->Form->request->data = array('Model' => array('user_id' => 'value'));
$result = $this->Form->input('Model.user_id', array('empty' => true));
$expected = array(
'div' => array('class' => 'input select'),
@ -2101,9 +2114,8 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Model' => array('user_id' => null));
$this->View->viewVars['users'] = array('value' => 'good', 'other' => 'bad');
$this->Form->request->data = array('Model' => array('user_id' => null));
$result = $this->Form->input('Model.user_id', array('empty' => 'Some Empty'));
$expected = array(
'div' => array('class' => 'input select'),
@ -2125,9 +2137,8 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Model' => array('user_id' => 'value'));
$this->View->viewVars['users'] = array('value' => 'good', 'other' => 'bad');
$this->Form->request->data = array('Model' => array('user_id' => 'value'));
$result = $this->Form->input('Model.user_id', array('empty' => 'Some Empty'));
$expected = array(
'div' => array('class' => 'input select'),
@ -2149,9 +2160,8 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('User' => array('User' => array('value')));
$this->View->viewVars['users'] = array('value' => 'good', 'other' => 'bad');
$this->Form->request->data = array('User' => array('User' => array('value')));
$result = $this->Form->input('User.User', array('empty' => true));
$expected = array(
'div' => array('class' => 'input select'),
@ -2270,8 +2280,8 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->Form->create('Contact');
$this->Form->params['prefix'] = 'admin';
$this->Form->action = 'admin_edit';
$this->Form->request['prefix'] = 'admin';
$this->Form->request['action'] = 'admin_edit';
$result = $this->Form->inputs();
$expected = array(
'<fieldset',
@ -2521,16 +2531,16 @@ class FormHelperTest extends CakeTestCase {
$result = $this->Form->text('Model.field', array('id' => 'theID'));
$this->assertTags($result, array('input' => array('type' => 'text', 'name' => 'data[Model][field]', 'id' => 'theID')));
$this->Form->data['Model']['text'] = 'test <strong>HTML</strong> values';
$this->Form->request->data['Model']['text'] = 'test <strong>HTML</strong> values';
$result = $this->Form->text('Model.text');
$this->assertTags($result, array('input' => array('type' => 'text', 'name' => 'data[Model][text]', 'value' => 'test &lt;strong&gt;HTML&lt;/strong&gt; values', 'id' => 'ModelText')));
$this->Form->validationErrors['Model']['text'] = 1;
$this->Form->data['Model']['text'] = 'test';
$this->Form->request->data['Model']['text'] = 'test';
$result = $this->Form->text('Model.text', array('id' => 'theID'));
$this->assertTags($result, array('input' => array('type' => 'text', 'name' => 'data[Model][text]', 'value' => 'test', 'id' => 'theID', 'class' => 'form-error')));
$this->Form->data['Model']['0']['OtherModel']['field'] = 'My value';
$this->Form->request->data['Model']['0']['OtherModel']['field'] = 'My value';
$result = $this->Form->text('Model.0.OtherModel.field', array('id' => 'myId'));
$expected = array(
'input' => array('type' => 'text', 'name' => 'data[Model][0][OtherModel][field]', 'value' => 'My value', 'id' => 'myId')
@ -2547,11 +2557,11 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testDefaultValue() {
$this->Form->data['Model']['field'] = 'test';
$this->Form->request->data['Model']['field'] = 'test';
$result = $this->Form->text('Model.field', array('default' => 'default value'));
$this->assertTags($result, array('input' => array('type' => 'text', 'name' => 'data[Model][field]', 'value' => 'test', 'id' => 'ModelField')));
unset($this->Form->data['Model']['field']);
unset($this->Form->request->data['Model']['field']);
$result = $this->Form->text('Model.field', array('default' => 'default value'));
$this->assertTags($result, array('input' => array('type' => 'text', 'name' => 'data[Model][field]', 'value' => 'default value', 'id' => 'ModelField')));
}
@ -2630,7 +2640,7 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, array('input' => array('type' => 'password', 'name' => 'data[Model][field]', 'id' => 'ModelField')));
$this->Form->validationErrors['Model']['passwd'] = 1;
$this->Form->data['Model']['passwd'] = 'test';
$this->Form->request->data['Model']['passwd'] = 'test';
$result = $this->Form->password('Model.passwd', array('id' => 'theID'));
$this->assertTags($result, array('input' => array('type' => 'password', 'name' => 'data[Model][passwd]', 'value' => 'test', 'id' => 'theID', 'class' => 'form-error')));
}
@ -2973,7 +2983,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Model' => array('field' => 'value'));
$this->Form->request->data = array('Model' => array('field' => 'value'));
$result = $this->Form->select('Model.field', array('value' => 'good', 'other' => 'bad'));
$expected = array(
'select' => array('name' => 'data[Model][field]', 'id' => 'ModelField'),
@ -2989,7 +2999,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array();
$this->Form->request->data = array();
$result = $this->Form->select('Model.field', array('value' => 'good', 'other' => 'bad'));
$expected = array(
'select' => array('name' => 'data[Model][field]', 'id' => 'ModelField'),
@ -3038,7 +3048,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Model' => array('contact_id' => 228));
$this->Form->request->data = array('Model' => array('contact_id' => 228));
$result = $this->Form->select(
'Model.contact_id',
array('228' => '228 value', '228-1' => '228-1 value', '228-2' => '228-2 value'),
@ -3234,7 +3244,7 @@ class FormHelperTest extends CakeTestCase {
2 => 'red',
3 => 'green'
);
$this->Form->data = array(
$this->Form->request->data = array(
'Contact' => array(),
'ContactTag' => array(
array(
@ -3376,7 +3386,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Model' => array('tags' => array(1)));
$this->Form->request->data = array('Model' => array('tags' => array(1)));
$result = $this->Form->select(
'Model.tags', array('1' => 'first', 'Array' => 'Array'), null, array('multiple' => 'checkbox')
);
@ -3414,7 +3424,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testSelectMultipleCheckboxSecurity() {
$this->Form->params['_Token']['key'] = 'testKey';
$this->Form->request['_Token'] = array('key' => 'testKey');
$this->assertEqual($this->Form->fields, array());
$result = $this->Form->select(
@ -3537,7 +3547,7 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->Form->validationErrors['Model']['field'] = 1;
$this->Form->data['Model']['field'] = 'myvalue';
$this->Form->request->data['Model']['field'] = 'myvalue';
$result = $this->Form->checkbox('Model.field', array('id' => 'theID', 'value' => 'myvalue'));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'theID_'),
@ -3552,7 +3562,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '';
$this->Form->request->data['Model']['field'] = '';
$result = $this->Form->checkbox('Model.field', array('id' => 'theID'));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'value' => '0', 'id' => 'theID_'),
@ -3611,7 +3621,7 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->Form->validationErrors['Model']['field'] = 1;
$this->Form->data['Contact']['published'] = 1;
$this->Form->request->data['Contact']['published'] = 1;
$result = $this->Form->checkbox('Contact.published', array('id' => 'theID'));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Contact][published]', 'value' => '0', 'id' => 'theID_'),
@ -3620,7 +3630,7 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->Form->validationErrors['Model']['field'] = 1;
$this->Form->data['Contact']['published'] = 0;
$this->Form->request->data['Contact']['published'] = 0;
$result = $this->Form->checkbox('Contact.published', array('id'=>'theID'));
$expected = array(
'input' => array('type' => 'hidden', 'name' => 'data[Contact][published]', 'value' => '0', 'id' => 'theID_'),
@ -3978,7 +3988,7 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->assertNoPattern('/<option[^<>]+value=""[^<>]+selected="selected"[^>]*>/', $result);
$this->Form->data['Contact']['data'] = null;
$this->Form->request->data['Contact']['data'] = null;
$result = $this->Form->dateTime('Contact.date', 'DMY', '12');
$expected = array(
array('select' => array('name' => 'data[Contact][date][day]', 'id' => 'ContactDateDay')),
@ -4019,8 +4029,8 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->assertNoPattern('/<option[^<>]+value=""[^<>]+selected="selected"[^>]*>/', $result);
$this->Form->data['Model']['field'] = date('Y') . '-01-01 00:00:00';
$now = strtotime($this->Form->data['Model']['field']);
$this->Form->request->data['Model']['field'] = date('Y') . '-01-01 00:00:00';
$now = strtotime($this->Form->request->data['Model']['field']);
$result = $this->Form->dateTime('Model.field', 'DMY', '12', null, array('empty' => false));
$expected = array(
array('select' => array('name' => 'data[Model][field][day]', 'id' => 'ModelFieldDay')),
@ -4212,7 +4222,7 @@ class FormHelperTest extends CakeTestCase {
$this->assertPattern('/<option[^<>]+value="35"[^<>]+selected="selected"[^>]*>35<\/option>/', $result);
$this->assertNoErrors();
$this->Form->data['Contact'] = array(
$this->Form->request->data['Contact'] = array(
'date' => array(
'day' => '',
'month' => '',
@ -4430,7 +4440,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '2006-10-10 23:12:32';
$this->Form->request->data['Model']['field'] = '2006-10-10 23:12:32';
$result = $this->Form->day('Model.field');
$expected = array(
array('select' => array('name' => 'data[Model][field][day]', 'id' => 'ModelFieldDay')),
@ -4451,7 +4461,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '';
$this->Form->request->data['Model']['field'] = '';
$result = $this->Form->day('Model.field', '10');
$expected = array(
array('select' => array('name' => 'data[Model][field][day]', 'id' => 'ModelFieldDay')),
@ -4472,7 +4482,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '2006-10-10 23:12:32';
$this->Form->request->data['Model']['field'] = '2006-10-10 23:12:32';
$result = $this->Form->day('Model.field', true);
$expected = array(
array('select' => array('name' => 'data[Model][field][day]', 'id' => 'ModelFieldDay')),
@ -4522,7 +4532,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '2006-10-10 00:12:32';
$this->Form->request->data['Model']['field'] = '2006-10-10 00:12:32';
$result = $this->Form->minute('Model.field');
$expected = array(
array('select' => array('name' => 'data[Model][field][min]', 'id' => 'ModelFieldMin')),
@ -4546,7 +4556,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '';
$this->Form->request->data['Model']['field'] = '';
$result = $this->Form->minute('Model.field', null, array('interval' => 5));
$expected = array(
array('select' => array('name' => 'data[Model][field][min]', 'id' => 'ModelFieldMin')),
@ -4566,7 +4576,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '2006-10-10 00:10:32';
$this->Form->request->data['Model']['field'] = '2006-10-10 00:10:32';
$result = $this->Form->minute('Model.field', null, array('interval' => 5));
$expected = array(
array('select' => array('name' => 'data[Model][field][min]', 'id' => 'ModelFieldMin')),
@ -4612,7 +4622,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '2006-10-10 00:12:32';
$this->Form->request->data['Model']['field'] = '2006-10-10 00:12:32';
$result = $this->Form->hour('Model.field', false);
$expected = array(
array('select' => array('name' => 'data[Model][field][hour]', 'id' => 'ModelFieldHour')),
@ -4632,7 +4642,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '';
$this->Form->request->data['Model']['field'] = '';
$result = $this->Form->hour('Model.field', true, '23');
$expected = array(
array('select' => array('name' => 'data[Model][field][hour]', 'id' => 'ModelFieldHour')),
@ -4655,7 +4665,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['field'] = '2006-10-10 00:12:32';
$this->Form->request->data['Model']['field'] = '2006-10-10 00:12:32';
$result = $this->Form->hour('Model.field', true);
$expected = array(
array('select' => array('name' => 'data[Model][field][hour]', 'id' => 'ModelFieldHour')),
@ -4675,7 +4685,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
unset($this->Form->data['Model']['field']);
unset($this->Form->request->data['Model']['field']);
$result = $this->Form->hour('Model.field', true, 'now');
$thisHour = date('H');
$optValue = date('G');
@ -4719,7 +4729,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->data['Contact']['published'] = '';
$this->request->data['Contact']['published'] = '';
$result = $this->Form->year('Contact.published', 2006, 2007, null, array('class' => 'year'));
$expected = array(
array('select' => array('name' => 'data[Contact][published][year]', 'id' => 'ContactPublishedYear', 'class' => 'year')),
@ -4735,7 +4745,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['published'] = '2006-10-10';
$this->Form->request->data['Contact']['published'] = '2006-10-10';
$result = $this->Form->year('Contact.published', 2006, 2007, null, array('empty' => false));
$expected = array(
array('select' => array('name' => 'data[Contact][published][year]', 'id' => 'ContactPublishedYear')),
@ -4749,7 +4759,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['published'] = '';
$this->Form->request->data['Contact']['published'] = '';
$result = $this->Form->year('Contact.published', 2006, 2007, false);
$expected = array(
array('select' => array('name' => 'data[Contact][published][year]', 'id' => 'ContactPublishedYear')),
@ -4765,7 +4775,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['published'] = '2006-10-10';
$this->Form->request->data['Contact']['published'] = '2006-10-10';
$result = $this->Form->year('Contact.published', 2006, 2007, false, array('empty' => false));
$expected = array(
array('select' => array('name' => 'data[Contact][published][year]', 'id' => 'ContactPublishedYear')),
@ -4779,7 +4789,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['published'] = '';
$this->Form->request->data['Contact']['published'] = '';
$result = $this->Form->year('Contact.published', 2006, 2007, 2007);
$expected = array(
array('select' => array('name' => 'data[Contact][published][year]', 'id' => 'ContactPublishedYear')),
@ -4795,7 +4805,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['published'] = '2006-10-10';
$this->Form->request->data['Contact']['published'] = '2006-10-10';
$result = $this->Form->year('Contact.published', 2006, 2007, 2007, array('empty' => false));
$expected = array(
array('select' => array('name' => 'data[Contact][published][year]', 'id' => 'ContactPublishedYear')),
@ -4809,7 +4819,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['published'] = '';
$this->Form->request->data['Contact']['published'] = '';
$result = $this->Form->year('Contact.published', 2006, 2008, 2007, array('empty' => false));
$expected = array(
array('select' => array('name' => 'data[Contact][published][year]', 'id' => 'ContactPublishedYear')),
@ -4826,7 +4836,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['published'] = '2006-10-10';
$this->Form->request->data['Contact']['published'] = '2006-10-10';
$result = $this->Form->year('Contact.published', 2006, 2008, null, array('empty' => false));
$expected = array(
array('select' => array('name' => 'data[Contact][published][year]', 'id' => 'ContactPublishedYear')),
@ -4843,7 +4853,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array();
$this->Form->request->data = array();
$this->Form->create('Contact');
$result = $this->Form->year('published', 2006, 2008, null, array('empty' => false));
$expected = array(
@ -4869,7 +4879,7 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testTextArea() {
$this->Form->data = array('Model' => array('field' => 'some test data'));
$this->Form->request->data = array('Model' => array('field' => 'some test data'));
$result = $this->Form->textarea('Model.field');
$expected = array(
'textarea' => array('name' => 'data[Model][field]', 'id' => 'ModelField'),
@ -4885,7 +4895,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Model' => array('field' => 'some <strong>test</strong> data with <a href="#">HTML</a> chars'));
$this->Form->request->data = array('Model' => array('field' => 'some <strong>test</strong> data with <a href="#">HTML</a> chars'));
$result = $this->Form->textarea('Model.field');
$expected = array(
'textarea' => array('name' => 'data[Model][field]', 'id' => 'ModelField'),
@ -4894,7 +4904,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array('Model' => array('field' => 'some <strong>test</strong> data with <a href="#">HTML</a> chars'));
$this->Form->request->data = array('Model' => array('field' => 'some <strong>test</strong> data with <a href="#">HTML</a> chars'));
$result = $this->Form->textarea('Model.field', array('escape' => false));
$expected = array(
'textarea' => array('name' => 'data[Model][field]', 'id' => 'ModelField'),
@ -4903,7 +4913,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Model']['0']['OtherModel']['field'] = null;
$this->Form->request->data['Model']['0']['OtherModel']['field'] = null;
$result = $this->Form->textarea('Model.0.OtherModel.field');
$expected = array(
'textarea' => array('name' => 'data[Model][0][OtherModel][field]', 'id' => 'Model0OtherModelField'),
@ -4945,7 +4955,7 @@ class FormHelperTest extends CakeTestCase {
*/
function testHiddenField() {
$this->Form->validationErrors['Model']['field'] = 1;
$this->Form->data['Model']['field'] = 'test';
$this->Form->request->data['Model']['field'] = 'test';
$result = $this->Form->hidden('Model.field', array('id' => 'theID'));
$this->assertTags($result, array('input' => array('type' => 'hidden', 'name' => 'data[Model][field]', 'id' => 'theID', 'value' => 'test')));
}
@ -4960,7 +4970,7 @@ class FormHelperTest extends CakeTestCase {
$result = $this->Form->file('Model.upload');
$this->assertTags($result, array('input' => array('type' => 'file', 'name' => 'data[Model][upload]', 'id' => 'ModelUpload')));
$this->Form->data['Model.upload'] = array("name" => "", "type" => "", "tmp_name" => "", "error" => 4, "size" => 0);
$this->Form->request->data['Model.upload'] = array("name" => "", "type" => "", "tmp_name" => "", "error" => 4, "size" => 0);
$result = $this->Form->input('Model.upload', array('type' => 'file'));
$expected = array(
'div' => array('class' => 'input file'),
@ -5237,8 +5247,8 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['id'] = 1;
$this->Form->params['action'] = 'edit';
$this->Form->request->data['Contact']['id'] = 1;
$this->Form->request['action'] = 'edit';
$result = $this->Form->create('Contact');
$expected = array(
'form' => array(
@ -5251,8 +5261,8 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['Contact']['id'] = 1;
$this->Form->params['action'] = 'edit';
$this->Form->request->data['Contact']['id'] = 1;
$this->Form->request['action'] = 'edit';
$result = $this->Form->create('Contact', array('type' => 'file'));
$expected = array(
'form' => array(
@ -5265,7 +5275,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data['ContactNonStandardPk']['pk'] = 1;
$this->Form->request->data['ContactNonStandardPk']['pk'] = 1;
$result = $this->Form->create('ContactNonStandardPk');
$expected = array(
'form' => array(
@ -5290,7 +5300,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->params['action'] = 'add';
$this->Form->request['action'] = 'add';
$result = $this->Form->create('User', array('url' => array('action' => 'login')));
$expected = array(
'form' => array(
@ -5324,8 +5334,8 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->params['controller'] = 'pages';
$this->Form->params['models'] = array('User', 'Post');
$this->Form->request['controller'] = 'pages';
$this->Form->request['models'] = array('User', 'Post');
$result = $this->Form->create('User', array('action' => 'signup'));
$expected = array(
'form' => array(
@ -5338,9 +5348,9 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array();
$this->Form->params['controller'] = 'contacts';
$this->Form->params['models'] = array('Contact');
$this->Form->request->data = array();
$this->Form->request['controller'] = 'contacts';
$this->Form->request['models'] = array('Contact');
$result = $this->Form->create(array('url' => array('action' => 'index', 'param')));
$expected = array(
'form' => array(
@ -5405,7 +5415,7 @@ class FormHelperTest extends CakeTestCase {
* Test base form url when url param is passed with multiple parameters (&)
*
*/
function testCreateQuerystringParams() {
function testCreateQuerystringrequest() {
$encoding = strtolower(Configure::read('App.encoding'));
$result = $this->Form->create('Contact', array(
'type' => 'post',
@ -5487,13 +5497,17 @@ class FormHelperTest extends CakeTestCase {
* @return void
*/
function testEditFormWithData() {
$this->Form->data = array('Person' => array(
$this->Form->request->data = array('Person' => array(
'id' => 1,
'first_name' => 'Nate',
'last_name' => 'Abele',
'email' => 'nate@example.com'
));
$this->Form->params = array('models' => array('Person'), 'controller' => 'people', 'action' => 'add');
$this->Form->request->addParams(array(
'models' => array('Person'),
'controller' => 'people',
'action' => 'add'
));
$options = array(1 => 'Nate', 2 => 'Garrett', 3 => 'Larry');
$this->Form->create();
@ -5841,7 +5855,7 @@ class FormHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Form->data = array(
$this->Form->request->data = array(
'Contact' => array('non_existing_nor_validated' => 'CakePHP magic'
));
$result = $this->Form->input('Contact.non_existing_nor_validated', array('div' => false));
@ -6208,7 +6222,7 @@ class FormHelperTest extends CakeTestCase {
*/
function testMultiRecordForm() {
$this->Form->create('ValidateProfile');
$this->Form->data['ValidateProfile'][1]['ValidateItem'][2]['name'] = 'Value';
$this->Form->request->data['ValidateProfile'][1]['ValidateItem'][2]['name'] = 'Value';
$result = $this->Form->input('ValidateProfile.1.ValidateItem.2.name');
$expected = array(
'div' => array('class' => 'input textarea'),
@ -6262,7 +6276,7 @@ class FormHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->Form->validationErrors['ValidateProfile'][1]['ValidateItem'][2]['profile_id'] = 'Error';
$this->Form->data['ValidateProfile'][1]['ValidateItem'][2]['profile_id'] = '1';
$this->Form->request->data['ValidateProfile'][1]['ValidateItem'][2]['profile_id'] = '1';
$result = $this->Form->input('ValidateProfile.1.ValidateItem.2.profile_id');
$expected = array(
'div' => array('class' => 'input select error'),

View file

@ -17,7 +17,7 @@
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', array('Helper', 'AppHelper', 'ClassRegistry', 'Controller', 'Model'));
App::import('Core', array('Helper', 'AppHelper', 'ClassRegistry', 'Controller'));
App::import('Helper', array('Html', 'Form'));
if (!defined('FULL_BASE_URL')) {
@ -110,7 +110,8 @@ class HtmlHelperTest extends CakeTestCase {
function startTest() {
$this->View = $this->getMock('View', array('addScript'), array(new TheHtmlTestController()));
$this->Html = new HtmlHelper($this->View);
$this->Html->request = new CakeRequest(null, false);
$this->Html->request->webroot = '';
$this->_appEncoding = Configure::read('App.encoding');
$this->_asset = Configure::read('Asset');
$this->_debug = Configure::read('debug');
@ -155,6 +156,8 @@ class HtmlHelperTest extends CakeTestCase {
* @return void
*/
function testLink() {
$this->Html->request->webroot = '';
$result = $this->Html->link('/home');
$expected = array('a' => array('href' => '/home'), 'preg:/\/home/', '/a');
$this->assertTags($result, $expected);
@ -287,6 +290,7 @@ class HtmlHelperTest extends CakeTestCase {
* @return void
*/
function testImageTag() {
$this->Html->request->webroot = '';
Configure::write('Asset.timestamp', false);
$result = $this->Html->image('test.gif');
@ -310,7 +314,7 @@ class HtmlHelperTest extends CakeTestCase {
function testImageWithTimestampping() {
Configure::write('Asset.timestamp', 'force');
$this->Html->webroot = '/';
$this->Html->request->webroot = '/';
$result = $this->Html->image('cake.icon.png');
$this->assertTags($result, array('img' => array('src' => 'preg:/\/img\/cake\.icon\.png\?\d+/', 'alt' => '')));
@ -320,14 +324,12 @@ class HtmlHelperTest extends CakeTestCase {
$result = $this->Html->image('cake.icon.png');
$this->assertTags($result, array('img' => array('src' => 'preg:/\/img\/cake\.icon\.png\?\d+/', 'alt' => '')));
$webroot = $this->Html->webroot;
$this->Html->webroot = '/testing/longer/';
$this->Html->request->webroot = '/testing/longer/';
$result = $this->Html->image('cake.icon.png');
$expected = array(
'img' => array('src' => 'preg:/\/testing\/longer\/img\/cake\.icon\.png\?[0-9]+/', 'alt' => '')
);
$this->assertTags($result, $expected);
$this->Html->webroot = $webroot;
}
/**
@ -344,7 +346,7 @@ class HtmlHelperTest extends CakeTestCase {
App::import('Core', 'File');
$testfile = WWW_ROOT . 'theme' . DS . 'test_theme' . DS . 'img' . DS . '__cake_test_image.gif';
$file =& new File($testfile, true);
$file = new File($testfile, true);
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
@ -352,7 +354,7 @@ class HtmlHelperTest extends CakeTestCase {
Configure::write('Asset.timestamp', true);
Configure::write('debug', 1);
$this->Html->webroot = '/';
$this->Html->request->webroot = '/';
$this->Html->theme = 'test_theme';
$result = $this->Html->image('__cake_test_image.gif');
$this->assertTags($result, array(
@ -361,8 +363,7 @@ class HtmlHelperTest extends CakeTestCase {
'alt' => ''
)));
$webroot = $this->Html->webroot;
$this->Html->webroot = '/testing/';
$this->Html->request->webroot = '/testing/';
$result = $this->Html->image('__cake_test_image.gif');
$this->assertTags($result, array(
@ -370,9 +371,8 @@ class HtmlHelperTest extends CakeTestCase {
'src' => 'preg:/\/testing\/theme\/test_theme\/img\/__cake_test_image\.gif\?\d+/',
'alt' => ''
)));
$this->Html->webroot = $webroot;
$dir =& new Folder(WWW_ROOT . 'theme' . DS . 'test_theme');
$dir = new Folder(WWW_ROOT . 'theme' . DS . 'test_theme');
$dir->delete();
}
@ -390,7 +390,6 @@ class HtmlHelperTest extends CakeTestCase {
$webRoot = Configure::read('App.www_root');
Configure::write('App.www_root', TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'webroot' . DS);
$webroot = $this->Html->webroot;
$this->Html->theme = 'test_theme';
$result = $this->Html->css('webroot_test');
$expected = array(
@ -398,7 +397,6 @@ class HtmlHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$webroot = $this->Html->webroot;
$this->Html->theme = 'test_theme';
$result = $this->Html->css('theme_webroot');
$expected = array(
@ -514,19 +512,15 @@ class HtmlHelperTest extends CakeTestCase {
$expected['link']['href'] = 'preg:/.*css\/cake\.generic\.css\?[0-9]+/';
$this->assertTags($result, $expected);
$webroot = $this->Html->webroot;
$this->Html->webroot = '/testing/';
$this->Html->request->webroot = '/testing/';
$result = $this->Html->css('cake.generic');
$expected['link']['href'] = 'preg:/\/testing\/css\/cake\.generic\.css\?[0-9]+/';
$this->assertTags($result, $expected);
$this->Html->webroot = $webroot;
$webroot = $this->Html->webroot;
$this->Html->webroot = '/testing/longer/';
$this->Html->request->webroot = '/testing/longer/';
$result = $this->Html->css('cake.generic');
$expected['link']['href'] = 'preg:/\/testing\/longer\/css\/cake\.generic\.css\?[0-9]+/';
$this->assertTags($result, $expected);
$this->Html->webroot = $webroot;
}
/**
@ -617,7 +611,6 @@ class HtmlHelperTest extends CakeTestCase {
'script' => array('type' => 'text/javascript', 'src' => 'js/jquery-1.3.2.js', 'defer' => 'defer', 'encoding' => 'utf-8')
);
$this->assertTags($result, $expected);
$this->View->expects($this->any())->method('addScript')
->with($this->matchesRegularExpression('/script_in_head.js/'));
@ -709,7 +702,6 @@ class HtmlHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->View->expects($this->once())->method('addScript');
$result = $this->Html->scriptStart(array('safe' => false, 'inline' => false));
$this->assertNull($result);
echo 'this is some javascript';

View file

@ -96,6 +96,15 @@ class JsHelperTest extends CakeTestCase {
$controller = null;
$this->View = $this->getMock('View', array('addScript'), array(&$controller));
$this->Js = new JsHelper($this->View, 'Option');
$request = new CakeRequest(null, false);
$this->Js->request = $request;
$this->Js->Html = new HtmlHelper($this->View);
$this->Js->Html->request = $request;
$this->Js->Form = new FormHelper($this->View);
$this->Js->Form->request = $request;
$this->Js->Form->Html = $this->Js->Html;
$this->Js->OptionEngine = new OptionEngineHelper();
ClassRegistry::addObject('view', $this->View);
}
@ -118,12 +127,21 @@ class JsHelperTest extends CakeTestCase {
* @return void
*/
function _useMock() {
$request = new CakeRequest(null, false);
if (!class_exists('TestJsEngineHelper', false)) {
$this->getMock('JsBaseEngineHelper', array(), array(), 'TestJsEngineHelper');
}
$this->Js = new JsHelper($this->View, array('TestJs'));
$this->Js->TestJsEngine = new TestJsEngineHelper($this->View);
$this->mockObjects[] = $this->Js->TestJsEngine;
$this->Js->request = $request;
$this->Js->Html = new HtmlHelper($this->View);
$this->Js->Html->request = $request;
$this->Js->Form = new FormHelper($this->View);
$this->Js->Form->request = $request;
$this->Js->Form->Html = new HtmlHelper($this->View);
}
/**
@ -295,6 +313,7 @@ class JsHelperTest extends CakeTestCase {
if ($this->skipIf(!is_writable(JS), 'webroot/js is not Writable, script caching test has been skipped')) {
return;
}
$this->Js->request->webroot = '/';
$this->Js->JsBaseEngine = new TestJsEngineHelper();
$this->Js->buffer('one = 1;');
$this->Js->buffer('two = 2;');

View file

@ -17,6 +17,7 @@
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'View');
App::import('Helper', array('Html', 'Paginator', 'Form', 'Js'));
/**
@ -37,27 +38,31 @@ class PaginatorHelperTest extends CakeTestCase {
$controller = null;
$this->View = new View($controller);
$this->Paginator = new PaginatorHelper($this->View);
$this->Paginator->params['paging'] = array(
'Article' => array(
'current' => 9,
'count' => 62,
'prevPage' => false,
'nextPage' => true,
'pageCount' => 7,
'defaults' => array(
'order' => array('Article.date' => 'asc'),
'limit' => 9,
'conditions' => array()
),
'options' => array(
'order' => array('Article.date' => 'asc'),
'limit' => 9,
'page' => 1,
'conditions' => array()
$this->Paginator->Js = $this->getMock('PaginatorHelper', array(), array($this->View));
$this->Paginator->request = new CakeRequest(null, false);
$this->Paginator->request->addParams(array(
'paging' => array(
'Article' => array(
'current' => 9,
'count' => 62,
'prevPage' => false,
'nextPage' => true,
'pageCount' => 7,
'defaults' => array(
'order' => array('Article.date' => 'asc'),
'limit' => 9,
'conditions' => array()
),
'options' => array(
'order' => array('Article.date' => 'asc'),
'limit' => 9,
'page' => 1,
'conditions' => array()
)
)
)
);
$this->Paginator->Js = $this->getMock('PaginatorHelper', array(), array($this->View));
));
$this->Paginator->Html = new HtmlHelper($this->View);
Configure::write('Routing.prefixes', array());
Router::reload();
@ -81,9 +86,9 @@ class PaginatorHelperTest extends CakeTestCase {
*/
function testHasPrevious() {
$this->assertIdentical($this->Paginator->hasPrev(), false);
$this->Paginator->params['paging']['Article']['prevPage'] = true;
$this->Paginator->request->params['paging']['Article']['prevPage'] = true;
$this->assertIdentical($this->Paginator->hasPrev(), true);
$this->Paginator->params['paging']['Article']['prevPage'] = false;
$this->Paginator->request->params['paging']['Article']['prevPage'] = false;
}
/**
@ -94,9 +99,9 @@ class PaginatorHelperTest extends CakeTestCase {
*/
function testHasNext() {
$this->assertIdentical($this->Paginator->hasNext(), true);
$this->Paginator->params['paging']['Article']['nextPage'] = false;
$this->Paginator->request->params['paging']['Article']['nextPage'] = false;
$this->assertIdentical($this->Paginator->hasNext(), false);
$this->Paginator->params['paging']['Article']['nextPage'] = true;
$this->Paginator->request->params['paging']['Article']['nextPage'] = true;
}
/**
@ -106,13 +111,13 @@ class PaginatorHelperTest extends CakeTestCase {
* @return void
*/
function testDisabledLink() {
$this->Paginator->params['paging']['Article']['nextPage'] = false;
$this->Paginator->params['paging']['Article']['page'] = 1;
$this->Paginator->request->params['paging']['Article']['nextPage'] = false;
$this->Paginator->request->params['paging']['Article']['page'] = 1;
$result = $this->Paginator->next('Next', array(), true);
$expected = '<span class="next">Next</span>';
$this->assertEqual($result, $expected);
$this->Paginator->params['paging']['Article']['prevPage'] = false;
$this->Paginator->request->params['paging']['Article']['prevPage'] = false;
$result = $this->Paginator->prev('prev', array('update' => 'theList', 'indicator' => 'loading', 'url' => array('controller' => 'posts')), null, array('class' => 'disabled', 'tag' => 'span'));
$expected = array(
'span' => array('class' => 'disabled'), 'prev', '/span'
@ -166,7 +171,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['sort'] = 'title';
$this->Paginator->request->params['paging']['Article']['options']['sort'] = 'title';
$result = $this->Paginator->sort(array('asc' => 'ascending', 'desc' => 'descending'), 'title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/param/page:1/sort:title/direction:desc', 'class' => 'asc'),
@ -175,33 +180,35 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc" class="desc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('title');
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc" class="asc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'desc'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc" class="desc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'asc'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:asc" class="desc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'asc'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc" class="asc">Title<\/a>$/', $result);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['options']['sort'] = null;
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->request->params['paging']['Article']['options']['sort'] = null;
$result = $this->Paginator->sort('Title', 'title', array('direction' => 'desc'));
$this->assertPattern('/\/accounts\/index\/param\/page:1\/sort:title\/direction:desc" class="asc">Title<\/a>$/', $result);
@ -221,7 +228,7 @@ class PaginatorHelperTest extends CakeTestCase {
array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'form' => array(), 'url' => array('url' => 'accounts/')),
array('base' => '', 'here' => '/accounts/', 'webroot' => '/')
));
$this->Paginator->params['paging']['Article']['options']['order'] = array('full_name' => 'asc');
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('full_name' => 'asc');
$result = $this->Paginator->sort('Article.full_name');
$expected = array(
@ -239,7 +246,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('full_name' => 'desc');
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('full_name' => 'desc');
$result = $this->Paginator->sort('Article.full_name');
$expected = array(
'a' => array('href' => '/accounts/index/page:1/sort:Article.full_name/direction:asc', 'class' => 'desc'),
@ -305,7 +312,7 @@ class PaginatorHelperTest extends CakeTestCase {
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/', 'passedArgs' => array())
));
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$result = $this->Paginator->sort('Title','Article.title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:Article.title/direction:asc', 'class' => 'desc'),
@ -314,7 +321,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$result = $this->Paginator->sort('Title','Article.title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:Article.title/direction:desc', 'class' => 'asc'),
@ -323,7 +330,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Account.title' => 'asc');
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Account.title' => 'asc');
$result = $this->Paginator->sort('title');
$expected = array(
'a' => array('href' => '/officespace/accounts/index/page:1/sort:title/direction:asc'),
@ -364,48 +371,48 @@ class PaginatorHelperTest extends CakeTestCase {
$this->assertEqual($result, $expected);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'desc');
$result = $this->Paginator->sortDir();
$expected = 'desc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
unset($this->Paginator->request->params['paging']['Article']['options']);
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$result = $this->Paginator->sortDir();
$expected = 'asc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('title' => 'desc');
unset($this->Paginator->request->params['paging']['Article']['options']);
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('title' => 'desc');
$result = $this->Paginator->sortDir();
$expected = 'desc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['order'] = array('title' => 'asc');
unset($this->Paginator->request->params['paging']['Article']['options']);
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('title' => 'asc');
$result = $this->Paginator->sortDir();
$expected = 'asc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['direction'] = 'asc';
unset($this->Paginator->request->params['paging']['Article']['options']);
$this->Paginator->request->params['paging']['Article']['options']['direction'] = 'asc';
$result = $this->Paginator->sortDir();
$expected = 'asc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
$this->Paginator->params['paging']['Article']['options']['direction'] = 'desc';
unset($this->Paginator->request->params['paging']['Article']['options']);
$this->Paginator->request->params['paging']['Article']['options']['direction'] = 'desc';
$result = $this->Paginator->sortDir();
$expected = 'desc';
$this->assertEqual($result, $expected);
unset($this->Paginator->params['paging']['Article']['options']);
unset($this->Paginator->request->params['paging']['Article']['options']);
$result = $this->Paginator->sortDir('Article', array('direction' => 'asc'));
$expected = 'asc';
@ -437,7 +444,7 @@ class PaginatorHelperTest extends CakeTestCase {
array('base' => '', 'here' => '/admin/users', 'webroot' => '/')
));
Router::parse('/admin/users');
$this->Paginator->params['paging']['Article']['page'] = 1;
$this->Paginator->request->params['paging']['Article']['page'] = 1;
$result = $this->Paginator->next('Next');
$expected = array(
'<span',
@ -491,7 +498,7 @@ class PaginatorHelperTest extends CakeTestCase {
$result = $this->Paginator->url();
$this->assertEqual($result, '/index/page:1');
$this->Paginator->params['paging']['Article']['options']['page'] = 2;
$this->Paginator->request->params['paging']['Article']['options']['page'] = 2;
$result = $this->Paginator->url();
$this->assertEqual($result, '/index/page:2');
@ -499,7 +506,7 @@ class PaginatorHelperTest extends CakeTestCase {
$result = $this->Paginator->url($options);
$this->assertEqual($result, '/index/page:2/sort:Article/direction:desc');
$this->Paginator->params['paging']['Article']['options']['page'] = 3;
$this->Paginator->request->params['paging']['Article']['options']['page'] = 3;
$options = array('order' => array('Article.name' => 'desc'));
$result = $this->Paginator->url($options);
$this->assertEqual($result, '/index/page:3/sort:Article.name/direction:desc');
@ -524,9 +531,9 @@ class PaginatorHelperTest extends CakeTestCase {
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '', 'here' => 'posts/index', 'webroot' => '/')
));
$this->Paginator->params['paging']['Article']['options']['page'] = 2;
$this->Paginator->params['paging']['Article']['page'] = 2;
$this->Paginator->params['paging']['Article']['prevPage'] = true;
$this->Paginator->request->params['paging']['Article']['options']['page'] = 2;
$this->Paginator->request->params['paging']['Article']['page'] = 2;
$this->Paginator->request->params['paging']['Article']['prevPage'] = true;
$options = array('members' => true);
$result = $this->Paginator->url($options);
@ -585,7 +592,7 @@ class PaginatorHelperTest extends CakeTestCase {
$this->assertEqual('myDiv', $this->Paginator->options['update']);
$this->Paginator->options = array();
$this->Paginator->params = array();
$this->Paginator->request->params = array();
$options = array('paging' => array('Article' => array(
'order' => 'desc',
@ -597,17 +604,17 @@ class PaginatorHelperTest extends CakeTestCase {
'order' => 'desc',
'sort' => 'title'
));
$this->assertEqual($expected, $this->Paginator->params['paging']);
$this->assertEqual($expected, $this->Paginator->request->params['paging']);
$this->Paginator->options = array();
$this->Paginator->params = array();
$this->Paginator->request->params = array();
$options = array('Article' => array(
'order' => 'desc',
'sort' => 'title'
));
$this->Paginator->options($options);
$this->assertEqual($expected, $this->Paginator->params['paging']);
$this->assertEqual($expected, $this->Paginator->request->params['paging']);
$options = array('paging' => array('Article' => array(
'order' => 'desc',
@ -619,7 +626,7 @@ class PaginatorHelperTest extends CakeTestCase {
'order' => 'desc',
'sort' => 'Article.title'
));
$this->assertEqual($expected, $this->Paginator->params['paging']);
$this->assertEqual($expected, $this->Paginator->request->params['paging']);
}
/**
@ -635,7 +642,7 @@ class PaginatorHelperTest extends CakeTestCase {
array('plugin' => null, 'controller' => 'articles', 'action' => 'index', 'pass' => array('2'), 'named' => array('foo' => 'bar'), 'form' => array(), 'url' => array('url' => 'articles/index/2/foo:bar'), 'bare' => 0),
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '/', 'here' => '/articles/', 'webroot' => '/', 'passedArgs' => array(0 => '2', 'foo' => 'bar'))
));
$this->Paginator->params['paging'] = array(
$this->Paginator->request->params['paging'] = array(
'Article' => array(
'page' => 1, 'current' => 3, 'count' => 13,
'prevPage' => false, 'nextPage' => true, 'pageCount' => 8,
@ -648,8 +655,8 @@ class PaginatorHelperTest extends CakeTestCase {
)
);
$this->Paginator->params['pass'] = array(2);
$this->Paginator->params['named'] = array('foo' => 'bar');
$this->Paginator->request->params['pass'] = array(2);
$this->Paginator->request->params['named'] = array('foo' => 'bar');
$this->Paginator->beforeRender();
$result = $this->Paginator->sort('title');
@ -696,7 +703,7 @@ class PaginatorHelperTest extends CakeTestCase {
* @return void
*/
function testPagingLinks() {
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -717,8 +724,8 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 2;
$this->Paginator->params['paging']['Client']['prevPage'] = true;
$this->Paginator->request->params['paging']['Client']['page'] = 2;
$this->Paginator->request->params['paging']['Client']['prevPage'] = true;
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
$expected = array(
'<span',
@ -769,7 +776,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 1, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
'defaults' => array(),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -799,14 +806,14 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
'defaults' => array(),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
);
$this->Paginator->params['paging']['Client']['page'] = 2;
$this->Paginator->params['paging']['Client']['prevPage'] = true;
$this->Paginator->request->params['paging']['Client']['page'] = 2;
$this->Paginator->request->params['paging']['Client']['prevPage'] = true;
$result = $this->Paginator->prev('<< Previous', null, null, array('class' => 'disabled'));
$expected = array(
'<span',
@ -827,7 +834,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 2, 'current' => 1, 'count' => 13, 'prevPage' => true, 'nextPage' => false, 'pageCount' => 2,
'defaults' => array(),
'options' => array('page' => 2, 'limit' => 10, 'order' => array(), 'conditions' => array())
@ -842,7 +849,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array(
$this->Paginator->request->params['paging'] = array(
'Client' => array(
'page' => 2, 'current' => 1, 'count' => 13, 'prevPage' => true,
'nextPage' => false, 'pageCount' => 2,
@ -871,7 +878,7 @@ class PaginatorHelperTest extends CakeTestCase {
* @return void
*/
function testPagingLinksOptionsReplaceEmptyDisabledOptions() {
$this->Paginator->params['paging'] = array(
$this->Paginator->request->params['paging'] = array(
'Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false,
'nextPage' => true, 'pageCount' => 5,
@ -912,7 +919,7 @@ class PaginatorHelperTest extends CakeTestCase {
*/
function testPagingLinksNotDefaultModel() {
// Multiple Model Paginate
$this->Paginator->params['paging'] = array(
$this->Paginator->request->params['paging'] = array(
'Client' => array(
'page' => 1, 'current' => 3, 'count' => 13, 'prevPage' => false, 'nextPage' => true, 'pageCount' => 5,
'defaults' => array( 'limit'=>3, 'order' => array('Client.name' => 'DESC')),
@ -956,7 +963,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['page'] = 2;
$this->Paginator->request->params['paging']['Article']['options']['page'] = 2;
$result = $this->Paginator->link('Sort by title', array('sort' => 'title', 'direction' => 'desc'));
$expected = array(
'a' => array('href' => '/index/page:2/sort:title/direction:desc'),
@ -965,7 +972,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Article']['options']['page'] = 4;
$this->Paginator->request->params['paging']['Article']['options']['page'] = 4;
$result = $this->Paginator->link('Sort by title on page 4', array('sort' => 'Article.title', 'direction' => 'desc'));
$expected = array(
'a' => array('href' => '/index/page:4/sort:Article.title/direction:desc'),
@ -1020,7 +1027,7 @@ class PaginatorHelperTest extends CakeTestCase {
* @return void
*/
function testNumbers() {
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 8, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1109,7 +1116,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1137,7 +1144,7 @@ class PaginatorHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 14, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1164,7 +1171,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 2, 'current' => 3, 'count' => 27, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 9,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1214,7 +1221,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 15, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1245,7 +1252,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 10, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1277,7 +1284,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 6, 'current' => 15, 'count' => 623, 'prevPage' => 1, 'nextPage' => 1, 'pageCount' => 42,
'defaults' => array('limit' => 15, 'step' => 1, 'page' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 6, 'limit' => 15, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1309,7 +1316,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 37, 'current' => 15, 'count' => 623, 'prevPage' => 1, 'nextPage' => 1, 'pageCount' => 42,
'defaults' => array('limit' => 15, 'step' => 1, 'page' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 37, 'limit' => 15, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1341,7 +1348,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array(
$this->Paginator->request->params['paging'] = array(
'Client' => array(
'page' => 1,
'current' => 10,
@ -1374,7 +1381,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 2, 'current' => 10, 'count' => 31, 'prevPage' => true, 'nextPage' => true, 'pageCount' => 4,
'defaults' => array('limit' => 10),
'options' => array('page' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1392,7 +1399,7 @@ class PaginatorHelperTest extends CakeTestCase {
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 4895, 'current' => 10, 'count' => 48962, 'prevPage' => 1, 'nextPage' => 1, 'pageCount' => 4897,
'defaults' => array('limit' => 10),
'options' => array('page' => 4894, 'limit' => 10, 'order' => 'Client.name DESC', 'conditions' => array()))
@ -1414,7 +1421,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 3;
$this->Paginator->request->params['paging']['Client']['page'] = 3;
$result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
$expected = array(
@ -1474,7 +1481,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 4893;
$this->Paginator->request->params['paging']['Client']['page'] = 4893;
$result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
@ -1503,7 +1510,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 58;
$this->Paginator->request->params['paging']['Client']['page'] = 58;
$result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
@ -1538,7 +1545,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging']['Client']['page'] = 5;
$this->Paginator->request->params['paging']['Client']['page'] = 5;
$result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5, 'separator' => ' - '));
$expected = array(
array('span' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/span',
@ -1575,7 +1582,7 @@ class PaginatorHelperTest extends CakeTestCase {
* @return void
*/
function testFirstAndLast() {
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 1, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1585,7 +1592,7 @@ class PaginatorHelperTest extends CakeTestCase {
$expected = '';
$this->assertEqual($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 4, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1658,7 +1665,7 @@ class PaginatorHelperTest extends CakeTestCase {
);
$this->assertTags($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 15, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3, 'step' => 1, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1667,7 +1674,7 @@ class PaginatorHelperTest extends CakeTestCase {
$expected = '';
$this->assertEqual($result, $expected);
$this->Paginator->params['paging'] = array('Client' => array(
$this->Paginator->request->params['paging'] = array('Client' => array(
'page' => 4, 'current' => 3, 'count' => 30, 'prevPage' => false, 'nextPage' => 2, 'pageCount' => 15,
'defaults' => array('limit' => 3),
'options' => array('page' => 1, 'limit' => 3, 'order' => array('Client.name' => 'DESC'), 'conditions' => array()))
@ -1719,7 +1726,7 @@ class PaginatorHelperTest extends CakeTestCase {
* @return void
*/
function testCounter() {
$this->Paginator->params['paging'] = array(
$this->Paginator->request->params['paging'] = array(
'Client' => array(
'page' => 1,
'current' => 3,
@ -1856,8 +1863,8 @@ class PaginatorHelperTest extends CakeTestCase {
array('plugin' => null, 'controller' => null, 'action' => null, 'base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/', 'passedArgs' => array())
));
$this->Paginator->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->params['paging']['Article']['page'] = 1;
$this->Paginator->request->params['paging']['Article']['options']['order'] = array('Article.title' => 'asc');
$this->Paginator->request->params['paging']['Article']['page'] = 1;
$test = array('url'=> array(
'page'=> '1',
@ -1913,7 +1920,7 @@ class PaginatorHelperTest extends CakeTestCase {
function testMockAjaxProviderClassInjection() {
$mock = $this->getMock('PaginatorHelper', array(), array($this->View), 'PaginatorMockJsHelper');
$Paginator = new PaginatorHelper($this->View, array('ajax' => 'PaginatorMockJs'));
$Paginator->params['paging'] = array(
$Paginator->request->params['paging'] = array(
'Article' => array(
'current' => 9,
'count' => 62,

View file

@ -28,14 +28,6 @@ App::import('Helper', 'Text');
*/
class TextHelperTest extends CakeTestCase {
/**
* helper property
*
* @var mixed null
* @access public
*/
public $helper = null;
/**
* setUp method
*

View file

@ -17,9 +17,6 @@
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import('Helper', 'Time');
/**