Merge branch '1.3-misc' of dev@code.cakephp.org:cakephp into 1.3-misc

This commit is contained in:
mark_story 2009-11-24 22:10:11 -05:00
commit 3b1256cefb
162 changed files with 2719 additions and 1468 deletions

View file

@ -29,7 +29,7 @@
* 'plugins' => array('/full/path/to/plugins/', '/next/full/path/to/plugins/'), * 'plugins' => array('/full/path/to/plugins/', '/next/full/path/to/plugins/'),
* 'models' => array('/full/path/to/models/', '/next/full/path/to/models/'), * 'models' => array('/full/path/to/models/', '/next/full/path/to/models/'),
* 'views' => array('/full/path/to/views/', '/next/full/path/to/views/'), * 'views' => array('/full/path/to/views/', '/next/full/path/to/views/'),
* 'controllers' => array(/full/path/to/controllers/', '/next/full/path/to/controllers/'), * 'controllers' => array('/full/path/to/controllers/', '/next/full/path/to/controllers/'),
* 'datasources' => array('/full/path/to/datasources/', '/next/full/path/to/datasources/'), * 'datasources' => array('/full/path/to/datasources/', '/next/full/path/to/datasources/'),
* 'behaviors' => array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/'), * 'behaviors' => array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/'),
* 'components' => array('/full/path/to/components/', '/next/full/path/to/components/'), * 'components' => array('/full/path/to/components/', '/next/full/path/to/components/'),

View file

@ -69,22 +69,12 @@
*/ */
//Configure::write('App.baseUrl', env('SCRIPT_NAME')); //Configure::write('App.baseUrl', env('SCRIPT_NAME'));
/**
* Uncomment the define below to use CakePHP admin routes.
*
* The value of the define determines the name of the route
* and its associated controller actions:
*
* 'admin' -> admin_index() and /admin/controller/index
* 'superuser' -> superuser_index() and /superuser/controller/index
*
* [Note Routing.admin is deprecated in 1.3. Use Routing.prefixes instead]
*/
//Configure::write('Routing.admin', 'admin');
/** /**
* Uncomment the define below to use CakePHP prefix routes. * Uncomment the define below to use CakePHP prefix routes.
* *
* The value of the define determines the names of the routes
* and their associated controller actions:
*
* Set to an array of prefixes you want to use in your application. Use for * Set to an array of prefixes you want to use in your application. Use for
* admin or other prefixed routes. * admin or other prefixed routes.
* *
@ -93,6 +83,8 @@
* Enables: * Enables:
* `admin_index()` and `/admin/controller/index` * `admin_index()` and `/admin/controller/index`
* `manager_index()` and `/manager/controller/index` * `manager_index()` and `/manager/controller/index`
*
* [Note Routing.admin is deprecated in 1.3. Use Routing.prefixes instead]
*/ */
//Configure::write('Routing.prefixes', array('admin')); //Configure::write('Routing.prefixes', array('admin'));

View file

@ -212,6 +212,28 @@ if (!function_exists('array_combine')) {
return htmlspecialchars($text, ENT_QUOTES, $charset); return htmlspecialchars($text, ENT_QUOTES, $charset);
} }
/**
* Splits a dot syntax plugin name into its plugin and classname.
* If $name does not have a dot, then index 0 will be null.
*
* Commonly used like `list($plugin, $name) = pluginSplit($name);`
*
* @param string $name The name you want to plugin split.
* @param boolean $dotAppend Set to true if you want the plugin to have a '.' appended to it.
* @param string $plugin Optional default plugin to use if no plugin is found. Defaults to null.
* @return array Array with 2 indexes. 0 => plugin name, 1 => classname
*/
function pluginSplit($name, $dotAppend = false, $plugin = null) {
if (strpos($name, '.') !== false) {
$parts = explode('.', $name, 2);
if ($dotAppend) {
$parts[0] .= '.';
}
return $parts;
}
return array($plugin, $name);
}
/** /**
* Returns an array of all the given parameters. * Returns an array of all the given parameters.
* *

View file

@ -317,13 +317,8 @@ class ShellDispatcher {
$this->help(); $this->help();
return true; return true;
} }
if (strpos($arg, '.') !== false) { list($plugin, $shell) = pluginSplit($arg);
list($plugin, $shell) = explode('.', $arg);
} else {
$plugin = null;
$shell = $arg;
}
$this->shell = $shell; $this->shell = $shell;
$this->shellName = Inflector::camelize($shell); $this->shellName = Inflector::camelize($shell);
$this->shellClass = $this->shellName . 'Shell'; $this->shellClass = $this->shellName . 'Shell';

View file

@ -236,7 +236,7 @@ class AclShell extends Shell {
* @param integer $indent indent level. * @param integer $indent indent level.
* @return void * @return void
* @access protected * @access protected
**/ */
function _outputNode($class, $node, $indent) { function _outputNode($class, $node, $indent) {
$indent = str_repeat(' ', $indent); $indent = str_repeat(' ', $indent);
$data = $node[$class]; $data = $node[$class];
@ -521,7 +521,7 @@ class AclShell extends Shell {
* *
* @param string $identifier Identifier to parse * @param string $identifier Identifier to parse
* @return mixed a string for aliases, and an array for model.foreignKey * @return mixed a string for aliases, and an array for model.foreignKey
**/ */
function parseIdentifier($identifier) { function parseIdentifier($identifier) {
if (preg_match('/^([\w]+)\.(.*)$/', $identifier, $matches)) { if (preg_match('/^([\w]+)\.(.*)$/', $identifier, $matches)) {
return array( return array(
@ -539,7 +539,7 @@ class AclShell extends Shell {
* @param string $class Class type you want (Aro/Aco) * @param string $class Class type you want (Aro/Aco)
* @param mixed $identifier A mixed identifier for finding the node. * @param mixed $identifier A mixed identifier for finding the node.
* @return int Integer of NodeId. Will trigger an error if nothing is found. * @return int Integer of NodeId. Will trigger an error if nothing is found.
**/ */
function _getNodeId($class, $identifier) { function _getNodeId($class, $identifier) {
$node = $this->Acl->{$class}->node($identifier); $node = $this->Acl->{$class}->node($identifier);
if (empty($node)) { if (empty($node)) {

View file

@ -57,7 +57,7 @@ class BakeShell extends Shell {
} }
foreach($this->args as $i => $arg) { foreach($this->args as $i => $arg) {
if (strpos($arg, '.')) { if (strpos($arg, '.')) {
list($this->params['plugin'], $this->args[$i]) = explode('.', $arg); list($this->params['plugin'], $this->args[$i]) = pluginSplit($arg);
break; break;
} }
} }
@ -230,6 +230,8 @@ class BakeShell extends Shell {
$this->out("\n\tbake model\n\t\tbakes a model. run 'bake model help' for more info"); $this->out("\n\tbake model\n\t\tbakes a model. run 'bake model help' for more info");
$this->out("\n\tbake view\n\t\tbakes views. run 'bake view help' for more info"); $this->out("\n\tbake view\n\t\tbakes views. run 'bake view help' for more info");
$this->out("\n\tbake controller\n\t\tbakes a controller. run 'bake controller help' for more info"); $this->out("\n\tbake controller\n\t\tbakes a controller. run 'bake controller help' for more info");
$this->out("\n\tbake fixture\n\t\tbakes fixtures. run 'bake fixture help' for more info.");
$this->out("\n\tbake test\n\t\tbakes unit tests. run 'bake test help' for more info.");
$this->out(); $this->out();
} }

View file

@ -103,7 +103,7 @@ class I18nShell extends Shell {
* @access public * @access public
*/ */
function initdb() { function initdb() {
$this->Dispatch->args = array('schema', 'run', 'create', 'i18n'); $this->Dispatch->args = array('schema', 'create', 'i18n');
$this->Dispatch->dispatch(); $this->Dispatch->dispatch();
} }

View file

@ -63,9 +63,10 @@ class SchemaShell extends Shell {
} elseif (!empty($this->args[0])) { } elseif (!empty($this->args[0])) {
$name = $this->params['name'] = $this->args[0]; $name = $this->params['name'] = $this->args[0];
} }
if (strpos($name, '.')) { if (strpos($name, '.')) {
list($this->params['plugin'], $this->params['name']) = explode('.', $name); list($this->params['plugin'], $splitName) = pluginSplit($name);
$name = $this->params['name']; $name = $this->params['name'] = $splitName;
} }
if ($name) { if ($name) {
@ -242,7 +243,7 @@ class SchemaShell extends Shell {
* Run database create commands. Alias for run create. * Run database create commands. Alias for run create.
* *
* @return void * @return void
**/ */
function create() { function create() {
list($Schema, $table) = $this->_loadSchema(); list($Schema, $table) = $this->_loadSchema();
$this->__create($Schema, $table); $this->__create($Schema, $table);
@ -252,7 +253,7 @@ class SchemaShell extends Shell {
* Run database create commands. Alias for run create. * Run database create commands. Alias for run create.
* *
* @return void * @return void
**/ */
function update() { function update() {
list($Schema, $table) = $this->_loadSchema(); list($Schema, $table) = $this->_loadSchema();
$this->__update($Schema, $table); $this->__update($Schema, $table);
@ -262,7 +263,7 @@ class SchemaShell extends Shell {
* Prepares the Schema objects for database operations. * Prepares the Schema objects for database operations.
* *
* @return void * @return void
**/ */
function _loadSchema() { function _loadSchema() {
$name = $plugin = null; $name = $plugin = null;
if (isset($this->params['name'])) { if (isset($this->params['name'])) {

View file

@ -254,11 +254,7 @@ class Shell extends Object {
$this->modelClass = $modelClassName; $this->modelClass = $modelClassName;
foreach ($uses as $modelClass) { foreach ($uses as $modelClass) {
$plugin = null; list($plugin, $modelClass) = pluginSplit($modelClass, true);
if (strpos($modelClass, '.') !== false) {
list($plugin, $modelClass) = explode('.', $modelClass);
$plugin = $plugin . '.';
}
if (PHP5) { if (PHP5) {
$this->{$modelClass} = ClassRegistry::init($plugin . $modelClass); $this->{$modelClass} = ClassRegistry::init($plugin . $modelClass);
} else { } else {
@ -642,7 +638,7 @@ class Shell extends Object {
* *
* @param string $pluginName Name of the plugin you want ie. DebugKit * @param string $pluginName Name of the plugin you want ie. DebugKit
* @return string $path path to the correct plugin. * @return string $path path to the correct plugin.
**/ */
function _pluginPath($pluginName) { function _pluginPath($pluginName) {
return App::pluginPath($pluginName); return App::pluginPath($pluginName);
} }

View file

@ -113,7 +113,7 @@ class ControllerTask extends Shell {
* *
* @access public * @access public
* @return void * @return void
**/ */
function all() { function all() {
$this->interactive = false; $this->interactive = false;
$this->listAll($this->connection, false); $this->listAll($this->connection, false);
@ -219,7 +219,7 @@ class ControllerTask extends Shell {
* Confirm a to be baked controller with the user * Confirm a to be baked controller with the user
* *
* @return void * @return void
**/ */
function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) { function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
$this->out(); $this->out();
$this->hr(); $this->hr();
@ -257,7 +257,7 @@ class ControllerTask extends Shell {
* Interact with the user and ask about which methods (admin or regular they want to bake) * Interact with the user and ask about which methods (admin or regular they want to bake)
* *
* @return array Array containing (bakeRegular, bakeAdmin) answers * @return array Array containing (bakeRegular, bakeAdmin) answers
**/ */
function _askAboutMethods() { function _askAboutMethods() {
$wannaBakeCrud = $this->in( $wannaBakeCrud = $this->in(
__("Would you like to create some basic class methods \n(index(), add(), view(), edit())?", true), __("Would you like to create some basic class methods \n(index(), add(), view(), edit())?", true),
@ -348,7 +348,7 @@ class ControllerTask extends Shell {
* Interact with the user and get a list of additional helpers * Interact with the user and get a list of additional helpers
* *
* @return array Helpers that the user wants to use. * @return array Helpers that the user wants to use.
**/ */
function doHelpers() { function doHelpers() {
return $this->_doPropertyChoices( return $this->_doPropertyChoices(
__("Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?", true), __("Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?", true),
@ -360,7 +360,7 @@ class ControllerTask extends Shell {
* Interact with the user and get a list of additional components * Interact with the user and get a list of additional components
* *
* @return array Components the user wants to use. * @return array Components the user wants to use.
**/ */
function doComponents() { function doComponents() {
return $this->_doPropertyChoices( return $this->_doPropertyChoices(
__("Would you like this controller to use any components?", true), __("Would you like this controller to use any components?", true),
@ -374,7 +374,7 @@ class ControllerTask extends Shell {
* @param string $prompt A yes/no question to precede the list * @param string $prompt A yes/no question to precede the list
* @param sting $example A question for a comma separated list, with examples. * @param sting $example A question for a comma separated list, with examples.
* @return array Array of values for property. * @return array Array of values for property.
**/ */
function _doPropertyChoices($prompt, $example) { function _doPropertyChoices($prompt, $example) {
$proceed = $this->in($prompt, array('y','n'), 'n'); $proceed = $this->in($prompt, array('y','n'), 'n');
$property = array(); $property = array();

View file

@ -53,7 +53,7 @@ class DbConfigTask extends Shell {
* Used for testing. * Used for testing.
* *
* @var string * @var string
**/ */
var $databaseClassName = 'DATABASE_CONFIG'; var $databaseClassName = 'DATABASE_CONFIG';
/** /**
@ -258,6 +258,7 @@ class DbConfigTask extends Shell {
$oldConfigs = array(); $oldConfigs = array();
if (file_exists($filename)) { if (file_exists($filename)) {
config('database');
$db = new $this->databaseClassName; $db = new $this->databaseClassName;
$temp = get_class_vars(get_class($db)); $temp = get_class_vars(get_class($db));
@ -350,7 +351,7 @@ class DbConfigTask extends Shell {
* Get a user specified Connection name * Get a user specified Connection name
* *
* @return void * @return void
**/ */
function getConfig() { function getConfig() {
App::import('Model', 'ConnectionManager', false); App::import('Model', 'ConnectionManager', false);

View file

@ -54,14 +54,14 @@ class FixtureTask extends Shell {
* The db connection being used for baking * The db connection being used for baking
* *
* @var string * @var string
**/ */
var $connection = null; var $connection = null;
/** /**
* Schema instance * Schema instance
* *
* @var object * @var object
**/ */
var $_Schema = null; var $_Schema = null;
/** /**
@ -103,7 +103,7 @@ class FixtureTask extends Shell {
* *
* @access public * @access public
* @return void * @return void
**/ */
function all() { function all() {
$this->interactive = false; $this->interactive = false;
$this->Model->interactive = false; $this->Model->interactive = false;
@ -140,7 +140,7 @@ class FixtureTask extends Shell {
* *
* @param string $modelName Name of model you are dealing with. * @param string $modelName Name of model you are dealing with.
* @return array Array of import options. * @return array Array of import options.
**/ */
function importOptions($modelName) { function importOptions($modelName) {
$options = array(); $options = array();
$doSchema = $this->in(__('Would you like to import schema for this fixture?', true), array('y', 'n'), 'n'); $doSchema = $this->in(__('Would you like to import schema for this fixture?', true), array('y', 'n'), 'n');
@ -230,7 +230,7 @@ class FixtureTask extends Shell {
* @param string $fixture Contents of the fixture file. * @param string $fixture Contents of the fixture file.
* @access public * @access public
* @return void * @return void
**/ */
function generateFixtureFile($model, $otherVars) { function generateFixtureFile($model, $otherVars) {
$defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null); $defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
$vars = array_merge($defaults, $otherVars); $vars = array_merge($defaults, $otherVars);
@ -255,7 +255,7 @@ class FixtureTask extends Shell {
* *
* @param array $table Table schema array * @param array $table Table schema array
* @return string fields definitions * @return string fields definitions
**/ */
function _generateSchema($tableInfo) { function _generateSchema($tableInfo) {
$schema = $this->_Schema->generateTable('f', $tableInfo); $schema = $this->_Schema->generateTable('f', $tableInfo);
return substr($schema, 10, -2); return substr($schema, 10, -2);
@ -266,7 +266,7 @@ class FixtureTask extends Shell {
* *
* @param array $table Table schema array * @param array $table Table schema array
* @return array Array of records to use in the fixture. * @return array Array of records to use in the fixture.
**/ */
function _generateRecords($tableInfo, $recordCount = 1) { function _generateRecords($tableInfo, $recordCount = 1) {
$records = array(); $records = array();
for ($i = 0; $i < $recordCount; $i++) { for ($i = 0; $i < $recordCount; $i++) {
@ -277,9 +277,11 @@ class FixtureTask extends Shell {
} }
switch ($fieldInfo['type']) { switch ($fieldInfo['type']) {
case 'integer': case 'integer':
case 'float':
$insert = $i + 1; $insert = $i + 1;
break; break;
case 'string'; case 'string':
case 'binary':
$isPrimaryUuid = ( $isPrimaryUuid = (
isset($fieldInfo['key']) && strtolower($fieldInfo['key']) == 'primary' && isset($fieldInfo['key']) && strtolower($fieldInfo['key']) == 'primary' &&
isset($fieldInfo['length']) && $fieldInfo['length'] == 36 isset($fieldInfo['length']) && $fieldInfo['length'] == 36
@ -335,7 +337,7 @@ class FixtureTask extends Shell {
* *
* @param array $records Array of records to be converted to string * @param array $records Array of records to be converted to string
* @return string A string value of the $records array. * @return string A string value of the $records array.
**/ */
function _makeRecordString($records) { function _makeRecordString($records) {
$out = "array(\n"; $out = "array(\n";
foreach ($records as $record) { foreach ($records as $record) {
@ -358,7 +360,7 @@ class FixtureTask extends Shell {
* @param string $modelName name of the model to take records from. * @param string $modelName name of the model to take records from.
* @param string $useTable Name of table to use. * @param string $useTable Name of table to use.
* @return array Array of records. * @return array Array of records.
**/ */
function _getRecordsFromTable($modelName, $useTable = null) { function _getRecordsFromTable($modelName, $useTable = null) {
if ($this->interactive) { if ($this->interactive) {
$condition = null; $condition = null;

View file

@ -64,14 +64,14 @@ class ModelTask extends Shell {
* Holds tables found on connection. * Holds tables found on connection.
* *
* @var array * @var array
**/ */
var $__tables = array(); var $__tables = array();
/** /**
* Holds validation method map. * Holds validation method map.
* *
* @var array * @var array
**/ */
var $__validations = array(); var $__validations = array();
/** /**
@ -80,6 +80,8 @@ class ModelTask extends Shell {
* @access public * @access public
*/ */
function execute() { function execute() {
App::import('Model', 'Model', false);
if (empty($this->args)) { if (empty($this->args)) {
$this->__interactive(); $this->__interactive();
} }
@ -107,7 +109,7 @@ class ModelTask extends Shell {
* Bake all models at once. * Bake all models at once.
* *
* @return void * @return void
**/ */
function all() { function all() {
$this->listAll($this->connection, false); $this->listAll($this->connection, false);
$unitTestExists = $this->_checkUnitTest(); $unitTestExists = $this->_checkUnitTest();
@ -127,9 +129,12 @@ class ModelTask extends Shell {
* *
* @param string $className Name of class you want model to be. * @param string $className Name of class you want model to be.
* @return object Model instance * @return object Model instance
**/ */
function &_getModelObject($className) { function &_getModelObject($className, $table = null) {
$object = new Model(array('name' => $className, 'ds' => $this->connection)); if (!$table) {
$table = Inflector::tableize($className);
}
$object =& new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
return $object; return $object;
} }
@ -140,7 +145,7 @@ class ModelTask extends Shell {
* @param string $prompt Prompt to use for options list. * @param string $prompt Prompt to use for options list.
* @param integer $default The default option for the given prompt. * @param integer $default The default option for the given prompt.
* @return result of user choice. * @return result of user choice.
**/ */
function inOptions($options, $prompt = null, $default = null) { function inOptions($options, $prompt = null, $default = null) {
$valid = false; $valid = false;
$max = count($options); $max = count($options);
@ -165,8 +170,6 @@ class ModelTask extends Shell {
* @access private * @access private
*/ */
function __interactive() { function __interactive() {
App::import('Model', 'Model', false);
$this->hr(); $this->hr();
$this->out(sprintf("Bake Model\nPath: %s", $this->path)); $this->out(sprintf("Bake Model\nPath: %s", $this->path));
$this->hr(); $this->hr();
@ -262,7 +265,7 @@ class ModelTask extends Shell {
* @param string $associations Collection of associations. * @param string $associations Collection of associations.
* @access protected * @access protected
* @return void * @return void
**/ */
function _printAssociation($modelName, $type, $associations) { function _printAssociation($modelName, $type, $associations) {
if (!empty($associations[$type])) { if (!empty($associations[$type])) {
for ($i = 0; $i < count($associations[$type]); $i++) { for ($i = 0; $i < count($associations[$type]); $i++) {
@ -278,7 +281,7 @@ class ModelTask extends Shell {
* @param array $fields Array of fields that might have a primary key. * @param array $fields Array of fields that might have a primary key.
* @return string Name of field that is a primary key. * @return string Name of field that is a primary key.
* @access public * @access public
**/ */
function findPrimaryKey($fields) { function findPrimaryKey($fields) {
foreach ($fields as $name => $field) { foreach ($fields as $name => $field) {
if (isset($field['key']) && $field['key'] == 'primary') { if (isset($field['key']) && $field['key'] == 'primary') {
@ -293,7 +296,7 @@ class ModelTask extends Shell {
* *
* @param array $fields Array of fields to look for and choose as a displayField * @param array $fields Array of fields to look for and choose as a displayField
* @return mixed Name of field to use for displayField or false if the user declines to choose * @return mixed Name of field to use for displayField or false if the user declines to choose
**/ */
function findDisplayField($fields) { function findDisplayField($fields) {
$fieldNames = array_keys($fields); $fieldNames = array_keys($fields);
$prompt = __("A displayField could not be automatically detected\nwould you like to choose one?", true); $prompt = __("A displayField could not be automatically detected\nwould you like to choose one?", true);
@ -337,7 +340,7 @@ class ModelTask extends Shell {
* Populate the __validations array * Populate the __validations array
* *
* @return void * @return void
**/ */
function initValidations() { function initValidations() {
$options = $choices = array(); $options = $choices = array();
if (class_exists('Validation')) { if (class_exists('Validation')) {
@ -363,7 +366,7 @@ class ModelTask extends Shell {
* @param string $fieldName Name of field to be validated. * @param string $fieldName Name of field to be validated.
* @param array $metaData metadata for field * @param array $metaData metadata for field
* @return array Array of validation for the field. * @return array Array of validation for the field.
**/ */
function fieldValidation($fieldName, $metaData, $primaryKey = 'id') { function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
$defaultChoice = count($this->__validations); $defaultChoice = count($this->__validations);
$validate = $alreadyChosen = array(); $validate = $alreadyChosen = array();
@ -484,7 +487,7 @@ class ModelTask extends Shell {
* @param object $model Model instance of model being generated. * @param object $model Model instance of model being generated.
* @param array $associations Array of inprogress associations * @param array $associations Array of inprogress associations
* @return array $associations with belongsTo added in. * @return array $associations with belongsTo added in.
**/ */
function findBelongsTo(&$model, $associations) { function findBelongsTo(&$model, $associations) {
$fields = $model->schema(); $fields = $model->schema();
foreach ($fields as $fieldName => $field) { foreach ($fields as $fieldName => $field) {
@ -513,11 +516,11 @@ class ModelTask extends Shell {
* @param object $model Model instance being generated * @param object $model Model instance being generated
* @param array $associations Array of inprogress associations * @param array $associations Array of inprogress associations
* @return array $associations with hasOne and hasMany added in. * @return array $associations with hasOne and hasMany added in.
**/ */
function findHasOneAndMany(&$model, $associations) { function findHasOneAndMany(&$model, $associations) {
$foreignKey = $this->_modelKey($model->name); $foreignKey = $this->_modelKey($model->name);
foreach ($this->__tables as $otherTable) { foreach ($this->__tables as $otherTable) {
$tempOtherModel = $this->_getModelObject($this->_modelName($otherTable)); $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
$modelFieldsTemp = $tempOtherModel->schema(); $modelFieldsTemp = $tempOtherModel->schema();
$pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/'; $pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
@ -556,11 +559,11 @@ class ModelTask extends Shell {
* @param object $model Model instance being generated * @param object $model Model instance being generated
* @param array $associations Array of inprogress associations * @param array $associations Array of inprogress associations
* @return array $associations with hasAndBelongsToMany added in. * @return array $associations with hasAndBelongsToMany added in.
**/ */
function findHasAndBelongsToMany(&$model, $associations) { function findHasAndBelongsToMany(&$model, $associations) {
$foreignKey = $this->_modelKey($model->name); $foreignKey = $this->_modelKey($model->name);
foreach ($this->__tables as $otherTable) { foreach ($this->__tables as $otherTable) {
$tempOtherModel = $this->_getModelObject($this->_modelName($otherTable)); $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
$modelFieldsTemp = $tempOtherModel->schema(); $modelFieldsTemp = $tempOtherModel->schema();
$offset = strpos($otherTable, $model->table . '_'); $offset = strpos($otherTable, $model->table . '_');
@ -596,7 +599,7 @@ class ModelTask extends Shell {
* @param array $model Temporary Model instance. * @param array $model Temporary Model instance.
* @param array $associations Array of associations to be confirmed. * @param array $associations Array of associations to be confirmed.
* @return array Array of confirmed associations * @return array Array of confirmed associations
**/ */
function confirmAssociations(&$model, $associations) { function confirmAssociations(&$model, $associations) {
foreach ($associations as $type => $settings) { foreach ($associations as $type => $settings) {
if (!empty($associations[$type])) { if (!empty($associations[$type])) {
@ -624,7 +627,7 @@ class ModelTask extends Shell {
* @param object $model Temporary model instance * @param object $model Temporary model instance
* @param array $associations Array of associations. * @param array $associations Array of associations.
* @return array Array of associations. * @return array Array of associations.
**/ */
function doMoreAssociations($model, $associations) { function doMoreAssociations($model, $associations) {
$prompt = __('Would you like to define some additional model associations?', true); $prompt = __('Would you like to define some additional model associations?', true);
$wannaDoMoreAssoc = $this->in($prompt, array('y','n'), 'n'); $wannaDoMoreAssoc = $this->in($prompt, array('y','n'), 'n');
@ -689,7 +692,7 @@ class ModelTask extends Shell {
* Finds all possible keys to use on custom associations. * Finds all possible keys to use on custom associations.
* *
* @return array array of tables and possible keys * @return array array of tables and possible keys
**/ */
function _generatePossibleKeys() { function _generatePossibleKeys() {
$possible = array(); $possible = array();
foreach ($this->__tables as $otherTable) { foreach ($this->__tables as $otherTable) {
@ -782,7 +785,7 @@ class ModelTask extends Shell {
* @param string $modelName Name of the model you want a table for. * @param string $modelName Name of the model you want a table for.
* @param string $useDbConfig Name of the database config you want to get tables from. * @param string $useDbConfig Name of the database config you want to get tables from.
* @return void * @return void
**/ */
function getTable($modelName, $useDbConfig = null) { function getTable($modelName, $useDbConfig = null) {
if (!isset($useDbConfig)) { if (!isset($useDbConfig)) {
$useDbConfig = $this->connection; $useDbConfig = $this->connection;
@ -811,7 +814,7 @@ class ModelTask extends Shell {
* *
* @param string $useDbConfig Connection name to scan. * @param string $useDbConfig Connection name to scan.
* @return array Array of tables in the database. * @return array Array of tables in the database.
**/ */
function getAllTables($useDbConfig = null) { function getAllTables($useDbConfig = null) {
if (!isset($useDbConfig)) { if (!isset($useDbConfig)) {
$useDbConfig = $this->connection; $useDbConfig = $this->connection;
@ -906,7 +909,7 @@ class ModelTask extends Shell {
* @access public * @access public
* @return void * @return void
* @see FixtureTask::bake * @see FixtureTask::bake
**/ */
function bakeFixture($className, $useTable = null) { function bakeFixture($className, $useTable = null) {
$this->Fixture->connection = $this->connection; $this->Fixture->connection = $this->connection;
$this->Fixture->plugin = $this->plugin; $this->Fixture->plugin = $this->plugin;

View file

@ -204,7 +204,7 @@ class PluginTask extends Shell {
* find and change $this->path to the user selection * find and change $this->path to the user selection
* *
* @return void * @return void
**/ */
function findPath($pathOptions) { function findPath($pathOptions) {
$valid = false; $valid = false;
$max = count($pathOptions); $max = count($pathOptions);

View file

@ -30,7 +30,7 @@ class ProjectTask extends Shell {
* configs path (used in testing). * configs path (used in testing).
* *
* @var string * @var string
**/ */
var $configPath = null; var $configPath = null;
/** /**
@ -149,6 +149,9 @@ class ProjectTask extends Shell {
$verbose = $this->in(__('Do you want verbose output?', true), array('y', 'n'), 'n'); $verbose = $this->in(__('Do you want verbose output?', true), array('y', 'n'), 'n');
$Folder = new Folder($skel); $Folder = new Folder($skel);
if (!empty($this->params['empty'])) {
$skip = array();
}
if ($Folder->copy(array('to' => $path, 'skip' => $skip))) { if ($Folder->copy(array('to' => $path, 'skip' => $skip))) {
$this->hr(); $this->hr();
$this->out(sprintf(__("Created: %s in %s", true), $app, $path)); $this->out(sprintf(__("Created: %s in %s", true), $app, $path));
@ -224,7 +227,8 @@ class ProjectTask extends Shell {
$File =& new File($path . 'webroot' . DS . 'index.php'); $File =& new File($path . 'webroot' . DS . 'index.php');
$contents = $File->read(); $contents = $File->read();
if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) {
$result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '" . CAKE_CORE_INCLUDE_PATH . "');", $contents); $root = strpos(CAKE_CORE_INCLUDE_PATH, '/') === 0 ? " DS . '" : "'";
$result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', " . $root . str_replace(DS, "' . DS . '", trim(CAKE_CORE_INCLUDE_PATH, DS)) . "');", $contents);
if (!$File->write($result)) { if (!$File->write($result)) {
return false; return false;
} }
@ -235,7 +239,7 @@ class ProjectTask extends Shell {
$File =& new File($path . 'webroot' . DS . 'test.php'); $File =& new File($path . 'webroot' . DS . 'test.php');
$contents = $File->read(); $contents = $File->read();
if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) {
$result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '" . CAKE_CORE_INCLUDE_PATH . "');", $contents); $result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', " . $root . str_replace(DS, "' . DS . '", trim(CAKE_CORE_INCLUDE_PATH, DS)) . "');", $contents);
if (!$File->write($result)) { if (!$File->write($result)) {
return false; return false;
} }
@ -280,30 +284,39 @@ class ProjectTask extends Shell {
$admin = ''; $admin = '';
$prefixes = Configure::read('Routing.prefixes'); $prefixes = Configure::read('Routing.prefixes');
if (!empty($prefixes)) { if (!empty($prefixes)) {
if ($this->interactive) {
$this->out();
$this->out(__('You have more than one routing prefix configured', true));
}
if (count($prefixes) == 1) { if (count($prefixes) == 1) {
return $prefixes[0] . '_'; return $prefixes[0] . '_';
} }
$options = array(); $options = array();
foreach ($prefixes as $i => $prefix) { foreach ($prefixes as $i => $prefix) {
$options[] = $i + 1; $options[] = $i + 1;
$this->out($i + 1 . '. ' . $prefix); if ($this->interactive) {
$this->out($i + 1 . '. ' . $prefix);
}
} }
$selection = $this->in(__('Please choose a prefix to bake with.', true), $options, 1); $selection = $this->in(__('Please choose a prefix to bake with.', true), $options, 1);
return $prefixes[$selection - 1] . '_'; return $prefixes[$selection - 1] . '_';
} }
if ($this->interactive) {
$this->out('You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/config/core.php to use prefix routing.'); $this->hr();
$this->out(__('What would you like the prefix route to be?', true));
$this->out(__('Example: www.example.com/admin/controller', true));
while ($admin == '') {
$admin = $this->in(__("What would you like the prefix route to be?", true), null, 'admin');
}
if ($this->cakeAdmin($admin) !== true) {
$this->out(__('Unable to write to /app/config/core.php.', true));
$this->out('You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/config/core.php to use prefix routing.'); $this->out('You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/config/core.php to use prefix routing.');
$this->_stop(); $this->out(__('What would you like the prefix route to be?', true));
$this->out(__('Example: www.example.com/admin/controller', true));
while ($admin == '') {
$admin = $this->in(__("Enter a routing prefix:", true), null, 'admin');
}
if ($this->cakeAdmin($admin) !== true) {
$this->out(__('Unable to write to /app/config/core.php.', true));
$this->out('You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/config/core.php to use prefix routing.');
$this->_stop();
}
return $admin . '_';
} }
return $admin . '_'; return '';
} }
/** /**

View file

@ -23,7 +23,7 @@ class TemplateTask extends Shell {
* variables to add to template scope * variables to add to template scope
* *
* @var array * @var array
**/ */
var $templateVars = array(); var $templateVars = array();
/** /**
@ -31,7 +31,7 @@ class TemplateTask extends Shell {
* Contains a list of $theme => $path * Contains a list of $theme => $path
* *
* @var array * @var array
**/ */
var $templatePaths = array(); var $templatePaths = array();
/** /**
@ -39,7 +39,7 @@ class TemplateTask extends Shell {
* *
* @access public * @access public
* @return void * @return void
**/ */
function initialize() { function initialize() {
$this->templatePaths = $this->_findThemes(); $this->templatePaths = $this->_findThemes();
} }
@ -50,7 +50,7 @@ class TemplateTask extends Shell {
* Bake themes are directories not named `skel` inside a `vendors/shells/templates` path. * Bake themes are directories not named `skel` inside a `vendors/shells/templates` path.
* *
* @return array Array of bake themes that are installed. * @return array Array of bake themes that are installed.
**/ */
function _findThemes() { function _findThemes() {
$paths = App::path('shells'); $paths = App::path('shells');
$core = array_pop($paths); $core = array_pop($paths);
@ -128,7 +128,7 @@ class TemplateTask extends Shell {
* @param string $vars Additional vars to set to template scope. * @param string $vars Additional vars to set to template scope.
* @access public * @access public
* @return contents of generated code template * @return contents of generated code template
**/ */
function generate($directory, $filename, $vars = null) { function generate($directory, $filename, $vars = null) {
if ($vars !== null) { if ($vars !== null) {
$this->set($vars); $this->set($vars);
@ -156,7 +156,7 @@ class TemplateTask extends Shell {
* If there is more than one installed theme user interaction will happen * If there is more than one installed theme user interaction will happen
* *
* @return string returns the path to the selected theme. * @return string returns the path to the selected theme.
**/ */
function getThemePath() { function getThemePath() {
if (count($this->templatePaths) == 1) { if (count($this->templatePaths) == 1) {
$paths = array_values($this->templatePaths); $paths = array_values($this->templatePaths);
@ -193,7 +193,7 @@ class TemplateTask extends Shell {
* @param string $filename lower_case_underscored filename you want. * @param string $filename lower_case_underscored filename you want.
* @access public * @access public
* @return string filename will exit program if template is not found. * @return string filename will exit program if template is not found.
**/ */
function _findTemplate($path, $directory, $filename) { function _findTemplate($path, $directory, $filename) {
$themeFile = $path . $directory . DS . $filename . '.ctp'; $themeFile = $path . $directory . DS . $filename . '.ctp';
if (file_exists($themeFile)) { if (file_exists($themeFile)) {

View file

@ -46,28 +46,28 @@ class TestTask extends Shell {
* Tasks used. * Tasks used.
* *
* @var array * @var array
**/ */
var $tasks = array('Template'); var $tasks = array('Template');
/** /**
* class types that methods can be generated for * class types that methods can be generated for
* *
* @var array * @var array
**/ */
var $classTypes = array('Model', 'Controller', 'Component', 'Behavior', 'Helper'); var $classTypes = array('Model', 'Controller', 'Component', 'Behavior', 'Helper');
/** /**
* Internal list of fixtures that have been added so far. * Internal list of fixtures that have been added so far.
* *
* @var string * @var string
**/ */
var $_fixtures = array(); var $_fixtures = array();
/** /**
* Flag for interactive mode * Flag for interactive mode
* *
* @var boolean * @var boolean
**/ */
var $interactive = false; var $interactive = false;
/** /**
@ -164,7 +164,7 @@ class TestTask extends Shell {
* Interact with the user and get their chosen type. Can exit the script. * Interact with the user and get their chosen type. Can exit the script.
* *
* @return string Users chosen type. * @return string Users chosen type.
**/ */
function getObjectType() { function getObjectType() {
$this->hr(); $this->hr();
$this->out(__("Select an object type:", true)); $this->out(__("Select an object type:", true));
@ -188,7 +188,7 @@ class TestTask extends Shell {
* *
* @param string $objectType Type of object to list classes for i.e. Model, Controller. * @param string $objectType Type of object to list classes for i.e. Model, Controller.
* @return string Class name the user chose. * @return string Class name the user chose.
**/ */
function getClassName($objectType) { function getClassName($objectType) {
$options = App::objects(strtolower($objectType)); $options = App::objects(strtolower($objectType));
$this->out(sprintf(__('Choose a %s class', true), $objectType)); $this->out(sprintf(__('Choose a %s class', true), $objectType));
@ -209,7 +209,7 @@ class TestTask extends Shell {
* Currently only model, and controller are supported * Currently only model, and controller are supported
* *
* @return boolean * @return boolean
**/ */
function typeCanDetectFixtures($type) { function typeCanDetectFixtures($type) {
$type = strtolower($type); $type = strtolower($type);
return ($type == 'controller' || $type == 'model'); return ($type == 'controller' || $type == 'model');
@ -219,7 +219,7 @@ class TestTask extends Shell {
* Check if a class with the given type is loaded or can be loaded. * Check if a class with the given type is loaded or can be loaded.
* *
* @return boolean * @return boolean
**/ */
function isLoadableClass($type, $class) { function isLoadableClass($type, $class) {
return App::import($type, $class); return App::import($type, $class);
} }
@ -229,7 +229,7 @@ class TestTask extends Shell {
* So that fixtures can be detected * So that fixtures can be detected
* *
* @return object * @return object
**/ */
function &buildTestSubject($type, $class) { function &buildTestSubject($type, $class) {
ClassRegistry::flush(); ClassRegistry::flush();
App::import($type, $class); App::import($type, $class);
@ -246,7 +246,7 @@ class TestTask extends Shell {
* Gets the real class name from the cake short form. * Gets the real class name from the cake short form.
* *
* @return string Real classname * @return string Real classname
**/ */
function getRealClassName($type, $class) { function getRealClassName($type, $class) {
if (strtolower($type) == 'model') { if (strtolower($type) == 'model') {
return $class; return $class;
@ -260,7 +260,7 @@ class TestTask extends Shell {
* *
* @param string $className Name of class to look at. * @param string $className Name of class to look at.
* @return array Array of method names. * @return array Array of method names.
**/ */
function getTestableMethods($className) { function getTestableMethods($className) {
$classMethods = get_class_methods($className); $classMethods = get_class_methods($className);
$parentMethods = get_class_methods(get_parent_class($className)); $parentMethods = get_class_methods(get_parent_class($className));
@ -280,7 +280,7 @@ class TestTask extends Shell {
* *
* @param object The object you want to generate fixtures for. * @param object The object you want to generate fixtures for.
* @return array Array of fixtures to be included in the test. * @return array Array of fixtures to be included in the test.
**/ */
function generateFixtureList(&$subject) { function generateFixtureList(&$subject) {
$this->_fixtures = array(); $this->_fixtures = array();
if (is_a($subject, 'Model')) { if (is_a($subject, 'Model')) {
@ -297,7 +297,7 @@ class TestTask extends Shell {
* *
* @return void * @return void
* @access protected * @access protected
**/ */
function _processModel(&$subject) { function _processModel(&$subject) {
$this->_addFixture($subject->name); $this->_addFixture($subject->name);
$associated = $subject->getAssociated(); $associated = $subject->getAssociated();
@ -321,7 +321,7 @@ class TestTask extends Shell {
* *
* @return void * @return void
* @access protected * @access protected
**/ */
function _processController(&$subject) { function _processController(&$subject) {
$subject->constructClasses(); $subject->constructClasses();
$models = array(Inflector::classify($subject->name)); $models = array(Inflector::classify($subject->name));
@ -339,7 +339,7 @@ class TestTask extends Shell {
* *
* @return void * @return void
* @access protected * @access protected
**/ */
function _addFixture($name) { function _addFixture($name) {
$parent = get_parent_class($name); $parent = get_parent_class($name);
$prefix = 'app.'; $prefix = 'app.';
@ -355,7 +355,7 @@ class TestTask extends Shell {
* Interact with the user to get additional fixtures they want to use. * Interact with the user to get additional fixtures they want to use.
* *
* @return void * @return void
**/ */
function getUserFixtures() { function getUserFixtures() {
$proceed = $this->in(__('Bake could not detect fixtures, would you like to add some?', true), array('y','n'), 'n'); $proceed = $this->in(__('Bake could not detect fixtures, would you like to add some?', true), array('y','n'), 'n');
$fixtures = array(); $fixtures = array();
@ -373,7 +373,7 @@ class TestTask extends Shell {
* Controllers require a mock class. * Controllers require a mock class.
* *
* @return boolean * @return boolean
**/ */
function hasMockClass($type) { function hasMockClass($type) {
$type = strtolower($type); $type = strtolower($type);
return $type == 'controller'; return $type == 'controller';
@ -383,7 +383,7 @@ class TestTask extends Shell {
* Generate a constructor code snippet for the type and classname * Generate a constructor code snippet for the type and classname
* *
* @return string Constructor snippet for the thing you are building. * @return string Constructor snippet for the thing you are building.
**/ */
function generateConstructor($type, $fullClassName) { function generateConstructor($type, $fullClassName) {
$type = strtolower($type); $type = strtolower($type);
if ($type == 'model') { if ($type == 'model') {
@ -401,7 +401,7 @@ class TestTask extends Shell {
* and get the plugin path if needed. * and get the plugin path if needed.
* *
* @return string filename the test should be created on * @return string filename the test should be created on
**/ */
function testCaseFileName($type, $className) { function testCaseFileName($type, $className) {
$path = $this->path; $path = $this->path;
if (isset($this->plugin)) { if (isset($this->plugin)) {
@ -418,7 +418,7 @@ class TestTask extends Shell {
* Show help file. * Show help file.
* *
* @return void * @return void
**/ */
function help() { function help() {
$this->hr(); $this->hr();
$this->out("Usage: cake bake test <type> <class>"); $this->out("Usage: cake bake test <type> <class>");

View file

@ -112,6 +112,7 @@ class ViewTask extends Shell {
$this->controllerName = Inflector::camelize($this->args[0]); $this->controllerName = Inflector::camelize($this->args[0]);
$this->controllerPath = Inflector::underscore($this->controllerName); $this->controllerPath = Inflector::underscore($this->controllerName);
$this->Project->interactive = false;
if (strtolower($this->args[0]) == 'all') { if (strtolower($this->args[0]) == 'all') {
return $this->all(); return $this->all();
} }
@ -144,7 +145,7 @@ class ViewTask extends Shell {
* Get a list of actions that can / should have views baked for them. * Get a list of actions that can / should have views baked for them.
* *
* @return array Array of action names that should be baked * @return array Array of action names that should be baked
**/ */
function _methodsToBake() { function _methodsToBake() {
$methods = array_diff( $methods = array_diff(
array_map('strtolower', get_class_methods($this->controllerName . 'Controller')), array_map('strtolower', get_class_methods($this->controllerName . 'Controller')),
@ -176,7 +177,7 @@ class ViewTask extends Shell {
* Bake All views for All controllers. * Bake All views for All controllers.
* *
* @return void * @return void
**/ */
function all() { function all() {
$this->Controller->interactive = false; $this->Controller->interactive = false;
$tables = $this->Controller->listAll($this->connection, false); $tables = $this->Controller->listAll($this->connection, false);
@ -308,7 +309,7 @@ class ViewTask extends Shell {
* *
* @param array $actions Array of actions to make files for. * @param array $actions Array of actions to make files for.
* @return void * @return void
**/ */
function bakeActions($actions, $vars) { function bakeActions($actions, $vars) {
foreach ($actions as $action) { foreach ($actions as $action) {
$content = $this->getContent($action, $vars); $content = $this->getContent($action, $vars);
@ -320,7 +321,7 @@ class ViewTask extends Shell {
* handle creation of baking a custom action view file * handle creation of baking a custom action view file
* *
* @return void * @return void
**/ */
function customAction() { function customAction() {
$action = ''; $action = '';
while ($action == '') { while ($action == '') {
@ -460,7 +461,7 @@ class ViewTask extends Shell {
* @return array $associations * @return array $associations
* @access private * @access private
*/ */
function __associations($model) { function __associations(&$model) {
$keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
$associations = array(); $associations = array();

View file

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

View file

View file

@ -20,15 +20,15 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!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"> <html xmlns="http://www.w3.org/1999/xhtml">
<head> <head>
<?php echo $html->charset(); ?> <?php echo $this->Html->charset(); ?>
<title> <title>
<?php __('CakePHP: the rapid development php framework:'); ?> <?php __('CakePHP: the rapid development php framework:'); ?>
<?php echo $title_for_layout; ?> <?php echo $title_for_layout; ?>
</title> </title>
<?php <?php
echo $html->meta('icon'); echo $this->Html->meta('icon');
echo $html->css('cake.generic'); echo $this->Html->css('cake.generic');
echo $scripts_for_layout; echo $scripts_for_layout;
?> ?>
@ -36,18 +36,18 @@
<body> <body>
<div id="container"> <div id="container">
<div id="header"> <div id="header">
<h1><?php echo $html->link(__('CakePHP: the rapid development php framework', true), 'http://cakephp.org'); ?></h1> <h1><?php echo $this->Html->link(__('CakePHP: the rapid development php framework', true), 'http://cakephp.org'); ?></h1>
</div> </div>
<div id="content"> <div id="content">
<?php $session->flash(); ?> <?php echo $this->Session->flash(); ?>
<?php echo $content_for_layout; ?> <?php echo $content_for_layout; ?>
</div> </div>
<div id="footer"> <div id="footer">
<?php echo $html->link( <?php echo $this->Html->link(
$html->image('cake.power.gif', array('alt'=>__("CakePHP: the rapid development php framework", true), 'border'=>"0")), $this->Html->image('cake.power.gif', array('alt'=> __('CakePHP: the rapid development php framework', true), 'border' => '0')),
'http://www.cakephp.org/', 'http://www.cakephp.org/',
array('target' => '_blank', 'escape' => false) array('target' => '_blank', 'escape' => false)
); );

View file

@ -280,7 +280,7 @@ class Dispatcher extends Object {
$params['form']['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE'); $params['form']['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
} }
if (isset($params['form']['_method'])) { if (isset($params['form']['_method'])) {
if (isset($_SERVER) && !empty($_SERVER)) { if (!empty($_SERVER)) {
$_SERVER['REQUEST_METHOD'] = $params['form']['_method']; $_SERVER['REQUEST_METHOD'] = $params['form']['_method'];
} else { } else {
$_ENV['REQUEST_METHOD'] = $params['form']['_method']; $_ENV['REQUEST_METHOD'] = $params['form']['_method'];
@ -614,15 +614,19 @@ class Dispatcher extends Object {
$this->_stop(); $this->_stop();
} }
$isAsset = false; $isAsset = false;
$assets = array('js' => 'text/javascript', 'css' => 'text/css', 'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'png' => 'image/png'); $assets = array(
'js' => 'text/javascript', 'css' => 'text/css',
'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'png' => 'image/png'
);
$ext = array_pop(explode('.', $url)); $ext = array_pop(explode('.', $url));
foreach ($assets as $type => $contentType) { foreach ($assets as $type => $contentType) {
if ($type === $ext) { if ($type === $ext) {
if ($type === 'css' || $type === 'js') { $parts = explode('/', $url);
$pos = strpos($url, $type . '/'); if ($parts[0] === 'css' || $parts[0] === 'js' || $parts[0] === 'img') {
$pos = 0;
} else { } else {
$pos = strpos($url, 'img/'); $pos = strlen($parts[0]);
} }
$isAsset = true; $isAsset = true;
break; break;
@ -640,7 +644,7 @@ class Dispatcher extends Object {
$paths = array(); $paths = array();
if ($pos > 0) { if ($pos > 0) {
$plugin = substr($url, 0, $pos - 1); $plugin = substr($url, 0, $pos);
$url = preg_replace('/^' . preg_quote($plugin, '/') . '\//i', '', $url); $url = preg_replace('/^' . preg_quote($plugin, '/') . '\//i', '', $url);
$paths[] = App::pluginPath($plugin) . 'vendors' . DS; $paths[] = App::pluginPath($plugin) . 'vendors' . DS;
} }

View file

@ -25,18 +25,12 @@
* @package cake * @package cake
* @subpackage cake.cake.libs * @subpackage cake.cake.libs
*/ */
class Cache extends Object { class Cache {
/**
* Cache engine to use
*
* @var CacheEngine
* @access protected
*/
var $_Engine = null;
/** /**
* Cache configuration stack * Cache configuration stack
* Keeps the permanent/default settings for each cache engine.
* These settings are used to reset the engines after temporary modification.
* *
* @var array * @var array
* @access private * @access private
@ -44,7 +38,7 @@ class Cache extends Object {
var $__config = array(); var $__config = array();
/** /**
* Holds name of the current configuration being used * Holds name of the current configuration name being used.
* *
* @var array * @var array
* @access private * @access private
@ -52,13 +46,20 @@ class Cache extends Object {
var $__name = 'default'; var $__name = 'default';
/** /**
* whether to reset the settings with the next call to self::set(); * Whether to reset the settings with the next call to Cache::set();
* *
* @var array * @var array
* @access private * @access private
*/ */
var $__reset = false; var $__reset = false;
/**
* Engine instances keyed by configuration name.
*
* @var array
*/
var $_engines = array();
/** /**
* Returns a singleton instance * Returns a singleton instance
* *
@ -75,21 +76,18 @@ class Cache extends Object {
} }
/** /**
* Tries to find and include a file for a cache engine and returns object instance * Set the cache configuration to use. config() can
* both create new configurations, return the settings for already configured
* configurations. It also sets the 'default' configuration to use for subsequent
* operations.
* *
* @param $name Name of the engine (without 'Engine') * To create a new configuration:
* @return mixed $engine object or null *
* @access private * `Cache::config('my_config', array('engine' => 'File', 'path' => TMP));`
*/ *
function __loadEngine($name) { * To get the settings for a configuration, and set it as the currently selected configuration
if (!class_exists($name . 'Engine')) { *
require LIBS . DS . 'cache' . DS . strtolower($name) . '.php'; * `Cache::config('default');`
}
return true;
}
/**
* Set the cache configuration to use
* *
* @see app/config/core.php for configuration settings * @see app/config/core.php for configuration settings
* @param string $name Name of the configuration * @param string $name Name of the configuration
@ -99,72 +97,113 @@ class Cache extends Object {
* @static * @static
*/ */
function config($name = null, $settings = array()) { function config($name = null, $settings = array()) {
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
if (is_array($name)) { if (is_array($name)) {
$settings = $name; $settings = $name;
} }
if ($name === null || !is_string($name)) { if ($name === null || !is_string($name)) {
$name = $_this->__name; $name = $self->__name;
} }
$current = array(); $current = array();
if (isset($_this->__config[$name])) { if (isset($self->__config[$name])) {
$current = $_this->__config[$name]; $current = $self->__config[$name];
} }
if (!empty($settings)) { if (!empty($settings)) {
$_this->__name = null; $self->__config[$name] = array_merge($current, $settings);
$_this->__config[$name] = array_merge($current, $settings);
} }
if (empty($_this->__config[$name]['engine'])) { if (empty($self->__config[$name]['engine'])) {
return false; return false;
} }
$_this->__name = $name; $self->__name = $name;
$engine = $_this->__config[$name]['engine']; $engine = $self->__config[$name]['engine'];
if (!$_this->isInitialized($engine)) { if (!isset($self->_engines[$name])) {
if ($_this->engine($engine, $_this->__config[$name]) === false) { $self->_buildEngine($name);
return false; $settings = $self->__config[$name] = $self->settings($name);
} } elseif ($settings = $self->set($self->__config[$name])) {
$settings = $_this->__config[$name] = $_this->settings($engine); $self->__config[$name] = $settings;
} else if ($settings = $_this->set($_this->__config[$name])) {
$_this->__config[$name] = $settings;
} }
return compact('engine', 'settings'); return compact('engine', 'settings');
} }
/** /**
* Set the cache engine to use or modify settings for one instance * Finds and builds the instance of the required engine class.
* *
* @param string $name Name of the engine (without 'Engine') * @param string $name Name of the config array that needs an engine instance built
* @param array $settings Optional associative array of settings passed to the engine * @return void
* @return boolean True on success, false on failure * @access protected
* @access public
* @static
*/ */
function engine($name = 'File', $settings = array()) { function _buildEngine($name) {
$cacheClass = $name . 'Engine'; $config = $this->__config[$name];
$_this =& Cache::getInstance();
if (!isset($_this->_Engine[$name])) {
if ($_this->__loadEngine($name) === false) {
return false;
}
$_this->_Engine[$name] =& new $cacheClass();
}
if ($_this->_Engine[$name]->init($settings)) { list($plugin, $class) = pluginSplit($config['engine']);
if (time() % $_this->_Engine[$name]->settings['probability'] === 0) { $cacheClass = $class . 'Engine';
$_this->_Engine[$name]->gc(); if (!class_exists($cacheClass) && $this->__loadEngine($class, $plugin) === false) {
return false;
}
$cacheClass = $class . 'Engine';
$this->_engines[$name] =& new $cacheClass();
if ($this->_engines[$name]->init($config)) {
if (time() % $this->_engines[$name]->settings['probability'] === 0) {
$this->_engines[$name]->gc();
} }
return true; return true;
} }
$_this->_Engine[$name] = null;
return false; return false;
} }
/**
* Returns an array containing the currently configured Cache settings.
*
* @return array
*/
function configured() {
$self = Cache::getInstance();
return array_keys($self->__config);
}
/**
* Drops a cache engine. Deletes the cache configuration information
* If the deleted configuration is the last configuration using an certain engine,
* the Engine instance is also unset.
*
* @param string $name A currently configured cache config you wish to remove.
* @return boolen success of the removal, returns false when the config does not exist.
*/
function drop($name) {
$self = Cache::getInstance();
if (!isset($self->__config[$name])) {
return false;
}
unset($self->__config[$name]);
unset($self->_engines[$name]);
return true;
}
/**
* Tries to find and include a file for a cache engine and returns object instance
*
* @param $name Name of the engine (without 'Engine')
* @return mixed $engine object or null
* @access private
*/
function __loadEngine($name, $plugin = null) {
if ($plugin) {
return App::import('Lib', $plugin . '.cache' . DS . $name, false);
} else {
$app = App::import('Lib', 'cache' . DS . $name, false);
if (!$app) {
require LIBS . 'cache' . DS . strtolower($name) . '.php';
}
return true;
}
}
/** /**
* Temporarily change settings to current config options. if no params are passed, resets settings if needed * Temporarily change settings to current config options. if no params are passed, resets settings if needed
* Cache::write() will reset the configuration changes made * Cache::write() will reset the configuration changes made
@ -176,30 +215,32 @@ class Cache extends Object {
* @static * @static
*/ */
function set($settings = array(), $value = null) { function set($settings = array(), $value = null) {
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
if (!isset($_this->__config[$_this->__name])) { if (!isset($self->__config[$self->__name])) {
return false; return false;
} }
$engine = $_this->__config[$_this->__name]['engine']; $name = $self->__name;
if (!empty($settings)) { if (!empty($settings)) {
$_this->__reset = true; $self->__reset = true;
} }
if ($_this->__reset === true) { if ($self->__reset === true) {
if (empty($settings)) { if (empty($settings)) {
$_this->__reset = false; $self->__reset = false;
$settings = $_this->__config[$_this->__name]; $settings = $self->__config[$name];
} else { } else {
if (is_string($settings) && $value !== null) { if (is_string($settings) && $value !== null) {
$settings = array($settings => $value); $settings = array($settings => $value);
} }
$settings = array_merge($_this->__config[$_this->__name], $settings); $settings = array_merge($self->__config[$self->__name], $settings);
if (isset($settings['duration']) && !is_numeric($settings['duration'])) {
$settings['duration'] = strtotime($settings['duration']) - time();
}
} }
$_this->engine($engine, $settings); $self->_engines[$name]->settings = $settings;
} }
return $self->settings($name);
return $_this->settings($engine);
} }
/** /**
@ -212,9 +253,8 @@ class Cache extends Object {
* @static * @static
*/ */
function gc() { function gc() {
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
$config = $_this->config(); $self->_engines[$self->__name]->gc();
$_this->_Engine[$config['engine']]->gc();
} }
/** /**
@ -228,43 +268,27 @@ class Cache extends Object {
* @static * @static
*/ */
function write($key, $value, $config = null) { function write($key, $value, $config = null) {
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
if (is_array($config)) { if (!$config) {
extract($config); $config = $self->__name;
} else if ($config && (is_numeric($config) || is_numeric($config[0]) || (isset($config[1]) && is_numeric($config[1])))) {
$config = null;
}
if ($config && isset($_this->__config[$config])) {
$settings = $_this->set($_this->__config[$config]);
} else {
$settings = $_this->settings();
} }
$settings = $self->settings($config);
if (empty($settings)) { if (empty($settings)) {
return null; return null;
} }
extract($settings); if (!$self->isInitialized($config)) {
return false;
}
$key = $self->_engines[$config]->key($key);
if (!$_this->isInitialized($engine)) { if (!$key || is_resource($value) || $settings['duration'] < 1) {
return false; return false;
} }
if (!$key = $_this->_Engine[$engine]->key($key)) { $success = $self->_engines[$config]->write($settings['prefix'] . $key, $value, $settings['duration']);
return false; $self->set();
}
if (is_resource($value)) {
return false;
}
if ($duration < 1) {
return false;
}
$success = $_this->_Engine[$engine]->write($settings['prefix'] . $key, $value, $duration);
$settings = $_this->set();
return $success; return $success;
} }
@ -278,29 +302,27 @@ class Cache extends Object {
* @static * @static
*/ */
function read($key, $config = null) { function read($key, $config = null) {
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
if (isset($_this->__config[$config])) { if (!$config) {
$settings = $_this->set($_this->__config[$config]); $config = $self->__name;
} else {
$settings = $_this->settings();
} }
$settings = $self->settings($config);
if (empty($settings)) { if (empty($settings)) {
return null; return null;
} }
extract($settings); if (!$self->isInitialized($config)) {
if (!$_this->isInitialized($engine)) {
return false; return false;
} }
if (!$key = $_this->_Engine[$engine]->key($key)) { $key = $self->_engines[$config]->key($key);
if (!$key) {
return false; return false;
} }
$success = $_this->_Engine[$engine]->read($settings['prefix'] . $key); $success = $self->_engines[$config]->read($settings['prefix'] . $key);
if ($config !== null && $config !== $_this->__name) { if ($config !== null && $config !== $self->__name) {
$settings = $_this->set(); $self->set();
} }
return $success; return $success;
} }
@ -315,28 +337,25 @@ class Cache extends Object {
* @static * @static
*/ */
function delete($key, $config = null) { function delete($key, $config = null) {
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
if (isset($_this->__config[$config])) { if (!$config) {
$settings = $_this->set($_this->__config[$config]); $config = $self->__name;
} else {
$settings = $_this->settings();
} }
$settings = $self->settings($config);
if (empty($settings)) { if (empty($settings)) {
return null; return null;
} }
extract($settings); if (!$self->isInitialized($config)) {
return false;
if (!$_this->isInitialized($engine)) { }
$key = $self->_engines[$config]->key($key);
if (!$key) {
return false; return false;
} }
if (!$key = $_this->_Engine[$engine]->key($key)) { $success = $self->_engines[$config]->delete($settings['prefix'] . $key);
return false; $self->set();
}
$success = $_this->_Engine[$engine]->delete($settings['prefix'] . $key);
$settings = $_this->set();
return $success; return $success;
} }
@ -350,28 +369,26 @@ class Cache extends Object {
* @static * @static
*/ */
function clear($check = false, $config = null) { function clear($check = false, $config = null) {
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
if (isset($_this->__config[$config])) { if (!$config) {
$settings = $_this->set($_this->__config[$config]); $config = $self->__name;
} else {
$settings = $_this->settings();
} }
$settings = $self->settings($config);
if (empty($settings)) { if (empty($settings)) {
return null; return null;
} }
extract($settings);
if (isset($engine) && !$_this->isInitialized($engine)) { if (!$self->isInitialized($config)) {
return false; return false;
} }
$success = $_this->_Engine[$engine]->clear($check); $success = $self->_engines[$config]->clear($check);
$settings = $_this->set(); $self->set();
return $success; return $success;
} }
/** /**
* Check if Cache has initialized a working storage engine * Check if Cache has initialized a working config for the given name.
* *
* @param string $engine Name of the engine * @param string $engine Name of the engine
* @param string $config Name of the configuration setting * @param string $config Name of the configuration setting
@ -379,33 +396,35 @@ class Cache extends Object {
* @access public * @access public
* @static * @static
*/ */
function isInitialized($engine = null) { function isInitialized($name = null) {
if (Configure::read('Cache.disable')) { if (Configure::read('Cache.disable')) {
return false; return false;
} }
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
if (!$engine && isset($_this->__config[$_this->__name]['engine'])) { if (!$name && isset($self->__config[$self->__name])) {
$engine = $_this->__config[$_this->__name]['engine']; $name = $self->__name;
} }
return isset($_this->_Engine[$engine]); return isset($self->_engines[$name]);
} }
/** /**
* Return the settings for current cache engine * Return the settings for current cache engine. If no name is supplied the settings
* for the 'active default' configuration will be returned. To set the 'active default'
* configuration use `Cache::config()`
* *
* @param string $engine Name of the engine * @param string $engine Name of the configuration to get settings for.
* @return array list of settings for this engine * @return array list of settings for this engine
* @see Cache::config()
* @access public * @access public
* @static * @static
*/ */
function settings($engine = null) { function settings($name = null) {
$_this =& Cache::getInstance(); $self =& Cache::getInstance();
if (!$engine && isset($_this->__config[$_this->__name]['engine'])) { if (!$name && isset($self->__config[$self->__name])) {
$engine = $_this->__config[$_this->__name]['engine']; $name = $self->__name;
} }
if (!empty($self->_engines[$name])) {
if (isset($_this->_Engine[$engine]) && !is_null($_this->_Engine[$engine])) { return $self->_engines[$name]->settings();
return $_this->_Engine[$engine]->settings();
} }
return array(); return array();
} }
@ -417,7 +436,7 @@ class Cache extends Object {
* @package cake * @package cake
* @subpackage cake.cake.libs * @subpackage cake.cake.libs
*/ */
class CacheEngine extends Object { class CacheEngine {
/** /**
* settings of current engine instance * settings of current engine instance
@ -428,7 +447,7 @@ class CacheEngine extends Object {
var $settings = array(); var $settings = array();
/** /**
* Iitialize the cache engine * Initialize the cache engine
* *
* Called automatically by the cache frontend * Called automatically by the cache frontend
* *

View file

@ -37,11 +37,12 @@ class FileEngine extends CacheEngine {
var $__File = null; var $__File = null;
/** /**
* settings * Settings
* path = absolute path to cache directory, default => CACHE *
* prefix = string prefix for filename, default => cake_ * - path = absolute path to cache directory, default => CACHE
* lock = enable file locking on write, default => false * - prefix = string prefix for filename, default => cake_
* serialize = serialize the data, default => true * - lock = enable file locking on write, default => false
* - serialize = serialize the data, default => true
* *
* @var array * @var array
* @see CacheEngine::__defaults * @see CacheEngine::__defaults

View file

@ -36,9 +36,11 @@ class MemcacheEngine extends CacheEngine {
var $__Memcache = null; var $__Memcache = null;
/** /**
* settings * Settings
* servers = string or array of memcache servers, default => 127.0.0.1 *
* compress = boolean, default => false * - servers = string or array of memcache servers, default => 127.0.0.1. If an
* array MemcacheEngine will use them as a pool.
* - compress = boolean, default => false
* *
* @var array * @var array
* @access public * @access public
@ -60,7 +62,10 @@ class MemcacheEngine extends CacheEngine {
return false; return false;
} }
parent::init(array_merge(array( parent::init(array_merge(array(
'engine'=> 'Memcache', 'prefix' => Inflector::slug(APP_DIR) . '_', 'servers' => array('127.0.0.1'), 'compress'=> false 'engine'=> 'Memcache',
'prefix' => Inflector::slug(APP_DIR) . '_',
'servers' => array('127.0.0.1'),
'compress'=> false
), $settings) ), $settings)
); );
@ -100,7 +105,7 @@ class MemcacheEngine extends CacheEngine {
*/ */
function write($key, &$value, $duration) { function write($key, &$value, $duration) {
$expires = time() + $duration; $expires = time() + $duration;
$this->__Memcache->set($key.'_expires', $expires, $this->settings['compress'], $expires); $this->__Memcache->set($key . '_expires', $expires, $this->settings['compress'], $expires);
return $this->__Memcache->set($key, $value, $this->settings['compress'], $expires); return $this->__Memcache->set($key, $value, $this->settings['compress'], $expires);
} }
@ -113,7 +118,7 @@ class MemcacheEngine extends CacheEngine {
*/ */
function read($key) { function read($key) {
$time = time(); $time = time();
$cachetime = intval($this->__Memcache->get($key.'_expires')); $cachetime = intval($this->__Memcache->get($key . '_expires'));
if ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime) { if ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime) {
return false; return false;
} }

View file

@ -2,7 +2,6 @@
/** /**
* Xcache storage engine for cache. * Xcache storage engine for cache.
* *
*
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
@ -29,9 +28,10 @@
class XcacheEngine extends CacheEngine { class XcacheEngine extends CacheEngine {
/** /**
* settings * Settings
* PHP_AUTH_USER = xcache.admin.user, default cake *
* PHP_AUTH_PW = xcache.admin.password, default cake * - PHP_AUTH_USER = xcache.admin.user, default cake
* - PHP_AUTH_PW = xcache.admin.password, default cake
* *
* @var array * @var array
* @access public * @access public
@ -67,7 +67,7 @@ class XcacheEngine extends CacheEngine {
*/ */
function write($key, &$value, $duration) { function write($key, &$value, $duration) {
$expires = time() + $duration; $expires = time() + $duration;
xcache_set($key.'_expires', $expires, $duration); xcache_set($key . '_expires', $expires, $duration);
return xcache_set($key, $value, $duration); return xcache_set($key, $value, $duration);
} }
@ -81,7 +81,7 @@ class XcacheEngine extends CacheEngine {
function read($key) { function read($key) {
if (xcache_isset($key)) { if (xcache_isset($key)) {
$time = time(); $time = time();
$cachetime = intval(xcache_get($key.'_expires')); $cachetime = intval(xcache_get($key . '_expires'));
if ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime) { if ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime) {
return false; return false;
} }

View file

@ -19,15 +19,6 @@
* @since CakePHP(tm) v 0.2.9 * @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php) * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/ */
/**
* Included libraries.
*
*/
if (!class_exists('File')) {
require LIBS . 'file.php';
}
/** /**
* Set up error level constants to be used within the framework if they are not defined within the * Set up error level constants to be used within the framework if they are not defined within the
* system. * system.
@ -60,7 +51,7 @@ class CakeLog {
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_streams = array(); var $_streams = array();
/** /**
@ -68,7 +59,7 @@ class CakeLog {
* *
* @return void * @return void
* @static * @static
**/ */
function &getInstance() { function &getInstance() {
static $instance = array(); static $instance = array();
if (!isset($instance[0])) { if (!isset($instance[0])) {
@ -85,7 +76,7 @@ class CakeLog {
* @param array $config Array of configuration information for the logger * @param array $config Array of configuration information for the logger
* @return boolean success of configuration. * @return boolean success of configuration.
* @static * @static
**/ */
function config($key, $config) { function config($key, $config) {
if (empty($config['engine'])) { if (empty($config['engine'])) {
trigger_error(__('Missing logger classname', true), E_USER_WARNING); trigger_error(__('Missing logger classname', true), E_USER_WARNING);
@ -107,12 +98,10 @@ class CakeLog {
* *
* @return mixed boolean false on any failures, string of classname to use if search was successful.\ * @return mixed boolean false on any failures, string of classname to use if search was successful.\
* @access protected * @access protected
**/ */
function _getLogger($loggerName) { function _getLogger($loggerName) {
$plugin = null; list($plugin, $loggerName) = pluginSplit($loggerName);
if (strpos($loggerName, '.') !== false) {
list($plugin, $loggerName) = explode('.', $loggerName);
}
if ($plugin) { if ($plugin) {
App::import('Lib', $plugin . '.log/' . $loggerName); App::import('Lib', $plugin . '.log/' . $loggerName);
} else { } else {
@ -139,46 +128,31 @@ class CakeLog {
* *
* @return array * @return array
* @static * @static
**/ */
function streams() { function configured() {
$self = CakeLog::getInstance(); $self = CakeLog::getInstance();
return array_keys($self->_streams); return array_keys($self->_streams);
} }
/** /**
* Remove a stream from the active streams. Once a stream has been removed * Removes a stream from the active streams. Once a stream has been removed
* it will no longer be called. * it will no longer have messages sent to it.
* *
* @param string $keyname Key name of callable to remove. * @param string $keyname Key name of callable to remove.
* @return void * @return void
* @static * @static
**/ */
function remove($streamName) { function drop($streamName) {
$self = CakeLog::getInstance(); $self = CakeLog::getInstance();
unset($self->_streams[$streamName]); unset($self->_streams[$streamName]);
} }
/**
* Add a stream the logger.
* Streams represent destinations for log messages. Each stream can connect to
* a different resource /interface and capture/write output to that source.
*
* @param string $key Keyname of config.
* @param array $config Array of config information for the LogStream
* @return boolean success
* @static
**/
function addStream($key, $config) {
$self = CakeLog::getInstance();
$self->_streams[$key] = $config;
}
/** /**
* Configures the automatic/default stream a FileLog. * Configures the automatic/default stream a FileLog.
* *
* @return void * @return void
* @access protected * @access protected
**/ */
function _autoConfig() { function _autoConfig() {
if (!class_exists('FileLog')) { if (!class_exists('FileLog')) {
App::import('Core', 'log/FileLog'); App::import('Core', 'log/FileLog');
@ -235,7 +209,7 @@ class CakeLog {
* @param integer $line Line that triggered the error * @param integer $line Line that triggered the error
* @param array $context Context * @param array $context Context
* @return void * @return void
**/ */
function handleError($code, $description, $file = null, $line = null, $context = null) { function handleError($code, $description, $file = null, $line = null, $context = null) {
if ($code === 2048 || $code === 8192) { if ($code === 2048 || $code === 8192) {
return; return;

View file

@ -212,11 +212,10 @@ class CakeSession extends Object {
* @access public * @access public
*/ */
function check($name) { function check($name) {
$var = $this->__validateKeys($name); if (empty($name)) {
if (empty($var)) {
return false; return false;
} }
$result = Set::extract($_SESSION, $var); $result = Set::classicExtract($_SESSION, $name);
return isset($result); return isset($result);
} }
@ -244,7 +243,7 @@ class CakeSession extends Object {
* *
* @return boolean * @return boolean
* @deprecated Use CakeSession::delete instead * @deprecated Use CakeSession::delete instead
**/ */
function del($name) { function del($name) {
trigger_error('CakeSession::del() is deprecated, use CakeSession::delete() instead.', E_USER_WARNING); trigger_error('CakeSession::del() is deprecated, use CakeSession::delete() instead.', E_USER_WARNING);
return $this->delete($name); return $this->delete($name);
@ -259,13 +258,11 @@ class CakeSession extends Object {
*/ */
function delete($name) { function delete($name) {
if ($this->check($name)) { if ($this->check($name)) {
if ($var = $this->__validateKeys($name)) { if (in_array($name, $this->watchKeys)) {
if (in_array($var, $this->watchKeys)) { trigger_error('Deleting session key {' . $name . '}', E_USER_NOTICE);
trigger_error('Deleting session key {' . $var . '}', E_USER_NOTICE);
}
$this->__overwrite($_SESSION, Set::remove($_SESSION, $var));
return ($this->check($var) == false);
} }
$this->__overwrite($_SESSION, Set::remove($_SESSION, $name));
return ($this->check($name) == false);
} }
$this->__setError(2, "$name doesn't exist"); $this->__setError(2, "$name doesn't exist");
return false; return false;
@ -354,7 +351,7 @@ class CakeSession extends Object {
if (empty($name)) { if (empty($name)) {
return false; return false;
} }
$result = Set::extract($_SESSION, $name); $result = Set::classicExtract($_SESSION, $name);
if (!is_null($result)) { if (!is_null($result)) {
return $result; return $result;
@ -385,7 +382,6 @@ class CakeSession extends Object {
* @access public * @access public
*/ */
function watch($var) { function watch($var) {
$var = $this->__validateKeys($var);
if (empty($var)) { if (empty($var)) {
return false; return false;
} }
@ -402,7 +398,6 @@ class CakeSession extends Object {
* @access public * @access public
*/ */
function ignore($var) { function ignore($var) {
$var = $this->__validateKeys($var);
if (!in_array($var, $this->watchKeys)) { if (!in_array($var, $this->watchKeys)) {
return; return;
} }
@ -424,16 +419,14 @@ class CakeSession extends Object {
* @access public * @access public
*/ */
function write($name, $value) { function write($name, $value) {
$var = $this->__validateKeys($name); if (empty($name)) {
if (empty($var)) {
return false; return false;
} }
if (in_array($var, $this->watchKeys)) { if (in_array($name, $this->watchKeys)) {
trigger_error('Writing session key {' . $var . '}: ' . Debugger::exportVar($value), E_USER_NOTICE); trigger_error('Writing session key {' . $name . '}: ' . Debugger::exportVar($value), E_USER_NOTICE);
} }
$this->__overwrite($_SESSION, Set::insert($_SESSION, $var, $value)); $this->__overwrite($_SESSION, Set::insert($_SESSION, $name, $value));
return (Set::extract($_SESSION, $var) === $value); return (Set::classicExtract($_SESSION, $name) === $value);
} }
/** /**
@ -676,22 +669,6 @@ class CakeSession extends Object {
$this->__regenerateId(); $this->__regenerateId();
} }
/**
* Validate that the $name is in correct dot notation
* example: $name = 'ControllerName.key';
*
* @param string $name Session key names as string.
* @return mixed false is $name is not correct format, or $name if it is correct
* @access private
*/
function __validateKeys($name) {
if (is_string($name) && preg_match("/^[ 0-9a-zA-Z._-]*$/", $name)) {
return $name;
}
$this->__setError(3, "$name is not a string");
return false;
}
/** /**
* Helper method to set an internal error message. * Helper method to set an internal error message.
* *

View file

@ -118,12 +118,12 @@ class ClassRegistry {
foreach ($objects as $key => $settings) { foreach ($objects as $key => $settings) {
if (is_array($settings)) { if (is_array($settings)) {
$plugin = $pluginPath = null; $pluginPath = null;
$settings = array_merge($defaults, $settings); $settings = array_merge($defaults, $settings);
$class = $settings['class']; $class = $settings['class'];
if (strpos($class, '.') !== false) { list($plugin, $class) = pluginSplit($class);
list($plugin, $class) = explode('.', $class); if ($plugin) {
$pluginPath = $plugin . '.'; $pluginPath = $plugin . '.';
} }

View file

@ -91,11 +91,21 @@ class Configure extends Object {
if (strpos($name, '.') === false) { if (strpos($name, '.') === false) {
$_this->{$name} = $value; $_this->{$name} = $value;
} else { } else {
$names = explode('.', $name, 2); $names = explode('.', $name, 4);
if (!isset($_this->{$names[0]})) { switch (count($names)) {
$_this->{$names[0]} = array(); case 2:
$_this->{$names[0]}[$names[1]] = $value;
break;
case 3:
$_this->{$names[0]}[$names[1]][$names[2]] = $value;
case 4:
$names = explode('.', $name, 2);
if (!isset($_this->{$names[0]})) {
$_this->{$names[0]} = array();
}
$_this->{$names[0]} = Set::insert($_this->{$names[0]}, $names[1], $value);
break;
} }
$_this->{$names[0]} = Set::insert($_this->{$names[0]}, $names[1], $value);
} }
} }
@ -130,12 +140,14 @@ class Configure extends Object {
/** /**
* Used to read information stored in the Configure instance. * Used to read information stored in the Configure instance.
* *
* Usage * Usage:
* {{{
* Configure::read('Name'); will return all values for Name * Configure::read('Name'); will return all values for Name
* Configure::read('Name.key'); will return only the value of Configure::Name[key] * Configure::read('Name.key'); will return only the value of Configure::Name[key]
* }}}
* *
* @link http://book.cakephp.org/view/413/read * @link http://book.cakephp.org/view/413/read
* @param string $var Variable to obtain * @param string $var Variable to obtain. Use '.' to access array elements.
* @return string value of Configure::$var * @return string value of Configure::$var
* @access public * @access public
*/ */
@ -147,28 +159,44 @@ class Configure extends Object {
} }
if (strpos($var, '.') !== false) { if (strpos($var, '.') !== false) {
$names = explode('.', $var, 2); $names = explode('.', $var, 3);
$var = $names[0]; $var = $names[0];
} }
if (!isset($_this->{$var})) { if (!isset($_this->{$var})) {
return null; return null;
} }
if (!isset($names[1])) {
if (!empty($names[1])) { return $_this->{$var};
return Set::extract($_this->{$var}, $names[1]);
} }
switch (count($names)) {
return $_this->{$var}; case 2:
if (isset($_this->{$var}[$names[1]])) {
return $_this->{$var}[$names[1]];
}
break;
case 3:
if (isset($_this->{$var}[$names[1]][$names[2]])) {
return $_this->{$var}[$names[1]][$names[2]];
}
if (!isset($_this->{$var}[$names[1]])) {
return null;
}
return Set::classicExtract($_this->{$var}[$names[1]], $names[2]);
break;
}
return null;
} }
/** /**
* Used to delete a variable from the Configure instance. * Used to delete a variable from the Configure instance.
* *
* Usage: * Usage:
* {{{
* Configure::delete('Name'); will delete the entire Configure::Name * Configure::delete('Name'); will delete the entire Configure::Name
* Configure::delete('Name.key'); will delete only the Configure::Name[key] * Configure::delete('Name.key'); will delete only the Configure::Name[key]
* }}}
* *
* @link http://book.cakephp.org/view/414/delete * @link http://book.cakephp.org/view/414/delete
* @param string $var the var to be deleted * @param string $var the var to be deleted
* @return void * @return void
* @access public * @access public
@ -188,21 +216,30 @@ class Configure extends Object {
/** /**
* Loads a file from app/config/configure_file.php. * Loads a file from app/config/configure_file.php.
* Config file variables should be formated like: * Config file variables should be formated like:
* $config['name'] = 'value'; * `$config['name'] = 'value';`
* These will be used to create dynamic Configure vars. * These will be used to create dynamic Configure vars. load() is also used to
* load stored config files created with Configure::store()
* *
* Usage Configure::load('configure_file'); * - To load config files from app/config use `Configure::load('configure_file');`.
* - To load config files from a plugin `Configure::load('plugin.configure_file');`.
* *
* @link http://book.cakephp.org/view/415/load * @link http://book.cakephp.org/view/415/load
* @param string $fileName name of file to load, extension must be .php and only the name * @param string $fileName name of file to load, extension must be .php and only the name
* should be used, not the extenstion * should be used, not the extenstion
* @return mixed false if file not found, void if load successful * @return mixed false if file not found, void if load successful
* @access public * @access public
*/ */
function load($fileName) { function load($fileName) {
$found = false; $found = $plugin = $pluginPath = false;
list($plugin, $fileName) = pluginSplit($fileName);
if ($plugin) {
$pluginPath = App::pluginPath($plugin);
}
if (file_exists(CONFIGS . $fileName . '.php')) { if ($pluginPath && file_exists($pluginPath . 'config' . DS . $fileName . '.php')) {
include($pluginPath . 'config' . DS . $fileName . '.php');
$found = true;
} elseif (file_exists(CONFIGS . $fileName . '.php')) {
include(CONFIGS . $fileName . '.php'); include(CONFIGS . $fileName . '.php');
$found = true; $found = true;
} elseif (file_exists(CACHE . 'persistent' . DS . $fileName . '.php')) { } elseif (file_exists(CACHE . 'persistent' . DS . $fileName . '.php')) {
@ -233,9 +270,9 @@ class Configure extends Object {
/** /**
* Used to determine the current version of CakePHP. * Used to determine the current version of CakePHP.
* *
* Usage Configure::version(); * Usage `Configure::version();`
* *
* @link http://book.cakephp.org/view/416/version * @link http://book.cakephp.org/view/416/version
* @return string Current version of CakePHP * @return string Current version of CakePHP
* @access public * @access public
*/ */
@ -252,9 +289,11 @@ class Configure extends Object {
/** /**
* Used to write a config file to disk. * Used to write a config file to disk.
* *
* Configure::store('Model', 'class.paths', array('Users' => array( * {{{
* Configure::store('Model', 'class_paths', array('Users' => array(
* 'path' => 'users', 'plugin' => true * 'path' => 'users', 'plugin' => true
* ))); * )));
* }}}
* *
* @param string $type Type of config file to write, ex: Models, Controllers, Helpers, Components * @param string $type Type of config file to write, ex: Models, Controllers, Helpers, Components
* @param string $name file name. * @param string $name file name.
@ -267,20 +306,7 @@ class Configure extends Object {
$content = ''; $content = '';
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$content .= "\$config['$type']['$key']"; $content .= "\$config['$type']['$key'] = " . var_export($value, true) . ";\n";
if (is_array($value)) {
$content .= " = array(";
foreach ($value as $key1 => $value2) {
$value2 = addslashes($value2);
$content .= "'$key1' => '$value2', ";
}
$content .= ");\n";
} else {
$value = addslashes($value);
$content .= " = '$value';\n";
}
} }
if (is_null($type)) { if (is_null($type)) {
$write = false; $write = false;
@ -367,10 +393,6 @@ class Configure extends Object {
trigger_error(sprintf(__("Can't find application core file. Please create %score.php, and make sure it is readable by PHP.", true), CONFIGS), E_USER_ERROR); trigger_error(sprintf(__("Can't find application core file. Please create %score.php, and make sure it is readable by PHP.", true), CONFIGS), E_USER_ERROR);
} }
if (!include(CONFIGS . 'bootstrap.php')) {
trigger_error(sprintf(__("Can't find application bootstrap file. Please create %sbootstrap.php, and make sure it is readable by PHP.", true), CONFIGS), E_USER_ERROR);
}
if (Configure::read('Cache.disable') !== true) { if (Configure::read('Cache.disable') !== true) {
$cache = Cache::config('default'); $cache = Cache::config('default');
@ -407,6 +429,11 @@ class Configure extends Object {
} }
Cache::config('default'); Cache::config('default');
} }
if (!include(CONFIGS . 'bootstrap.php')) {
trigger_error(sprintf(__("Can't find application bootstrap file. Please create %sbootstrap.php, and make sure it is readable by PHP.", true), CONFIGS), E_USER_ERROR);
}
if (App::path('controllers') == array()) { if (App::path('controllers') == array()) {
App::build(array( App::build(array(
'models' => $modelPaths, 'views' => $viewPaths, 'controllers' => $controllerPaths, 'models' => $modelPaths, 'views' => $viewPaths, 'controllers' => $controllerPaths,
@ -684,7 +711,7 @@ class App extends Object {
* *
* @param string $plugin CamelCased plugin name to find the path of. * @param string $plugin CamelCased plugin name to find the path of.
* @return string full path to the plugin. * @return string full path to the plugin.
**/ */
function pluginPath($plugin) { function pluginPath($plugin) {
$_this =& App::getInstance(); $_this =& App::getInstance();
$pluginDir = Inflector::underscore($plugin); $pluginDir = Inflector::underscore($plugin);
@ -1222,8 +1249,8 @@ class App extends Object {
/** /**
* Returns an array of filenames of PHP files in the given directory. * Returns an array of filenames of PHP files in the given directory.
* *
* @param string $path Path to scan for files * @param string $path Path to scan for files
* @param string $suffix if false, return only directories. if string, match and return files * @param string $suffix if false, return only directories. if string, match and return files
* @return array List of directories or files in directory * @return array List of directories or files in directory
*/ */
function __list($path, $suffix = false, $extension = false) { function __list($path, $suffix = false, $extension = false) {

View file

@ -56,7 +56,7 @@ class Component extends Object {
* *
* @var array * @var array
* @access private * @access private
**/ */
var $__settings = array(); var $__settings = array();
/** /**
@ -189,16 +189,8 @@ class Component extends Object {
$normal = Set::merge(array('Session' => null), $normal); $normal = Set::merge(array('Session' => null), $normal);
} }
foreach ((array)$normal as $component => $config) { foreach ((array)$normal as $component => $config) {
$plugin = null; $plugin = isset($this->__controllerVars['plugin']) ? $this->__controllerVars['plugin'] . '.' : null;
list($plugin, $component) = pluginSplit($component, true, $plugin);
if (isset($this->__controllerVars['plugin'])) {
$plugin = $this->__controllerVars['plugin'] . '.';
}
if (strpos($component, '.') !== false) {
list($plugin, $component) = explode('.', $component);
$plugin = $plugin . '.';
}
$componentCn = $component . 'Component'; $componentCn = $component . 'Component';
if (!class_exists($componentCn)) { if (!class_exists($componentCn)) {

View file

@ -46,9 +46,7 @@ class AclComponent extends Object {
$name = Inflector::camelize(strtolower(Configure::read('Acl.classname'))); $name = Inflector::camelize(strtolower(Configure::read('Acl.classname')));
if (!class_exists($name)) { if (!class_exists($name)) {
if (App::import('Component', $name)) { if (App::import('Component', $name)) {
if (strpos($name, '.') !== false) { list($plugin, $name) = pluginSplit($name);
list($plugin, $name) = explode('.', $name);
}
$name .= 'Component'; $name .= 'Component';
} else { } else {
trigger_error(sprintf(__('Could not find %s.', true), $name), E_USER_WARNING); trigger_error(sprintf(__('Could not find %s.', true), $name), E_USER_WARNING);

View file

@ -263,7 +263,7 @@ class CookieComponent extends Object {
/** /**
* @deprecated use delete() * @deprecated use delete()
**/ */
function del($key) { function del($key) {
trigger_error('Deprecated method, use CookieComponent::delete instead', E_USER_WARNING); trigger_error('Deprecated method, use CookieComponent::delete instead', E_USER_WARNING);
return $this->delete($key); return $this->delete($key);

View file

@ -391,9 +391,7 @@ class EmailComponent extends Object{
$viewClass = $this->Controller->view; $viewClass = $this->Controller->view;
if ($viewClass != 'View') { if ($viewClass != 'View') {
if (strpos($viewClass, '.') !== false) { list($plugin, $viewClass) = pluginSplit($viewClass);
list($plugin, $viewClass) = explode('.', $viewClass);
}
$viewClass = $viewClass . 'View'; $viewClass = $viewClass . 'View';
App::import('View', $this->Controller->view); App::import('View', $this->Controller->view);
} }

View file

@ -576,7 +576,7 @@ class SecurityComponent extends Object {
} }
$data = $controller->data; $data = $controller->data;
if (!isset($data['_Token']) || !isset($data['_Token']['fields'])) { if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['key'])) {
return false; return false;
} }
$token = $data['_Token']['key']; $token = $data['_Token']['key'];

View file

@ -528,11 +528,7 @@ class Controller extends Object {
$plugin = $this->plugin . '.'; $plugin = $this->plugin . '.';
} }
} }
list($plugin, $modelClass) = pluginSplit($modelClass, true, $plugin);
if (strpos($modelClass, '.') !== false) {
list($plugin, $modelClass) = explode('.', $modelClass);
$plugin = $plugin . '.';
}
if ($this->persistModel === true) { if ($this->persistModel === true) {
$cached = $this->_persist($modelClass, null, $object); $cached = $this->_persist($modelClass, null, $object);
@ -808,9 +804,7 @@ class Controller extends Object {
$viewClass = $this->view; $viewClass = $this->view;
if ($this->view != 'View') { if ($this->view != 'View') {
if (strpos($viewClass, '.') !== false) { list($plugin, $viewClass) = pluginSplit($viewClass);
list($plugin, $viewClass) = explode('.', $viewClass);
}
$viewClass = $viewClass . 'View'; $viewClass = $viewClass . 'View';
App::import('View', $this->view); App::import('View', $this->view);
} }
@ -1003,9 +997,8 @@ class Controller extends Object {
if (is_string($object)) { if (is_string($object)) {
$assoc = null; $assoc = null;
if (strpos($object, '.') !== false) {
if (strpos($object, '.') !== false) { list($object, $assoc) = pluginSplit($object);
list($object, $assoc) = explode('.', $object);
} }
if ($assoc && isset($this->{$object}->{$assoc})) { if ($assoc && isset($this->{$object}->{$assoc})) {
@ -1112,8 +1105,9 @@ class Controller extends Object {
$type = $defaults[0]; $type = $defaults[0];
unset($defaults[0]); unset($defaults[0]);
} }
$options = array_merge(array('page' => 1, 'limit' => 20), $defaults, $options);
extract($options = array_merge(array('page' => 1, 'limit' => 20), $defaults, $options)); $options['limit'] = (empty($options['limit']) || !is_numeric($options['limit'])) ? 1 : $options['limit'];
extract($options);
if (is_array($scope) && !empty($scope)) { if (is_array($scope) && !empty($scope)) {
$conditions = array_merge($conditions, $scope); $conditions = array_merge($conditions, $scope);

View file

@ -107,10 +107,13 @@ class ErrorHandler extends Object {
if (!in_array(strtolower($method), array_map('strtolower', get_class_methods($this)))) { if (!in_array(strtolower($method), array_map('strtolower', get_class_methods($this)))) {
$method = 'error'; $method = 'error';
} }
if ($method !== 'error') { if ($method !== 'error') {
if (Configure::read('debug') == 0) { if (Configure::read('debug') == 0) {
$parentMethods = get_class_methods(get_parent_class($this)); $parentClass = get_parent_class($this);
if (strtolower($parentClass) != 'errorhandler') {
$method = 'error404';
}
$parentMethods = get_class_methods($parentClass);
if (in_array($method, $parentMethods)) { if (in_array($method, $parentMethods)) {
$method = 'error404'; $method = 'error404';
} }

View file

@ -577,7 +577,8 @@ class HttpSocket extends CakeSocket {
$stripIfEmpty = array( $stripIfEmpty = array(
'query' => '?%query', 'query' => '?%query',
'fragment' => '#%fragment', 'fragment' => '#%fragment',
'user' => '%user:%pass@' 'user' => '%user:%pass@',
'host' => '%host:%port/'
); );
foreach ($stripIfEmpty as $key => $strip) { foreach ($stripIfEmpty as $key => $strip) {
@ -590,7 +591,6 @@ class HttpSocket extends CakeSocket {
if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) { if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) {
$uriTemplate = str_replace(':%port', null, $uriTemplate); $uriTemplate = str_replace(':%port', null, $uriTemplate);
} }
foreach ($uri as $property => $value) { foreach ($uri as $property => $value) {
$uriTemplate = str_replace('%'.$property, $value, $uriTemplate); $uriTemplate = str_replace('%'.$property, $value, $uriTemplate);
} }

View file

@ -392,7 +392,7 @@ class I18n extends Object {
$header = ""; $header = "";
do { do {
$line = trim(fgets($file, 1024)); $line = trim(fgets($file));
if ($line == "" || $line[0] == "#") { if ($line == "" || $line[0] == "#") {
continue; continue;
} }

View file

@ -37,7 +37,7 @@ class Inflector {
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_plural = array( var $_plural = array(
'rules' => array( 'rules' => array(
'/(s)tatus$/i' => '\1\2tatuses', '/(s)tatus$/i' => '\1\2tatuses',
@ -105,7 +105,7 @@ class Inflector {
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_singular = array( var $_singular = array(
'rules' => array( 'rules' => array(
'/(s)tatuses$/i' => '\1\2tatus', '/(s)tatuses$/i' => '\1\2tatus',
@ -139,6 +139,7 @@ class Inflector {
'/(m)en$/i' => '\1an', '/(m)en$/i' => '\1an',
'/(c)hildren$/i' => '\1\2hild', '/(c)hildren$/i' => '\1\2hild',
'/(n)ews$/i' => '\1\2ews', '/(n)ews$/i' => '\1\2ews',
'/eaus$/' => 'eau',
'/^(.*us)$/' => '\\1', '/^(.*us)$/' => '\\1',
'/s$/i' => '' '/s$/i' => ''
), ),
@ -155,7 +156,7 @@ class Inflector {
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_uninflected = array( var $_uninflected = array(
'Amoyese', 'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus', 'Amoyese', 'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus',
'carp', 'chassis', 'clippers', 'cod', 'coitus', 'Congoese', 'contretemps', 'corps', 'carp', 'chassis', 'clippers', 'cod', 'coitus', 'Congoese', 'contretemps', 'corps',
@ -176,7 +177,7 @@ class Inflector {
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_pluralized = array(); var $_pluralized = array();
/** /**
@ -184,7 +185,7 @@ class Inflector {
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_singularized = array(); var $_singularized = array();
/** /**

View file

@ -2,7 +2,6 @@
/** /**
* File Storage stream for Logging * File Storage stream for Logging
* *
*
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
@ -18,7 +17,9 @@
* @since CakePHP(tm) v 1.3 * @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php) * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/ */
if (!class_exists('File')) {
require LIBS . 'file.php';
}
/** /**
* File Storage stream for Logging * File Storage stream for Logging
* *
@ -31,7 +32,7 @@ class FileLog {
* Path to save log files on. * Path to save log files on.
* *
* @var string * @var string
**/ */
var $_path = null; var $_path = null;
/** /**
@ -43,7 +44,7 @@ class FileLog {
* *
* @param array $options Options for the FileLog, see above. * @param array $options Options for the FileLog, see above.
* @return void * @return void
**/ */
function FileLog($options = array()) { function FileLog($options = array()) {
$options += array('path' => LOGS); $options += array('path' => LOGS);
$this->_path = $options['path']; $this->_path = $options['path'];
@ -55,7 +56,7 @@ class FileLog {
* @param string $type The type of log you are making. * @param string $type The type of log you are making.
* @param string $message The message you want to log. * @param string $message The message you want to log.
* @return boolean success of write. * @return boolean success of write.
**/ */
function write($type, $message) { function write($type, $message) {
$debugTypes = array('notice', 'info', 'debug'); $debugTypes = array('notice', 'info', 'debug');

View file

@ -36,7 +36,7 @@ class MagicDb extends Object {
* Holds the parsed MagicDb for this class instance * Holds the parsed MagicDb for this class instance
* *
* @var array * @var array
**/ */
var $db = array(); var $db = array();
/** /**
@ -45,7 +45,7 @@ class MagicDb extends Object {
* @var $magicDb mixed Can be an array containing the db, a magic db as a string, or a filename pointing to a magic db in .db or magic.db.php format * @var $magicDb mixed Can be an array containing the db, a magic db as a string, or a filename pointing to a magic db in .db or magic.db.php format
* @return boolean Returns false if reading / validation failed or true on success. * @return boolean Returns false if reading / validation failed or true on success.
* @author Felix * @author Felix
**/ */
function read($magicDb = null) { function read($magicDb = null) {
if (!is_string($magicDb) && !is_array($magicDb)) { if (!is_string($magicDb) && !is_array($magicDb)) {
return false; return false;

View file

@ -155,7 +155,7 @@ class ContainableBehavior extends ModelBehavior {
if (!$reset && empty($instance->__backOriginalAssociation)) { if (!$reset && empty($instance->__backOriginalAssociation)) {
$instance->__backOriginalAssociation = $backupBindings; $instance->__backOriginalAssociation = $backupBindings;
} else if ($reset) { } else if ($reset) {
$instance->__backAssociation[$type] = $instance->{$type}; $instance->__backAssociation[$type] = $backupBindings[$type];
} }
$instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]); $instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]);
} }

View file

@ -63,7 +63,7 @@ class CakeSchema extends Object {
* plugin name. * plugin name.
* *
* @var string * @var string
**/ */
var $plugin = null; var $plugin = null;
/** /**
@ -245,7 +245,7 @@ class CakeSchema extends Object {
if (is_object($Object) && $Object->useTable !== false) { if (is_object($Object) && $Object->useTable !== false) {
$Object->setDataSource($connection); $Object->setDataSource($connection);
$table = $db->fullTableName($Object->useTable, false); $table = $db->fullTableName($Object, false);
if (in_array($table, $currentTables)) { if (in_array($table, $currentTables)) {
$key = array_search($table, $currentTables); $key = array_search($table, $currentTables);
@ -382,7 +382,7 @@ class CakeSchema extends Object {
* @param string $table Table name you want returned. * @param string $table Table name you want returned.
* @param array $fields Array of field information to generate the table with. * @param array $fields Array of field information to generate the table with.
* @return string Variable declaration for a schema class * @return string Variable declaration for a schema class
**/ */
function generateTable($table, $fields) { function generateTable($table, $fields) {
$out = "\tvar \${$table} = array(\n"; $out = "\tvar \${$table} = array(\n";
if (is_array($fields)) { if (is_array($fields)) {
@ -573,7 +573,7 @@ class CakeSchema extends Object {
* @param array $new New indexes * @param array $new New indexes
* @param array $old Old indexes * @param array $old Old indexes
* @return mixed False on failure, or an array of parameters to add & drop. * @return mixed False on failure, or an array of parameters to add & drop.
**/ */
function _compareTableParameters($new, $old) { function _compareTableParameters($new, $old) {
if (!is_array($new) || !is_array($old)) { if (!is_array($new) || !is_array($old)) {
return false; return false;

View file

@ -404,7 +404,7 @@ class DataSource extends Object {
* before establishing a connection. * before establishing a connection.
* *
* @return boolean Whether or not the Datasources conditions for use are met. * @return boolean Whether or not the Datasources conditions for use are met.
**/ */
function enabled() { function enabled() {
return true; return true;
} }

View file

@ -123,7 +123,7 @@ class DboAdodb extends DboSource {
* Check that AdoDB is available. * Check that AdoDB is available.
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return function_exists('NewADOConnection'); return function_exists('NewADOConnection');
} }

View file

@ -144,7 +144,7 @@ class DboDb2 extends DboSource {
* Check that the DB2 extension is installed/loaded * Check that the DB2 extension is installed/loaded
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('ibm_db2'); return extension_loaded('ibm_db2');
} }

View file

@ -117,7 +117,7 @@ class DboFirebird extends DboSource {
* Firebird Transaction commands. * Firebird Transaction commands.
* *
* @var array * @var array
**/ */
var $_commands = array( var $_commands = array(
'begin' => 'SET TRANSACTION', 'begin' => 'SET TRANSACTION',
'commit' => 'COMMIT', 'commit' => 'COMMIT',
@ -143,7 +143,7 @@ class DboFirebird extends DboSource {
* Check that the interbase extension is loaded * Check that the interbase extension is loaded
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('interbase'); return extension_loaded('interbase');
} }

View file

@ -162,7 +162,7 @@ class DboMssql extends DboSource {
* Check that MsSQL is installed/loaded * Check that MsSQL is installed/loaded
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('mssql'); return extension_loaded('mssql');
} }
@ -426,7 +426,7 @@ class DboMssql extends DboSource {
* @return string Error message with error number * @return string Error message with error number
*/ */
function lastError() { function lastError() {
$error = mssql_get_last_message($this->connection); $error = mssql_get_last_message();
if ($error) { if ($error) {
if (!preg_match('/contexto de la base de datos a|contesto di database|changed database|datenbankkontext/i', $error)) { if (!preg_match('/contexto de la base de datos a|contesto di database|changed database|datenbankkontext/i', $error)) {

View file

@ -352,7 +352,7 @@ class DboMysqlBase extends DboSource {
* @param array $parameters Parameters to add & drop. * @param array $parameters Parameters to add & drop.
* @return array Array of table property alteration statementes. * @return array Array of table property alteration statementes.
* @todo Implement this method. * @todo Implement this method.
**/ */
function _alterTableParameters($table, $parameters) { function _alterTableParameters($table, $parameters) {
if (isset($parameters['change'])) { if (isset($parameters['change'])) {
return $this->buildTableParameters($parameters['change']); return $this->buildTableParameters($parameters['change']);
@ -456,13 +456,14 @@ class DboMysqlBase extends DboSource {
* @return string Character set name * @return string Character set name
*/ */
function getCharsetName($name) { function getCharsetName($name) {
$cols = $this->query('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= ' . $this->value($name) . ';'); if ((bool)version_compare(mysql_get_server_info($this->connection), "5", ">=")) {
if (isset($cols[0]['COLLATIONS']['CHARACTER_SET_NAME'])) { $cols = $this->query('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= ' . $this->value($name) . ';');
return $cols[0]['COLLATIONS']['CHARACTER_SET_NAME']; if (isset($cols[0]['COLLATIONS']['CHARACTER_SET_NAME'])) {
return $cols[0]['COLLATIONS']['CHARACTER_SET_NAME'];
}
} }
return false; return false;
} }
} }
/** /**
@ -530,7 +531,7 @@ class DboMysql extends DboMysqlBase {
* Check whether the MySQL extension is installed/loaded * Check whether the MySQL extension is installed/loaded
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('mysql'); return extension_loaded('mysql');
} }

View file

@ -87,7 +87,7 @@ class DboMysqli extends DboMysqlBase {
* Check that MySQLi is installed/enabled * Check that MySQLi is installed/enabled
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('mysqli'); return extension_loaded('mysqli');
} }

View file

@ -110,7 +110,7 @@ class DboOdbc extends DboSource {
* Check if the ODBC extension is installed/loaded * Check if the ODBC extension is installed/loaded
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('odbc'); return extension_loaded('odbc');
} }

View file

@ -127,7 +127,7 @@ class DboPostgres extends DboSource {
* Check if PostgreSQL is enabled/loaded * Check if PostgreSQL is enabled/loaded
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('pgsql'); return extension_loaded('pgsql');
} }

View file

@ -141,7 +141,7 @@ class DboSqlite extends DboSource {
* Check that SQLite is enabled/installed * Check that SQLite is enabled/installed
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('sqlite'); return extension_loaded('sqlite');
} }

View file

@ -109,7 +109,7 @@ class DboSybase extends DboSource {
* Check that one of the sybase extensions is installed * Check that one of the sybase extensions is installed
* *
* @return boolean * @return boolean
**/ */
function enabled() { function enabled() {
return extension_loaded('sybase') || extension_loaded('sybase_ct'); return extension_loaded('sybase') || extension_loaded('sybase_ct');
} }

View file

@ -495,7 +495,7 @@ class DboSource extends DataSource {
* *
* @param boolean $sorted Get the queries sorted by time taken, defaults to false. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
* @return array Array of queries run as an array * @return array Array of queries run as an array
**/ */
function getLog($sorted = false) { function getLog($sorted = false) {
if ($sorted) { if ($sorted) {
$log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC); $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
@ -851,12 +851,12 @@ class DboSource extends DataSource {
if (count($ins) > 1) { if (count($ins) > 1) {
$query = str_replace('{$__cakeID__$}', '(' .join(', ', $ins) .')', $query); $query = str_replace('{$__cakeID__$}', '(' .join(', ', $ins) .')', $query);
$query = str_replace('= (', 'IN (', $query); $query = str_replace('= (', 'IN (', $query);
$query = str_replace('= (', 'IN (', $query); $query = str_replace('= (', 'IN (', $query);
} else { } else {
$query = str_replace('{$__cakeID__$}',$ins[0], $query); $query = str_replace('{$__cakeID__$}',$ins[0], $query);
} }
$query = str_replace(' WHERE 1 = 1', '', $query); $query = str_replace(' WHERE 1 = 1', '', $query);
} }
$foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey']; $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
@ -930,7 +930,7 @@ class DboSource extends DataSource {
$this->__mergeAssociation($resultSet[$i], $fetch, $association, $type, $selfJoin); $this->__mergeAssociation($resultSet[$i], $fetch, $association, $type, $selfJoin);
} }
if (isset($resultSet[$i][$association])) { if (isset($resultSet[$i][$association])) {
$resultSet[$i][$association] = $linkModel->afterFind($resultSet[$i][$association]); $resultSet[$i][$association] = $linkModel->afterFind($resultSet[$i][$association], false);
} }
} else { } else {
$tempArray[0][$association] = false; $tempArray[0][$association] = false;
@ -952,7 +952,7 @@ class DboSource extends DataSource {
$query = str_replace('{$__cakeID__$}', join(', ', $ids), $query); $query = str_replace('{$__cakeID__$}', join(', ', $ids), $query);
if (count($ids) > 1) { if (count($ids) > 1) {
$query = str_replace('= (', 'IN (', $query); $query = str_replace('= (', 'IN (', $query);
$query = str_replace('= (', 'IN (', $query); $query = str_replace('= (', 'IN (', $query);
} }
return $this->fetchAll($query, $model->cacheQueries, $model->alias); return $this->fetchAll($query, $model->cacheQueries, $model->alias);
} }
@ -967,7 +967,7 @@ class DboSource extends DataSource {
* @param object $model Model being merged onto * @param object $model Model being merged onto
* @param object $linkModel Model being merged * @param object $linkModel Model being merged
* @return void * @return void
**/ */
function __mergeHasMany(&$resultSet, $merge, $association, &$model, &$linkModel) { function __mergeHasMany(&$resultSet, $merge, $association, &$model, &$linkModel) {
foreach ($resultSet as $i => $value) { foreach ($resultSet as $i => $value) {
$count = 0; $count = 0;
@ -2483,7 +2483,7 @@ class DboSource extends DataSource {
* @param array $columnData The array of column data. * @param array $columnData The array of column data.
* @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
* @return string a built column with the field parameters added. * @return string a built column with the field parameters added.
**/ */
function _buildFieldParameters($columnString, $columnData, $position) { function _buildFieldParameters($columnString, $columnData, $position) {
foreach ($this->fieldParameters as $paramName => $value) { foreach ($this->fieldParameters as $paramName => $value) {
if (isset($columnData[$paramName]) && $value['position'] == $position) { if (isset($columnData[$paramName]) && $value['position'] == $position) {

View file

@ -641,20 +641,15 @@ class Model extends Overloadable {
if (strpos($assoc, '.') !== false) { if (strpos($assoc, '.') !== false) {
$value = $this->{$type}[$assoc]; $value = $this->{$type}[$assoc];
unset($this->{$type}[$assoc]); unset($this->{$type}[$assoc]);
list($plugin, $assoc) = explode('.', $assoc); list($plugin, $assoc) = pluginSplit($assoc, true);
$this->{$type}[$assoc] = $value; $this->{$type}[$assoc] = $value;
$plugin = $plugin . '.';
} }
} }
$className = $assoc; $className = $assoc;
if (isset($value['className']) && !empty($value['className'])) { if (!empty($value['className'])) {
$className = $value['className']; list($plugin, $className) = pluginSplit($value['className'], true);
if (strpos($className, '.') !== false) { $this->{$type}[$assoc]['className'] = $className;
list($plugin, $className) = explode('.', $className);
$plugin = $plugin . '.';
$this->{$type}[$assoc]['className'] = $className;
}
} }
$this->__constructLinkedModel($assoc, $plugin . $className); $this->__constructLinkedModel($assoc, $plugin . $className);
} }
@ -753,13 +748,8 @@ class Model extends Overloadable {
if (is_array($joinClass)) { if (is_array($joinClass)) {
$joinClass = key($joinClass); $joinClass = key($joinClass);
} }
$plugin = null; list($plugin, $joinClass) = pluginSplit($joinClass, true);
$this->{$type}[$assocKey]['with'] = $joinClass;
if (strpos($joinClass, '.') !== false) {
list($plugin, $joinClass) = explode('.', $joinClass);
$plugin = $plugin . '.';
$this->{$type}[$assocKey]['with'] = $joinClass;
}
if (!ClassRegistry::isKeySet($joinClass) && $dynamicWith === true) { if (!ClassRegistry::isKeySet($joinClass) && $dynamicWith === true) {
$this->{$joinClass} = new AppModel(array( $this->{$joinClass} = new AppModel(array(
@ -2453,7 +2443,7 @@ class Model extends Overloadable {
) || ) ||
$this->beforeValidate($options) === false $this->beforeValidate($options) === false
) { ) {
return $this->validationErrors; return false;
} }
if (!isset($this->validate) || empty($this->validate)) { if (!isset($this->validate) || empty($this->validate)) {
@ -2925,7 +2915,7 @@ class Model extends Overloadable {
} }
/** /**
* Called during save operations, before validation. Please note that custom * Called during validation operations, before validation. Please note that custom
* validation rules can be defined in $validate. * validation rules can be defined in $validate.
* *
* @return boolean True if validate operation should continue, false to abort * @return boolean True if validate operation should continue, false to abort

View file

@ -279,10 +279,7 @@ class BehaviorCollection extends Object {
* @access public * @access public
*/ */
function attach($behavior, $config = array()) { function attach($behavior, $config = array()) {
$name = $behavior; list($plugin, $name) = pluginSplit($behavior);
if (strpos($behavior, '.')) {
list($plugin, $name) = explode('.', $behavior, 2);
}
$class = $name . 'Behavior'; $class = $name . 'Behavior';
if (!App::import('Behavior', $behavior)) { if (!App::import('Behavior', $behavior)) {

View file

@ -161,7 +161,7 @@ class Router {
* Builds __prefixes * Builds __prefixes
* *
* @return void * @return void
**/ */
function Router() { function Router() {
$this->__setPrefixes(); $this->__setPrefixes();
} }
@ -173,7 +173,7 @@ class Router {
* @return void * @return void
* @access private * @access private
* @todo Remove support for Routing.admin in future versions. * @todo Remove support for Routing.admin in future versions.
**/ */
function __setPrefixes() { function __setPrefixes() {
$routing = Configure::read('Routing'); $routing = Configure::read('Routing');
if (!empty($routing['admin'])) { if (!empty($routing['admin'])) {
@ -183,6 +183,7 @@ class Router {
$this->__prefixes = array_merge($this->__prefixes, (array)$routing['prefixes']); $this->__prefixes = array_merge($this->__prefixes, (array)$routing['prefixes']);
} }
} }
/** /**
* Gets a reference to the Router object instance * Gets a reference to the Router object instance
* *
@ -232,6 +233,7 @@ class Router {
foreach ($_this->__prefixes as $prefix) { foreach ($_this->__prefixes as $prefix) {
if (isset($default[$prefix])) { if (isset($default[$prefix])) {
$default['prefix'] = $prefix; $default['prefix'] = $prefix;
break;
} }
} }
if (isset($default['prefix'])) { if (isset($default['prefix'])) {
@ -597,6 +599,7 @@ class Router {
if (strcasecmp($name, $match) === 0) { if (strcasecmp($name, $match) === 0) {
$url = substr($url, 0, strpos($url, '.' . $name)); $url = substr($url, 0, strpos($url, '.' . $name));
$ext = $match; $ext = $match;
break;
} }
} }
} }
@ -859,6 +862,7 @@ class Router {
$plugin = $url['plugin']; $plugin = $url['plugin'];
} }
$_url = $url;
$url = array_merge(array('controller' => $params['controller'], 'plugin' => $params['plugin']), Set::filter($url, true)); $url = array_merge(array('controller' => $params['controller'], 'plugin' => $params['plugin']), Set::filter($url, true));
if ($plugin !== false) { if ($plugin !== false) {
@ -878,7 +882,13 @@ class Router {
$originalUrl = $url; $originalUrl = $url;
if (isset($route[4]['persist'], $_this->__params[0])) { if (isset($route[4]['persist'], $_this->__params[0])) {
$url = array_merge(array_intersect_key($params, Set::combine($route[4]['persist'], '/')), $url); foreach($route[4]['persist'] as $_key) {
if (array_key_exists($_key, $_url)) {
$url[$_key] = $_url[$_key];
} elseif (array_key_exists($_key, $params)) {
$url[$_key] = $params[$_key];
}
}
} }
if ($match = $_this->mapRouteElements($route, $url)) { if ($match = $_this->mapRouteElements($route, $url)) {
$output = trim($match, '/'); $output = trim($match, '/');
@ -890,7 +900,7 @@ class Router {
$named = $args = array(); $named = $args = array();
$skip = array_merge( $skip = array_merge(
array('bare', 'action', 'controller', 'plugin', 'ext', '?', '#', 'prefix'), array('bare', 'action', 'controller', 'plugin', 'ext', '?', '#', 'prefix'),
$_this->__prefixes $_this->__prefixes
); );

View file

@ -61,7 +61,6 @@ class Security extends Object {
* @static * @static
*/ */
function inactiveMins() { function inactiveMins() {
$_this =& Security::getInstance();
switch (Configure::read('Security.level')) { switch (Configure::read('Security.level')) {
case 'high': case 'high':
return 10; return 10;
@ -179,7 +178,6 @@ class Security extends Object {
return ''; return '';
} }
$_this =& Security::getInstance();
if (!defined('CIPHER_SEED')) { if (!defined('CIPHER_SEED')) {
//This is temporary will change later //This is temporary will change later
define('CIPHER_SEED', '76859309657453542496749683645'); define('CIPHER_SEED', '76859309657453542496749683645');

View file

@ -213,8 +213,8 @@ class Validation extends Object {
* *
* @param mixed $check credit card number to validate * @param mixed $check credit card number to validate
* @param mixed $type 'all' may be passed as a sting, defaults to fast which checks format of most major credit cards * @param mixed $type 'all' may be passed as a sting, defaults to fast which checks format of most major credit cards
* if an array is used only the values of the array are checked. * if an array is used only the values of the array are checked.
* Example: array('amex', 'bankcard', 'maestro') * Example: array('amex', 'bankcard', 'maestro')
* @param boolean $deep set to true this will check the Luhn algorithm of the credit card. * @param boolean $deep set to true this will check the Luhn algorithm of the credit card.
* @param string $regex A custom regex can also be passed, this will be used instead of the defined regex values * @param string $regex A custom regex can also be passed, this will be used instead of the defined regex values
* @return boolean Success * @return boolean Success
@ -608,12 +608,14 @@ class Validation extends Object {
/** /**
* Validate a multiple select. * Validate a multiple select.
* *
* Valid Options
*
* - in => provide a list of choices that selections must be made from
* - max => maximun number of non-zero choices that can be made
* - min => minimum number of non-zero choices that can be made
*
* @param mixed $check Value to check * @param mixed $check Value to check
* @param mixed $options Options for the check. * @param mixed $options Options for the check.
* Valid options
* in => provide a list of choices that selections must be made from
* max => maximun number of non-zero choices that can be made
* min => minimum number of non-zero choices that can be made
* @return boolean Success * @return boolean Success
* @access public * @access public
*/ */
@ -672,12 +674,16 @@ class Validation extends Object {
if (is_null($_this->regex)) { if (is_null($_this->regex)) {
switch ($_this->country) { switch ($_this->country) {
case 'us': case 'us':
case 'all':
case 'can':
// includes all NANPA members. see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories // includes all NANPA members. see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories
default:
$_this->regex = '/^(?:\+?1)?[-. ]?\\(?[2-9][0-8][0-9]\\)?[-. ]?[2-9][0-9]{2}[-. ]?[0-9]{4}$/'; $_this->regex = '/^(?:\+?1)?[-. ]?\\(?[2-9][0-8][0-9]\\)?[-. ]?[2-9][0-9]{2}[-. ]?[0-9]{4}$/';
break; break;
} }
} }
if (empty($_this->regex)) {
return $_this->_pass('phone', $check, $country);
}
return $_this->_check(); return $_this->_check();
} }
@ -698,6 +704,9 @@ class Validation extends Object {
if (is_array($check)) { if (is_array($check)) {
$_this->_extract($check); $_this->_extract($check);
} }
if (empty($country)) {
$_this->country = 'us';
}
if (is_null($_this->regex)) { if (is_null($_this->regex)) {
switch ($_this->country) { switch ($_this->country) {
@ -715,11 +724,13 @@ class Validation extends Object {
$_this->regex = '/^[1-9]{1}[0-9]{3}$/i'; $_this->regex = '/^[1-9]{1}[0-9]{3}$/i';
break; break;
case 'us': case 'us':
default:
$_this->regex = '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i'; $_this->regex = '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i';
break; break;
} }
} }
if (empty($_this->regex)) {
return $_this->_pass('postal', $check, $country);
}
return $_this->_check(); return $_this->_check();
} }
@ -783,13 +794,14 @@ class Validation extends Object {
* Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt
* *
* The regex checks for the following component parts: * The regex checks for the following component parts:
* a valid, optional, scheme *
* a valid ip address OR * - a valid, optional, scheme
* a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt * - a valid ip address OR
* with an optional port number * a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt
* an optional valid path * with an optional port number
* an optional query string (get parameters) * - an optional valid path
* an optional fragment (anchor tag) * - an optional query string (get parameters)
* - an optional fragment (anchor tag)
* *
* @param string $check Value to check * @param string $check Value to check
* @param boolean $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher) * @param boolean $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
@ -834,6 +846,31 @@ class Validation extends Object {
return call_user_func_array(array(&$object, $method), array($check, $args)); return call_user_func_array(array(&$object, $method), array($check, $args));
} }
/**
* Attempts to pass unhandled Validation locales to a class starting with $classPrefix
* and ending with Validation. For example $classPrefix = 'nl', the class would be
* `NlValidation`.
*
* @param string $method The method to call on the other class.
* @param mixed $check The value to check or an array of parameters for the method to be called.
* @param string $classPrefix The prefix for the class to do the validation.
* @return mixed Return of Passed method, false on failure
* @access protected
**/
function _pass($method, $check, $classPrefix) {
$className = ucwords($classPrefix) . 'Validation';
if (!class_exists($className)) {
trigger_error(sprintf(__('Could not find %s class, unable to complete validation.', true), $className), E_USER_WARNING);
return false;
}
if (!method_exists($className, $method)) {
trigger_error(sprintf(__('Method %s does not exist on %s unable to complete validation.', true), $method, $className), E_USER_WARNING);
return false;
}
$check = (array)$check;
return call_user_func_array(array($className, $method), $check);
}
/** /**
* Runs a regular expression match. * Runs a regular expression match.
* *

View file

@ -225,7 +225,7 @@ class Helper extends Overloadable {
* *
* @param string $path The file path to timestamp, the path must be inside WWW_ROOT * @param string $path The file path to timestamp, the path must be inside WWW_ROOT
* @return string Path with a timestamp added, or not. * @return string Path with a timestamp added, or not.
**/ */
function assetTimestamp($path) { function assetTimestamp($path) {
$timestampEnabled = ( $timestampEnabled = (
(Configure::read('Asset.timestamp') === true && Configure::read() > 0) || (Configure::read('Asset.timestamp') === true && Configure::read() > 0) ||
@ -578,8 +578,9 @@ class Helper extends Overloadable {
* @param array $options * @param array $options
* @param string $key * @param string $key
* @return array * @return array
* @access protected
*/ */
function __name($options = array(), $field = null, $key = 'name') { function _name($options = array(), $field = null, $key = 'name') {
$view =& ClassRegistry::getObject('view'); $view =& ClassRegistry::getObject('view');
if ($options === null) { if ($options === null) {
$options = array(); $options = array();
@ -646,7 +647,9 @@ class Helper extends Overloadable {
} }
$habtmKey = $this->field(); $habtmKey = $this->field();
if (empty($result) && isset($this->data[$habtmKey]) && is_array($this->data[$habtmKey])) { if (empty($result) && isset($this->data[$habtmKey][$habtmKey])) {
$result = $this->data[$habtmKey][$habtmKey];
} elseif (empty($result) && isset($this->data[$habtmKey]) && is_array($this->data[$habtmKey])) {
if (ClassRegistry::isKeySet($habtmKey)) { if (ClassRegistry::isKeySet($habtmKey)) {
$model =& ClassRegistry::getObject($habtmKey); $model =& ClassRegistry::getObject($habtmKey);
$result = $this->__selectedArray($this->data[$habtmKey], $model->primaryKey); $result = $this->__selectedArray($this->data[$habtmKey], $model->primaryKey);
@ -687,7 +690,7 @@ class Helper extends Overloadable {
$this->setEntity($field); $this->setEntity($field);
} }
$options = (array)$options; $options = (array)$options;
$options = $this->__name($options); $options = $this->_name($options);
$options = $this->value($options); $options = $this->value($options);
$options = $this->domId($options); $options = $this->domId($options);
if ($this->tagIsInvalid()) { if ($this->tagIsInvalid()) {

View file

@ -528,7 +528,7 @@ class AjaxHelper extends AppHelper {
} }
} }
$attr = $this->_parseAttributes(array_merge($options, array('id' => $id))); $attr = $this->_parseAttributes(array_merge($options, array('id' => $id)));
return $this->output(sprintf($this->Html->tags['blockstart'], $attr)); return sprintf($this->Html->tags['blockstart'], $attr);
} }
/** /**
@ -547,7 +547,7 @@ class AjaxHelper extends AppHelper {
return ''; return '';
} }
} }
return $this->output($this->Html->tags['blockend']); return $this->Html->tags['blockend'];
} }
/** /**

View file

@ -68,24 +68,32 @@ class CacheHelper extends AppHelper {
$useCallbacks = false; $useCallbacks = false;
if (is_array($this->cacheAction)) { if (is_array($this->cacheAction)) {
$controller = Inflector::underscore($this->controllerName); $controller = Inflector::underscore($this->controllerName);
$controllerAlternate = Inflector::variable($this->controllerName);
$check = str_replace('/', '_', $this->here); $check = str_replace('/', '_', $this->here);
$replace = str_replace('/', '_', $this->base); $basePath = str_replace('/', '_', $this->base);
$match = str_replace($this->base, '', $this->here); $match = str_replace($this->base, '', $this->here);
$match = str_replace('//', '/', $match); $match = str_replace('//', '/', $match);
$match = str_replace('/' . $controller . '/', '', $match); $match = str_replace('/' . $controller . '/', '', $match);
$match = str_replace('/' . $controllerAlternate . '/', '', $match);
$match = str_replace('/' . $this->controllerName . '/', '', $match); $match = str_replace('/' . $this->controllerName . '/', '', $match);
$check = str_replace($replace, '', $check);
$check = str_replace($basePath, '', $check);
$check = str_replace('_' . $controller . '_', '', $check); $check = str_replace('_' . $controller . '_', '', $check);
$check = str_replace('_' . $this->controllerName . '_', '', $check); $check = str_replace('_' . $this->controllerName . '_', '', $check);
$check = str_replace('_' . $controllerAlternate . '_', '', $match);
$check = Inflector::slug($check); $check = Inflector::slug($check);
$check = preg_replace('/^_+/', '', $check); $check = trim($check, '_');
$keys = str_replace('/', '_', array_keys($this->cacheAction)); $keys = str_replace('/', '_', array_keys($this->cacheAction));
$found = array_keys($this->cacheAction); $found = array_keys($this->cacheAction);
$index = null; $index = null;
$count = 0; $count = 0;
foreach ($keys as $key => $value) { foreach ($keys as $key => $value) {
if (strpos($check, $value) === 0) { if (strpos($check, rtrim($value, '_')) === 0) {
$index = $found[$count]; $index = $found[$count];
break; break;
} }

View file

@ -172,7 +172,8 @@ class FormHelper extends AppHelper {
if (is_array($model) && empty($options)) { if (is_array($model) && empty($options)) {
$options = $model; $options = $model;
$model = null; $model = null;
} elseif (empty($model) && $model !== false && !empty($this->params['models'])) { }
if (empty($model) && $model !== false && !empty($this->params['models'])) {
$model = $this->params['models'][0]; $model = $this->params['models'][0];
$this->defaultModel = $this->params['models'][0]; $this->defaultModel = $this->params['models'][0];
} elseif (empty($model) && empty($this->params['models'])) { } elseif (empty($model) && empty($this->params['models'])) {
@ -293,7 +294,7 @@ class FormHelper extends AppHelper {
$this->setEntity($model . '.', true); $this->setEntity($model . '.', true);
$attributes = $this->_parseAttributes($htmlAttributes, null, ''); $attributes = $this->_parseAttributes($htmlAttributes, null, '');
return $this->output(sprintf($this->Html->tags['form'], $attributes)) . $append; return sprintf($this->Html->tags['form'], $attributes) . $append;
} }
/** /**
@ -348,7 +349,7 @@ class FormHelper extends AppHelper {
$view =& ClassRegistry::getObject('view'); $view =& ClassRegistry::getObject('view');
$view->modelScope = false; $view->modelScope = false;
return $this->output($out); return $out;
} }
/** /**
@ -527,11 +528,11 @@ class FormHelper extends AppHelper {
$labelFor = $this->domId($fieldName); $labelFor = $this->domId($fieldName);
} }
return $this->output(sprintf( return sprintf(
$this->Html->tags['label'], $this->Html->tags['label'],
$labelFor, $labelFor,
$this->_parseAttributes($options), $text $this->_parseAttributes($options), $text
)); );
} }
/** /**
@ -939,11 +940,11 @@ class FormHelper extends AppHelper {
} }
unset($options['hiddenField']); unset($options['hiddenField']);
return $this->output($output . sprintf( return $output . sprintf(
$this->Html->tags['checkbox'], $this->Html->tags['checkbox'],
$options['name'], $options['name'],
$this->_parseAttributes($options, array('name'), null, ' ') $this->_parseAttributes($options, array('name'), null, ' ')
)); );
} }
/** /**
@ -1035,7 +1036,7 @@ class FormHelper extends AppHelper {
sprintf($this->Html->tags['legend'], $legend) . $out sprintf($this->Html->tags['legend'], $legend) . $out
); );
} }
return $this->output($out); return $out;
} }
/** /**
@ -1049,11 +1050,11 @@ class FormHelper extends AppHelper {
$options = $this->_initInputField($fieldName, array_merge( $options = $this->_initInputField($fieldName, array_merge(
array('type' => 'text'), $options array('type' => 'text'), $options
)); ));
return $this->output(sprintf( return sprintf(
$this->Html->tags['input'], $this->Html->tags['input'],
$options['name'], $options['name'],
$this->_parseAttributes($options, array('name'), null, ' ') $this->_parseAttributes($options, array('name'), null, ' ')
)); );
} }
/** /**
@ -1065,11 +1066,11 @@ class FormHelper extends AppHelper {
*/ */
function password($fieldName, $options = array()) { function password($fieldName, $options = array()) {
$options = $this->_initInputField($fieldName, $options); $options = $this->_initInputField($fieldName, $options);
return $this->output(sprintf( return sprintf(
$this->Html->tags['password'], $this->Html->tags['password'],
$options['name'], $options['name'],
$this->_parseAttributes($options, array('name'), null, ' ') $this->_parseAttributes($options, array('name'), null, ' ')
)); );
} }
/** /**
@ -1090,12 +1091,12 @@ class FormHelper extends AppHelper {
} }
unset($options['value']); unset($options['value']);
} }
return $this->output(sprintf( return sprintf(
$this->Html->tags['textarea'], $this->Html->tags['textarea'],
$options['name'], $options['name'],
$this->_parseAttributes($options, array('type', 'name'), null, ' '), $this->_parseAttributes($options, array('type', 'name'), null, ' '),
$value $value
)); );
} }
/** /**
@ -1122,11 +1123,11 @@ class FormHelper extends AppHelper {
$this->__secure(null, '' . $options['value']); $this->__secure(null, '' . $options['value']);
} }
return $this->output(sprintf( return sprintf(
$this->Html->tags['hidden'], $this->Html->tags['hidden'],
$options['name'], $options['name'],
$this->_parseAttributes($options, array('name', 'class'), '', ' ') $this->_parseAttributes($options, array('name', 'class'), '', ' ')
)); );
} }
/** /**
@ -1148,7 +1149,7 @@ class FormHelper extends AppHelper {
} }
$attributes = $this->_parseAttributes($options, array('name'), '', ' '); $attributes = $this->_parseAttributes($options, array('name'), '', ' ');
return $this->output(sprintf($this->Html->tags['file'], $options['name'], $attributes)); return sprintf($this->Html->tags['file'], $options['name'], $attributes);
} }
/** /**
@ -1168,12 +1169,12 @@ class FormHelper extends AppHelper {
if ($options['escape']) { if ($options['escape']) {
$title = h($title); $title = h($title);
} }
return $this->output(sprintf( return sprintf(
$this->Html->tags['button'], $this->Html->tags['button'],
$options['type'], $options['type'],
$this->_parseAttributes($options, array('type'), '', ' '), $this->_parseAttributes($options, array('type'), '', ' '),
$title $title
)); );
} }
/** /**
@ -1216,11 +1217,11 @@ class FormHelper extends AppHelper {
if (strpos($caption, '://') !== false) { if (strpos($caption, '://') !== false) {
unset($options['type']); unset($options['type']);
$out .= $this->output($before . sprintf( $out .= $before . sprintf(
$this->Html->tags['submitimage'], $this->Html->tags['submitimage'],
$caption, $caption,
$this->_parseAttributes($options, null, '', ' ') $this->_parseAttributes($options, null, '', ' ')
) . $after); ) . $after;
} elseif (preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption)) { } elseif (preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption)) {
unset($options['type']); unset($options['type']);
if ($caption{0} !== '/') { if ($caption{0} !== '/') {
@ -1229,17 +1230,17 @@ class FormHelper extends AppHelper {
$caption = trim($caption, '/'); $caption = trim($caption, '/');
$url = $this->webroot($caption); $url = $this->webroot($caption);
} }
$out .= $this->output($before . sprintf( $out .= $before . sprintf(
$this->Html->tags['submitimage'], $this->Html->tags['submitimage'],
$url, $url,
$this->_parseAttributes($options, null, '', ' ') $this->_parseAttributes($options, null, '', ' ')
) . $after); ) . $after;
} else { } else {
$options['value'] = $caption; $options['value'] = $caption;
$out .= $this->output($before . sprintf( $out .= $before . sprintf(
$this->Html->tags['submit'], $this->Html->tags['submit'],
$this->_parseAttributes($options, null, '', ' ') $this->_parseAttributes($options, null, '', ' ')
). $after); ). $after;
} }
if (isset($divOptions)) { if (isset($divOptions)) {
@ -1346,7 +1347,7 @@ class FormHelper extends AppHelper {
$template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend'; $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend';
$select[] = $this->Html->tags[$template]; $select[] = $this->Html->tags[$template];
return $this->output(implode("\n", $select)); return implode("\n", $select);
} }
/** /**
@ -1751,8 +1752,9 @@ class FormHelper extends AppHelper {
* @param array $options * @param array $options
* @param string $key * @param string $key
* @return array * @return array
* @access protected
*/ */
function __name($options = array(), $field = null, $key = 'name') { function _name($options = array(), $field = null, $key = 'name') {
if ($this->requestType == 'get') { if ($this->requestType == 'get') {
if ($options === null) { if ($options === null) {
$options = array(); $options = array();
@ -1777,7 +1779,7 @@ class FormHelper extends AppHelper {
return $name; return $name;
} }
} }
return parent::__name($options, $field, $key); return parent::_name($options, $field, $key);
} }
/** /**
@ -1846,7 +1848,7 @@ class FormHelper extends AppHelper {
$label['class'] = 'selected'; $label['class'] = 'selected';
} }
list($name) = array_values($this->__name()); list($name) = array_values($this->_name());
if (empty($attributes['class'])) { if (empty($attributes['class'])) {
$attributes['class'] = 'checkbox'; $attributes['class'] = 'checkbox';

View file

@ -143,14 +143,14 @@ class HtmlHelper extends AppHelper {
* *
* @var array * @var array
* @access private * @access private
**/ */
var $__includedScripts = array(); var $__includedScripts = array();
/** /**
* Options for the currently opened script block buffer if any. * Options for the currently opened script block buffer if any.
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_scriptBlockOptions = array(); var $_scriptBlockOptions = array();
/** /**
* Document type definitions * Document type definitions
@ -201,7 +201,7 @@ class HtmlHelper extends AppHelper {
*/ */
function docType($type = 'xhtml-strict') { function docType($type = 'xhtml-strict') {
if (isset($this->__docTypes[$type])) { if (isset($this->__docTypes[$type])) {
return $this->output($this->__docTypes[$type]); return $this->__docTypes[$type];
} }
return null; return null;
} }
@ -270,7 +270,7 @@ class HtmlHelper extends AppHelper {
} }
if ($inline) { if ($inline) {
return $this->output($out); return $out;
} else { } else {
$view =& ClassRegistry::getObject('view'); $view =& ClassRegistry::getObject('view');
$view->addScript($out); $view->addScript($out);
@ -288,7 +288,7 @@ class HtmlHelper extends AppHelper {
if (empty($charset)) { if (empty($charset)) {
$charset = strtolower(Configure::read('App.encoding')); $charset = strtolower(Configure::read('App.encoding'));
} }
return $this->output(sprintf($this->tags['charset'], (!empty($charset) ? $charset : 'utf-8'))); return sprintf($this->tags['charset'], (!empty($charset) ? $charset : 'utf-8'));
} }
/** /**
@ -347,7 +347,7 @@ class HtmlHelper extends AppHelper {
} }
unset($options['default']); unset($options['default']);
} }
return $this->output(sprintf($this->tags['link'], $url, $this->_parseAttributes($options), $title)); return sprintf($this->tags['link'], $url, $this->_parseAttributes($options), $title);
} }
/** /**
@ -355,7 +355,7 @@ class HtmlHelper extends AppHelper {
* *
* #### Options * #### Options
* *
* - `inline` If set to false, the generated tag appears in the head tag of the layout. * - `inline` If set to false, the generated tag appears in the head tag of the layout. Defaults to true
* *
* @param mixed $path The name of a CSS style sheet or an array containing names of * @param mixed $path The name of a CSS style sheet or an array containing names of
* CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot * CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot
@ -366,13 +366,13 @@ class HtmlHelper extends AppHelper {
* @access public * @access public
*/ */
function css($path, $rel = null, $options = array()) { function css($path, $rel = null, $options = array()) {
$inline = isset($options['inline']) ? $options['inline'] : true; $options += array('inline' => true);
if (is_array($path)) { if (is_array($path)) {
$out = ''; $out = '';
foreach ($path as $i) { foreach ($path as $i) {
$out .= "\n\t" . $this->css($i, $rel, $options, $inline); $out .= "\n\t" . $this->css($i, $rel, $options);
} }
if ($inline) { if ($options['inline']) {
return $out . "\n"; return $out . "\n";
} }
return; return;
@ -401,16 +401,15 @@ class HtmlHelper extends AppHelper {
} }
if ($rel == 'import') { if ($rel == 'import') {
$out = sprintf($this->tags['style'], $this->_parseAttributes($options, null, '', ' '), '@import url(' . $url . ');'); $out = sprintf($this->tags['style'], $this->_parseAttributes($options, array('inline'), '', ' '), '@import url(' . $url . ');');
} else { } else {
if ($rel == null) { if ($rel == null) {
$rel = 'stylesheet'; $rel = 'stylesheet';
} }
$out = sprintf($this->tags['css'], $rel, $url, $this->_parseAttributes($options, array('inline'), '', ' ')); $out = sprintf($this->tags['css'], $rel, $url, $this->_parseAttributes($options, array('inline'), '', ' '));
} }
$out = $this->output($out);
if ($inline) { if ($options['inline']) {
return $out; return $out;
} else { } else {
$view =& ClassRegistry::getObject('view'); $view =& ClassRegistry::getObject('view');
@ -436,7 +435,7 @@ class HtmlHelper extends AppHelper {
* @param mixed $options Array of options, and html attributes see above. If boolean sets $options['inline'] = value * @param mixed $options Array of options, and html attributes see above. If boolean sets $options['inline'] = value
* @return mixed String of <script /> tags or null if $inline is false or if $once is true and the file has been * @return mixed String of <script /> tags or null if $inline is false or if $once is true and the file has been
* included before. * included before.
**/ */
function script($url, $options = array()) { function script($url, $options = array()) {
if (is_bool($options)) { if (is_bool($options)) {
list($inline, $options) = array($options, array()); list($inline, $options) = array($options, array());
@ -471,12 +470,10 @@ class HtmlHelper extends AppHelper {
$url = str_replace(JS_URL, 'cjs/', $url); $url = str_replace(JS_URL, 'cjs/', $url);
} }
} }
$inline = $options['inline']; $attributes = $this->_parseAttributes($options, array('inline', 'once'), ' ');
unset($options['inline'], $options['once']); $out = sprintf($this->tags['javascriptlink'], $url, $attributes);
$attributes = $this->_parseAttributes($options, ' ', ' ');
$out = $this->output(sprintf($this->tags['javascriptlink'], $url, $attributes));
if ($inline) { if ($options['inline']) {
return $out; return $out;
} else { } else {
$view =& ClassRegistry::getObject('view'); $view =& ClassRegistry::getObject('view');
@ -494,10 +491,9 @@ class HtmlHelper extends AppHelper {
* @param string $script The script to wrap * @param string $script The script to wrap
* @param array $options The options to use. * @param array $options The options to use.
* @return mixed string or null depending on the value of `$options['inline']` * @return mixed string or null depending on the value of `$options['inline']`
**/ */
function scriptBlock($script, $options = array()) { function scriptBlock($script, $options = array()) {
$defaultOptions = array('safe' => true, 'inline' => true); $options += array('safe' => true, 'inline' => true);
$options = array_merge($defaultOptions, $options);
if ($options['safe']) { if ($options['safe']) {
$script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n"; $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
} }
@ -524,10 +520,9 @@ class HtmlHelper extends AppHelper {
* *
* @param array $options Options for the code block. * @param array $options Options for the code block.
* @return void * @return void
**/ */
function scriptStart($options = array()) { function scriptStart($options = array()) {
$defaultOptions = array('safe' => true, 'inline' => true); $options += array('safe' => true, 'inline' => true);
$options = array_merge($defaultOptions, $options);
$this->_scriptBlockOptions = $options; $this->_scriptBlockOptions = $options;
ob_start(); ob_start();
return null; return null;
@ -538,7 +533,7 @@ class HtmlHelper extends AppHelper {
* used when the scriptBlock was started * used when the scriptBlock was started
* *
* @return mixed depending on the settings of scriptStart() either a script tag or null * @return mixed depending on the settings of scriptStart() either a script tag or null
**/ */
function scriptEnd() { function scriptEnd() {
$buffer = ob_get_clean(); $buffer = ob_get_clean();
$options = $this->_scriptBlockOptions; $options = $this->_scriptBlockOptions;
@ -589,7 +584,7 @@ class HtmlHelper extends AppHelper {
$out[] = $crumb[0]; $out[] = $crumb[0];
} }
} }
return $this->output(join($separator, $out)); return join($separator, $out);
} else { } else {
return null; return null;
} }
@ -628,9 +623,9 @@ class HtmlHelper extends AppHelper {
$image = sprintf($this->tags['image'], $path, $this->_parseAttributes($options, null, '', ' ')); $image = sprintf($this->tags['image'], $path, $this->_parseAttributes($options, null, '', ' '));
if ($url) { if ($url) {
return $this->output(sprintf($this->tags['link'], $this->url($url), null, $image)); return sprintf($this->tags['link'], $this->url($url), null, $image);
} }
return $this->output($image); return $image;
} }
/** /**
@ -647,8 +642,7 @@ class HtmlHelper extends AppHelper {
foreach ($names as $arg) { foreach ($names as $arg) {
$out[] = sprintf($this->tags['tableheader'], $this->_parseAttributes($thOptions), $arg); $out[] = sprintf($this->tags['tableheader'], $this->_parseAttributes($thOptions), $arg);
} }
$data = sprintf($this->tags['tablerow'], $this->_parseAttributes($trOptions), join(' ', $out)); return sprintf($this->tags['tablerow'], $this->_parseAttributes($trOptions), join(' ', $out));
return $this->output($data);
} }
/** /**
@ -702,7 +696,7 @@ class HtmlHelper extends AppHelper {
$options = $this->_parseAttributes($count % 2 ? $oddTrOptions : $evenTrOptions); $options = $this->_parseAttributes($count % 2 ? $oddTrOptions : $evenTrOptions);
$out[] = sprintf($this->tags['tablerow'], $options, join(' ', $cellsOut)); $out[] = sprintf($this->tags['tablerow'], $options, join(' ', $cellsOut));
} }
return $this->output(join("\n", $out)); return implode("\n", $out);
} }
/** /**
@ -733,7 +727,7 @@ class HtmlHelper extends AppHelper {
} else { } else {
$tag = 'tag'; $tag = 'tag';
} }
return $this->output(sprintf($this->tags[$tag], $name, $this->_parseAttributes($options, null, ' ', ''), $text, $name)); return sprintf($this->tags[$tag], $name, $this->_parseAttributes($options, null, ' ', ''), $text, $name);
} }
/** /**
@ -782,7 +776,7 @@ class HtmlHelper extends AppHelper {
} else { } else {
$tag = 'para'; $tag = 'para';
} }
return $this->output(sprintf($this->tags[$tag], $this->_parseAttributes($options, null, ' ', ''), $text)); return sprintf($this->tags[$tag], $this->_parseAttributes($options, null, ' ', ''), $text);
} }
/** /**

View file

@ -273,7 +273,7 @@ class JavascriptHelper extends AppHelper {
} }
} }
} }
$out = $this->output(sprintf($this->tags['javascriptlink'], $url)); $out = sprintf($this->tags['javascriptlink'], $url);
if ($inline) { if ($inline) {
return $out; return $out;
@ -319,7 +319,7 @@ class JavascriptHelper extends AppHelper {
* Encode a string into JSON. Converts and escapes necessary characters. * Encode a string into JSON. Converts and escapes necessary characters.
* *
* @return void * @return void
**/ */
function _utf8ToHex($string) { function _utf8ToHex($string) {
$length = strlen($string); $length = strlen($string);
$return = ''; $return = '';

View file

@ -27,7 +27,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* Option mappings for jQuery * Option mappings for jQuery
* *
* @var array * @var array
**/ */
var $_optionMap = array( var $_optionMap = array(
'request' => array( 'request' => array(
'type' => 'dataType', 'type' => 'dataType',
@ -55,7 +55,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* callback arguments lists * callback arguments lists
* *
* @var string * @var string
**/ */
var $_callbackArguments = array( var $_callbackArguments = array(
'slider' => array( 'slider' => array(
'start' => 'event, ui', 'start' => 'event, ui',
@ -103,7 +103,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* when jQuery is put into noConflict() mode. * when jQuery is put into noConflict() mode.
* *
* @var string * @var string
**/ */
var $jQueryObject = '$'; var $jQueryObject = '$';
/** /**
@ -116,7 +116,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param string $callbacks Array of callback / special options. * @param string $callbacks Array of callback / special options.
* @access public * @access public
* @return string * @return string
**/ */
function _methodTemplate($method, $template, $options, $extraSafeKeys = array()) { function _methodTemplate($method, $template, $options, $extraSafeKeys = array()) {
$options = $this->_mapOptions($method, $options); $options = $this->_mapOptions($method, $options);
$options = $this->_prepareCallbacks($method, $options); $options = $this->_prepareCallbacks($method, $options);
@ -133,7 +133,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* *
* @param string $selector The selector that is targeted * @param string $selector The selector that is targeted
* @return object instance of $this. Allows chained methods. * @return object instance of $this. Allows chained methods.
**/ */
function get($selector) { function get($selector) {
if ($selector == 'window' || $selector == 'document') { if ($selector == 'window' || $selector == 'document') {
$this->selection = $this->jQueryObject . '(' . $selector .')'; $this->selection = $this->jQueryObject . '(' . $selector .')';
@ -155,7 +155,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param string $callback The Javascript function you wish to trigger or the function literal * @param string $callback The Javascript function you wish to trigger or the function literal
* @param array $options Options for the event. * @param array $options Options for the event.
* @return string completed event handler * @return string completed event handler
**/ */
function event($type, $callback, $options = array()) { function event($type, $callback, $options = array()) {
$defaults = array('wrap' => true, 'stop' => true); $defaults = array('wrap' => true, 'stop' => true);
$options = array_merge($defaults, $options); $options = array_merge($defaults, $options);
@ -175,7 +175,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* *
* @param string $functionBody The code to run on domReady * @param string $functionBody The code to run on domReady
* @return string completed domReady method * @return string completed domReady method
**/ */
function domReady($functionBody) { function domReady($functionBody) {
$this->get('document'); $this->get('document');
return $this->event('ready', $functionBody, array('stop' => false)); return $this->event('ready', $functionBody, array('stop' => false));
@ -187,7 +187,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param string $method The method you want to apply to the selection * @param string $method The method you want to apply to the selection
* @param string $callback The function body you wish to apply during the iteration. * @param string $callback The function body you wish to apply during the iteration.
* @return string completed iteration * @return string completed iteration
**/ */
function each($callback) { function each($callback) {
return $this->selection . '.each(function () {' . $callback . '});'; return $this->selection . '.each(function () {' . $callback . '});';
} }
@ -199,7 +199,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the effect. * @param array $options Array of options for the effect.
* @return string completed string with effect. * @return string completed string with effect.
* @see JsBaseEngineHelper::effect() * @see JsBaseEngineHelper::effect()
**/ */
function effect($name, $options = array()) { function effect($name, $options = array()) {
$speed = null; $speed = null;
if (isset($options['speed']) && in_array($options['speed'], array('fast', 'slow'))) { if (isset($options['speed']) && in_array($options['speed'], array('fast', 'slow'))) {
@ -230,7 +230,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param mixed $url * @param mixed $url
* @param array $options * @param array $options
* @return string The completed ajax call. * @return string The completed ajax call.
**/ */
function request($url, $options = array()) { function request($url, $options = array()) {
$url = $this->url($url); $url = $this->url($url);
$options = $this->_mapOptions('request', $options); $options = $this->_mapOptions('request', $options);
@ -266,7 +266,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the sortable. * @param array $options Array of options for the sortable.
* @return string Completed sortable script. * @return string Completed sortable script.
* @see JsHelper::sortable() for options list. * @see JsHelper::sortable() for options list.
**/ */
function sortable($options = array()) { function sortable($options = array()) {
$template = '%s.sortable({%s});'; $template = '%s.sortable({%s});';
return $this->_methodTemplate('sortable', $template, $options); return $this->_methodTemplate('sortable', $template, $options);
@ -280,7 +280,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the draggable element. * @param array $options Array of options for the draggable element.
* @return string Completed Draggable script. * @return string Completed Draggable script.
* @see JsHelper::drag() for options list. * @see JsHelper::drag() for options list.
**/ */
function drag($options = array()) { function drag($options = array()) {
$template = '%s.draggable({%s});'; $template = '%s.draggable({%s});';
return $this->_methodTemplate('drag', $template, $options); return $this->_methodTemplate('drag', $template, $options);
@ -294,7 +294,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the droppable element. * @param array $options Array of options for the droppable element.
* @return string Completed Droppable script. * @return string Completed Droppable script.
* @see JsHelper::drop() for options list. * @see JsHelper::drop() for options list.
**/ */
function drop($options = array()) { function drop($options = array()) {
$template = '%s.droppable({%s});'; $template = '%s.droppable({%s});';
return $this->_methodTemplate('drop', $template, $options); return $this->_methodTemplate('drop', $template, $options);
@ -308,7 +308,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the droppable element. * @param array $options Array of options for the droppable element.
* @return string Completed Slider script. * @return string Completed Slider script.
* @see JsHelper::slider() for options list. * @see JsHelper::slider() for options list.
**/ */
function slider($options = array()) { function slider($options = array()) {
$callbacks = array('start', 'change', 'slide', 'stop'); $callbacks = array('start', 'change', 'slide', 'stop');
$template = '%s.slider({%s});'; $template = '%s.slider({%s});';
@ -322,7 +322,7 @@ class JqueryEngineHelper extends JsBaseEngineHelper {
* @param array $options Options for the serialization * @param array $options Options for the serialization
* @return string completed form serialization script * @return string completed form serialization script
* @see JsHelper::serializeForm() for option list. * @see JsHelper::serializeForm() for option list.
**/ */
function serializeForm($options = array()) { function serializeForm($options = array()) {
$options = array_merge(array('isForm' => false, 'inline' => false), $options); $options = array_merge(array('isForm' => false, 'inline' => false), $options);
$selector = $this->selection; $selector = $this->selection;

View file

@ -26,20 +26,20 @@
* *
* @package cake * @package cake
* @subpackage cake.cake.libs.view.helpers * @subpackage cake.cake.libs.view.helpers
**/ */
class JsHelper extends AppHelper { class JsHelper extends AppHelper {
/** /**
* Whether or not you want scripts to be buffered or output. * Whether or not you want scripts to be buffered or output.
* *
* @var boolean * @var boolean
**/ */
var $bufferScripts = true; var $bufferScripts = true;
/** /**
* helpers * helpers
* *
* @var array * @var array
**/ */
var $helpers = array('Html', 'Form'); var $helpers = array('Html', 'Form');
/** /**
@ -47,14 +47,14 @@ class JsHelper extends AppHelper {
* *
* @var array * @var array
* @see JsHelper::set() * @see JsHelper::set()
**/ */
var $__jsVars = array(); var $__jsVars = array();
/** /**
* Scripts that are queued for output * Scripts that are queued for output
* *
* @var array * @var array
**/ */
var $__bufferedScripts = array(); var $__bufferedScripts = array();
/** /**
@ -62,14 +62,14 @@ class JsHelper extends AppHelper {
* *
* @var string * @var string
* @access private * @access private
**/ */
var $__engineName; var $__engineName;
/** /**
* The javascript variable created by set() variables. * The javascript variable created by set() variables.
* *
* @var string * @var string
**/ */
var $setVariable = APP_DIR; var $setVariable = APP_DIR;
/** /**
@ -78,7 +78,7 @@ class JsHelper extends AppHelper {
* @param array $settings Settings array contains name of engine helper. * @param array $settings Settings array contains name of engine helper.
* @access public * @access public
* @return void * @return void
**/ */
function __construct($settings = array()) { function __construct($settings = array()) {
$className = 'Jquery'; $className = 'Jquery';
if (is_array($settings) && isset($settings[0])) { if (is_array($settings) && isset($settings[0])) {
@ -87,9 +87,8 @@ class JsHelper extends AppHelper {
$className = $settings; $className = $settings;
} }
$engineName = $className; $engineName = $className;
if (strpos($className, '.') !== false) { list($plugin, $className) = pluginSplit($className);
list($plugin, $className) = explode('.', $className);
}
$this->__engineName = $className . 'Engine'; $this->__engineName = $className . 'Engine';
$engineClass = $engineName . 'Engine'; $engineClass = $engineName . 'Engine';
$this->helpers[] = $engineClass; $this->helpers[] = $engineClass;
@ -115,7 +114,7 @@ class JsHelper extends AppHelper {
* @param array $params Parameters for the method being called. * @param array $params Parameters for the method being called.
* @access public * @access public
* @return mixed Depends on the return of the dispatched method, or it could be an instance of the EngineHelper * @return mixed Depends on the return of the dispatched method, or it could be an instance of the EngineHelper
**/ */
function call__($method, $params) { function call__($method, $params) {
if (isset($this->{$this->__engineName}) && method_exists($this->{$this->__engineName}, $method)) { if (isset($this->{$this->__engineName}) && method_exists($this->{$this->__engineName}, $method)) {
$buffer = false; $buffer = false;
@ -158,7 +157,7 @@ class JsHelper extends AppHelper {
* @param array $options Options to use for encoding JSON. See JsBaseEngineHelper::object() for more details. * @param array $options Options to use for encoding JSON. See JsBaseEngineHelper::object() for more details.
* @return string encoded JSON * @return string encoded JSON
* @deprecated Remove when support for PHP4 and Object::object are removed. * @deprecated Remove when support for PHP4 and Object::object are removed.
**/ */
function object($data = array(), $options = array()) { function object($data = array(), $options = array()) {
return $this->{$this->__engineName}->object($data, $options); return $this->{$this->__engineName}->object($data, $options);
} }
@ -178,7 +177,7 @@ class JsHelper extends AppHelper {
* *
* @param array $options options for the code block * @param array $options options for the code block
* @return string completed javascript tag. * @return string completed javascript tag.
**/ */
function writeBuffer($options = array()) { function writeBuffer($options = array()) {
$defaults = array('onDomReady' => true, 'inline' => true, 'cache' => false, 'clear' => true, 'safe' => true); $defaults = array('onDomReady' => true, 'inline' => true, 'cache' => false, 'clear' => true, 'safe' => true);
$options = array_merge($defaults, $options); $options = array_merge($defaults, $options);
@ -208,7 +207,7 @@ class JsHelper extends AppHelper {
* Write a script to the cached scripts. * Write a script to the cached scripts.
* *
* @return void * @return void
**/ */
function buffer($script) { function buffer($script) {
$this->__bufferedScripts[] = $script; $this->__bufferedScripts[] = $script;
} }
@ -218,7 +217,7 @@ class JsHelper extends AppHelper {
* *
* @param boolean $clear Whether or not to clear the script caches (default true) * @param boolean $clear Whether or not to clear the script caches (default true)
* @return array Array of scripts added to the request. * @return array Array of scripts added to the request.
**/ */
function getBuffer($clear = true) { function getBuffer($clear = true) {
$this->_createVars(); $this->_createVars();
$scripts = $this->__bufferedScripts; $scripts = $this->__bufferedScripts;
@ -233,7 +232,7 @@ class JsHelper extends AppHelper {
* Generates the object string for variables passed to javascript. * Generates the object string for variables passed to javascript.
* *
* @return string * @return string
**/ */
function _createVars() { function _createVars() {
if (!empty($this->__jsVars)) { if (!empty($this->__jsVars)) {
$setVar = (strpos($this->setVariable, '.')) ? $this->setVariable : 'var ' . $this->setVariable; $setVar = (strpos($this->setVariable, '.')) ? $this->setVariable : 'var ' . $this->setVariable;
@ -258,7 +257,7 @@ class JsHelper extends AppHelper {
* @param mixed $url Mixed either a string URL or an cake url array. * @param mixed $url Mixed either a string URL or an cake url array.
* @param array $options Options for both the HTML element and Js::request() * @param array $options Options for both the HTML element and Js::request()
* @return string Completed link. If buffering is disabled a script tag will be returned as well. * @return string Completed link. If buffering is disabled a script tag will be returned as well.
**/ */
function link($title, $url = null, $options = array()) { function link($title, $url = null, $options = array()) {
if (!isset($options['id'])) { if (!isset($options['id'])) {
$options['id'] = 'link-' . intval(mt_rand()); $options['id'] = 'link-' . intval(mt_rand());
@ -293,7 +292,7 @@ class JsHelper extends AppHelper {
* @param mixed $one * @param mixed $one
* @param mixed $two * @param mixed $two
* @return void * @return void
**/ */
function set($one, $two = null) { function set($one, $two = null) {
$data = null; $data = null;
if (is_array($one)) { if (is_array($one)) {
@ -322,7 +321,7 @@ class JsHelper extends AppHelper {
* @param string $title The display text of the submit button. * @param string $title The display text of the submit button.
* @param array $options Array of options to use. * @param array $options Array of options to use.
* @return string Completed submit button. * @return string Completed submit button.
**/ */
function submit($caption = null, $options = array()) { function submit($caption = null, $options = array()) {
if (!isset($options['id'])) { if (!isset($options['id'])) {
$options['id'] = 'submit-' . intval(mt_rand()); $options['id'] = 'submit-' . intval(mt_rand());
@ -364,7 +363,7 @@ class JsHelper extends AppHelper {
* @param array $options Options to filter. * @param array $options Options to filter.
* @param array $additional Array of additional keys to extract and include in the return options array. * @param array $additional Array of additional keys to extract and include in the return options array.
* @return array Array of options for non-js. * @return array Array of options for non-js.
**/ */
function _getHtmlOptions(&$options, $additional = array()) { function _getHtmlOptions(&$options, $additional = array()) {
$htmlKeys = array_merge(array('class', 'id', 'escape', 'onblur', 'onfocus', 'rel', 'title'), $additional); $htmlKeys = array_merge(array('class', 'id', 'escape', 'onblur', 'onfocus', 'rel', 'title'), $additional);
$htmlOptions = array(); $htmlOptions = array();
@ -388,14 +387,14 @@ class JsHelper extends AppHelper {
* Abstract Base Class for All JsEngines to extend. Provides generic methods. * Abstract Base Class for All JsEngines to extend. Provides generic methods.
* *
* @package cake.view.helpers * @package cake.view.helpers
**/ */
class JsBaseEngineHelper extends AppHelper { class JsBaseEngineHelper extends AppHelper {
/** /**
* Determines whether native JSON extension is used for encoding. Set by object constructor. * Determines whether native JSON extension is used for encoding. Set by object constructor.
* *
* @var boolean * @var boolean
* @access public * @access public
**/ */
var $useNative = false; var $useNative = false;
/** /**
@ -403,7 +402,7 @@ class JsBaseEngineHelper extends AppHelper {
* *
* @var string * @var string
* @access public * @access public
**/ */
var $selection; var $selection;
/** /**
@ -412,7 +411,7 @@ class JsBaseEngineHelper extends AppHelper {
* for end user use though. * for end user use though.
* *
* @var array * @var array
**/ */
var $_optionMap = array(); var $_optionMap = array();
/** /**
@ -420,21 +419,21 @@ class JsBaseEngineHelper extends AppHelper {
* This allows specific 'end point' methods to be automatically buffered by the JsHelper. * This allows specific 'end point' methods to be automatically buffered by the JsHelper.
* *
* @var array * @var array
**/ */
var $bufferedMethods = array('event', 'sortable', 'drag', 'drop', 'slider'); var $bufferedMethods = array('event', 'sortable', 'drag', 'drop', 'slider');
/** /**
* Contains a list of callback names -> default arguments. * Contains a list of callback names -> default arguments.
* *
* @var array * @var array
**/ */
var $_callbackArguments = array(); var $_callbackArguments = array();
/** /**
* Constructor. * Constructor.
* *
* @return void * @return void
**/ */
function __construct() { function __construct() {
$this->useNative = function_exists('json_encode'); $this->useNative = function_exists('json_encode');
} }
@ -445,7 +444,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $message Message you want to alter. * @param string $message Message you want to alter.
* @access public * @access public
* @return string completed alert() * @return string completed alert()
**/ */
function alert($message) { function alert($message) {
return 'alert("' . $this->escape($message) . '");'; return 'alert("' . $this->escape($message) . '");';
} }
@ -456,7 +455,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param mixed $url * @param mixed $url
* @param array $options * @param array $options
* @return string completed redirect in javascript * @return string completed redirect in javascript
**/ */
function redirect($url = null) { function redirect($url = null) {
return 'window.location = "' . Router::url($url) . '";'; return 'window.location = "' . Router::url($url) . '";';
} }
@ -467,7 +466,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $message Message you want confirmed. * @param string $message Message you want confirmed.
* @access public * @access public
* @return string completed confirm() * @return string completed confirm()
**/ */
function confirm($message) { function confirm($message) {
return 'confirm("' . $this->escape($message) . '");'; return 'confirm("' . $this->escape($message) . '");';
} }
@ -479,7 +478,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $message Message to use in the confirm dialog. * @param string $message Message to use in the confirm dialog.
* @access public * @access public
* @return string * @return string
**/ */
function confirmReturn($message) { function confirmReturn($message) {
$out = 'var _confirm = ' . $this->confirm($message); $out = 'var _confirm = ' . $this->confirm($message);
$out .= "if (!_confirm) {\n\treturn false;\n}"; $out .= "if (!_confirm) {\n\treturn false;\n}";
@ -493,7 +492,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $default Default message * @param string $default Default message
* @access public * @access public
* @return string completed prompt() * @return string completed prompt()
**/ */
function prompt($message, $default = '') { function prompt($message, $default = '') {
return 'prompt("' . $this->escape($message) . '", "' . $this->escape($default) . '");'; return 'prompt("' . $this->escape($message) . '", "' . $this->escape($default) . '");';
} }
@ -511,7 +510,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param array $options Set of options, see above. * @param array $options Set of options, see above.
* @return string A JSON code block * @return string A JSON code block
* @access public * @access public
**/ */
function object($data = array(), $options = array()) { function object($data = array(), $options = array()) {
$defaultOptions = array( $defaultOptions = array(
'prefix' => '', 'postfix' => '', 'prefix' => '', 'postfix' => '',
@ -571,7 +570,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param boolean $quoteStrings If false, leaves string values unquoted * @param boolean $quoteStrings If false, leaves string values unquoted
* @return string a JavaScript-safe/JSON representation of $val * @return string a JavaScript-safe/JSON representation of $val
* @access public * @access public
**/ */
function value($val, $quoteString = true) { function value($val, $quoteString = true) {
switch (true) { switch (true) {
case (is_array($val) || is_object($val)): case (is_array($val) || is_object($val)):
@ -611,7 +610,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $script String that needs to get escaped. * @param string $script String that needs to get escaped.
* @return string Escaped string. * @return string Escaped string.
* @access public * @access public
**/ */
function escape($string) { function escape($string) {
App::import('Core', 'Multibyte'); App::import('Core', 'Multibyte');
return $this->_utf8ToHex($string); return $this->_utf8ToHex($string);
@ -621,7 +620,7 @@ class JsBaseEngineHelper extends AppHelper {
* Encode a string into JSON. Converts and escapes necessary characters. * Encode a string into JSON. Converts and escapes necessary characters.
* *
* @return void * @return void
**/ */
function _utf8ToHex($string) { function _utf8ToHex($string) {
$length = strlen($string); $length = strlen($string);
$return = ''; $return = '';
@ -716,7 +715,7 @@ class JsBaseEngineHelper extends AppHelper {
* *
* @param string $selector The selector that is targeted * @param string $selector The selector that is targeted
* @return object instance of $this. Allows chained methods. * @return object instance of $this. Allows chained methods.
**/ */
function get($selector) { function get($selector) {
trigger_error(sprintf(__('%s does not have get() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have get() implemented', true), get_class($this)), E_USER_WARNING);
return $this; return $this;
@ -734,7 +733,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $callback The Javascript function you wish to trigger or the function literal * @param string $callback The Javascript function you wish to trigger or the function literal
* @param array $options Options for the event. * @param array $options Options for the event.
* @return string completed event handler * @return string completed event handler
**/ */
function event($type, $callback, $options = array()) { function event($type, $callback, $options = array()) {
trigger_error(sprintf(__('%s does not have event() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have event() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -744,7 +743,7 @@ class JsBaseEngineHelper extends AppHelper {
* *
* @param string $functionBody The code to run on domReady * @param string $functionBody The code to run on domReady
* @return string completed domReady method * @return string completed domReady method
**/ */
function domReady($functionBody) { function domReady($functionBody) {
trigger_error(sprintf(__('%s does not have domReady() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have domReady() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -754,7 +753,7 @@ class JsBaseEngineHelper extends AppHelper {
* *
* @param string $callback The function body you wish to apply during the iteration. * @param string $callback The function body you wish to apply during the iteration.
* @return string completed iteration * @return string completed iteration
**/ */
function each($callback) { function each($callback) {
trigger_error(sprintf(__('%s does not have each() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have each() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -781,7 +780,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $name The name of the effect to trigger. * @param string $name The name of the effect to trigger.
* @param array $options Array of options for the effect. * @param array $options Array of options for the effect.
* @return string completed string with effect. * @return string completed string with effect.
**/ */
function effect($name, $options) { function effect($name, $options) {
trigger_error(sprintf(__('%s does not have effect() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have effect() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -810,7 +809,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param mixed $url Array or String URL to target with the request. * @param mixed $url Array or String URL to target with the request.
* @param array $options Array of options. See above for cross library supported options * @param array $options Array of options. See above for cross library supported options
* @return string XHR request. * @return string XHR request.
**/ */
function request($url, $options = array()) { function request($url, $options = array()) {
trigger_error(sprintf(__('%s does not have request() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have request() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -833,7 +832,7 @@ class JsBaseEngineHelper extends AppHelper {
* *
* @param array $options Options array see above. * @param array $options Options array see above.
* @return string Completed drag script * @return string Completed drag script
**/ */
function drag($options = array()) { function drag($options = array()) {
trigger_error(sprintf(__('%s does not have drag() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have drag() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -854,7 +853,7 @@ class JsBaseEngineHelper extends AppHelper {
* - `leave` - Event fired when a drag is removed from a drop zone without being dropped. * - `leave` - Event fired when a drag is removed from a drop zone without being dropped.
* *
* @return string Completed drop script * @return string Completed drop script
**/ */
function drop($options = array()) { function drop($options = array()) {
trigger_error(sprintf(__('%s does not have drop() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have drop() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -878,7 +877,7 @@ class JsBaseEngineHelper extends AppHelper {
* *
* @param array $options Array of options for the sortable. See above. * @param array $options Array of options for the sortable. See above.
* @return string Completed sortable script. * @return string Completed sortable script.
**/ */
function sortable() { function sortable() {
trigger_error(sprintf(__('%s does not have sortable() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have sortable() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -901,7 +900,7 @@ class JsBaseEngineHelper extends AppHelper {
* - `complete` - Fired when the user stops sliding the handle * - `complete` - Fired when the user stops sliding the handle
* *
* @return string Completed slider script * @return string Completed slider script
**/ */
function slider() { function slider() {
trigger_error(sprintf(__('%s does not have slider() implemented', true), get_class($this)), E_USER_WARNING); trigger_error(sprintf(__('%s does not have slider() implemented', true), get_class($this)), E_USER_WARNING);
} }
@ -919,7 +918,7 @@ class JsBaseEngineHelper extends AppHelper {
* *
* @param array $options options for serialization generation. * @param array $options options for serialization generation.
* @return string completed form serialization script * @return string completed form serialization script
**/ */
function serializeForm() { function serializeForm() {
trigger_error( trigger_error(
sprintf(__('%s does not have serializeForm() implemented', true), get_class($this)), E_USER_WARNING sprintf(__('%s does not have serializeForm() implemented', true), get_class($this)), E_USER_WARNING
@ -935,7 +934,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param array $safeKeys Keys that should not be escaped. * @param array $safeKeys Keys that should not be escaped.
* @return string * @return string
* @access protected * @access protected
**/ */
function _parseOptions($options, $safeKeys = array()) { function _parseOptions($options, $safeKeys = array()) {
$out = array(); $out = array();
$safeKeys = array_flip($safeKeys); $safeKeys = array_flip($safeKeys);
@ -957,7 +956,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param array $options Array of options to map. * @param array $options Array of options to map.
* @return array Array of mapped options. * @return array Array of mapped options.
* @access protected * @access protected
**/ */
function _mapOptions($method, $options) { function _mapOptions($method, $options) {
if (!isset($this->_optionMap[$method])) { if (!isset($this->_optionMap[$method])) {
return $options; return $options;
@ -980,7 +979,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $callbacks Additional Keys that contain callbacks * @param string $callbacks Additional Keys that contain callbacks
* @access protected * @access protected
* @return array Array of options with callbacks added. * @return array Array of options with callbacks added.
**/ */
function _prepareCallbacks($method, $options, $callbacks = array()) { function _prepareCallbacks($method, $options, $callbacks = array()) {
$wrapCallbacks = true; $wrapCallbacks = true;
if (isset($options['wrapCallbacks'])) { if (isset($options['wrapCallbacks'])) {
@ -1016,7 +1015,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param string $method Name of method processing options for. * @param string $method Name of method processing options for.
* @param array $options Array of options to process. * @param array $options Array of options to process.
* @return string Parsed options string. * @return string Parsed options string.
**/ */
function _processOptions($method, $options) { function _processOptions($method, $options) {
$options = $this->_mapOptions($method, $options); $options = $this->_mapOptions($method, $options);
$options = $this->_prepareCallbacks($method, $options); $options = $this->_prepareCallbacks($method, $options);
@ -1030,7 +1029,7 @@ class JsBaseEngineHelper extends AppHelper {
* @param array $parameters Array of parameters to convert to a query string * @param array $parameters Array of parameters to convert to a query string
* @return string Querystring fragment * @return string Querystring fragment
* @access protected * @access protected
**/ */
function _toQuerystring($parameters) { function _toQuerystring($parameters) {
$out = ''; $out = '';
$keys = array_keys($parameters); $keys = array_keys($parameters);

View file

@ -32,7 +32,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* Option mappings for MooTools * Option mappings for MooTools
* *
* @var array * @var array
**/ */
var $_optionMap = array( var $_optionMap = array(
'request' => array( 'request' => array(
'complete' => 'onComplete', 'complete' => 'onComplete',
@ -70,7 +70,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* Contains a list of callback names -> default arguments. * Contains a list of callback names -> default arguments.
* *
* @var array * @var array
**/ */
var $_callbackArguments = array( var $_callbackArguments = array(
'slider' => array( 'slider' => array(
'onTick' => 'position', 'onTick' => 'position',
@ -116,7 +116,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* *
* @param string $selector The selector that is targeted * @param string $selector The selector that is targeted
* @return object instance of $this. Allows chained methods. * @return object instance of $this. Allows chained methods.
**/ */
function get($selector) { function get($selector) {
$this->_multipleSelection = false; $this->_multipleSelection = false;
if ($selector == 'window' || $selector == 'document') { if ($selector == 'window' || $selector == 'document') {
@ -144,7 +144,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param string $callback The Javascript function you wish to trigger or the function literal * @param string $callback The Javascript function you wish to trigger or the function literal
* @param array $options Options for the event. * @param array $options Options for the event.
* @return string completed event handler * @return string completed event handler
**/ */
function event($type, $callback, $options = array()) { function event($type, $callback, $options = array()) {
$defaults = array('wrap' => true, 'stop' => true); $defaults = array('wrap' => true, 'stop' => true);
$options = array_merge($defaults, $options); $options = array_merge($defaults, $options);
@ -165,7 +165,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* *
* @param string $functionBody The code to run on domReady * @param string $functionBody The code to run on domReady
* @return string completed domReady method * @return string completed domReady method
**/ */
function domReady($functionBody) { function domReady($functionBody) {
$this->selection = 'window'; $this->selection = 'window';
return $this->event('domready', $functionBody, array('stop' => false)); return $this->event('domready', $functionBody, array('stop' => false));
@ -177,7 +177,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param string $method The method you want to apply to the selection * @param string $method The method you want to apply to the selection
* @param string $callback The function body you wish to apply during the iteration. * @param string $callback The function body you wish to apply during the iteration.
* @return string completed iteration * @return string completed iteration
**/ */
function each($callback) { function each($callback) {
return $this->selection . '.each(function (item, index) {' . $callback . '});'; return $this->selection . '.each(function (item, index) {' . $callback . '});';
} }
@ -189,7 +189,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the effect. * @param array $options Array of options for the effect.
* @return string completed string with effect. * @return string completed string with effect.
* @see JsBaseEngineHelper::effect() * @see JsBaseEngineHelper::effect()
**/ */
function effect($name, $options = array()) { function effect($name, $options = array()) {
$speed = null; $speed = null;
if (isset($options['speed']) && in_array($options['speed'], array('fast', 'slow'))) { if (isset($options['speed']) && in_array($options['speed'], array('fast', 'slow'))) {
@ -231,7 +231,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param mixed $url * @param mixed $url
* @param array $options * @param array $options
* @return string The completed ajax call. * @return string The completed ajax call.
**/ */
function request($url, $options = array()) { function request($url, $options = array()) {
$url = $this->url($url); $url = $this->url($url);
$options = $this->_mapOptions('request', $options); $options = $this->_mapOptions('request', $options);
@ -270,7 +270,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the sortable. * @param array $options Array of options for the sortable.
* @return string Completed sortable script. * @return string Completed sortable script.
* @see JsHelper::sortable() for options list. * @see JsHelper::sortable() for options list.
**/ */
function sortable($options = array()) { function sortable($options = array()) {
$options = $this->_processOptions('sortable', $options); $options = $this->_processOptions('sortable', $options);
return 'var jsSortable = new Sortables(' . $this->selection . ', {' . $options . '});'; return 'var jsSortable = new Sortables(' . $this->selection . ', {' . $options . '});';
@ -284,7 +284,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the draggable. * @param array $options Array of options for the draggable.
* @return string Completed draggable script. * @return string Completed draggable script.
* @see JsHelper::drag() for options list. * @see JsHelper::drag() for options list.
**/ */
function drag($options = array()) { function drag($options = array()) {
$options = $this->_processOptions('drag', $options); $options = $this->_processOptions('drag', $options);
return $this->selection . '.makeDraggable({' . $options . '});'; return $this->selection . '.makeDraggable({' . $options . '});';
@ -303,7 +303,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the droppable. * @param array $options Array of options for the droppable.
* @return string Completed droppable script. * @return string Completed droppable script.
* @see JsHelper::drop() for options list. * @see JsHelper::drop() for options list.
**/ */
function drop($options = array()) { function drop($options = array()) {
if (empty($options['drag'])) { if (empty($options['drag'])) {
trigger_error( trigger_error(
@ -333,7 +333,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the slider. * @param array $options Array of options for the slider.
* @return string Completed slider script. * @return string Completed slider script.
* @see JsHelper::slider() for options list. * @see JsHelper::slider() for options list.
**/ */
function slider($options = array()) { function slider($options = array()) {
$slider = $this->selection; $slider = $this->selection;
$this->get($options['handle']); $this->get($options['handle']);
@ -358,7 +358,7 @@ class MootoolsEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options. * @param array $options Array of options.
* @return string Completed serializeForm() snippet * @return string Completed serializeForm() snippet
* @see JsHelper::serializeForm() * @see JsHelper::serializeForm()
**/ */
function serializeForm($options = array()) { function serializeForm($options = array()) {
$options = array_merge(array('isForm' => false, 'inline' => false), $options); $options = array_merge(array('isForm' => false, 'inline' => false), $options);
$selection = $this->selection; $selection = $this->selection;

View file

@ -36,7 +36,7 @@ class NumberHelper extends AppHelper {
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_currencies = array( var $_currencies = array(
'USD' => array( 'USD' => array(
'before' => '$', 'after' => 'c', 'zero' => 0, 'places' => 2, 'thousands' => ',', 'before' => '$', 'after' => 'c', 'zero' => 0, 'places' => 2, 'thousands' => ',',
@ -57,7 +57,7 @@ class NumberHelper extends AppHelper {
* *
* @var array * @var array
* @access protected * @access protected
**/ */
var $_currencyDefaults = array( var $_currencyDefaults = array(
'before'=>'', 'after' => '', 'zero' => '0', 'places' => 2, 'thousands' => ',', 'before'=>'', 'after' => '', 'zero' => '0', 'places' => 2, 'thousands' => ',',
'decimals' => '.','negative' => '()', 'escape' => true 'decimals' => '.','negative' => '()', 'escape' => true
@ -222,7 +222,7 @@ class NumberHelper extends AppHelper {
* @param string $formatName The format name to be used in the future. * @param string $formatName The format name to be used in the future.
* @param array $options The array of options for this format. * @param array $options The array of options for this format.
* @return void * @return void
**/ */
function addFormat($formatName, $options) { function addFormat($formatName, $options) {
$this->_currencies[$formatName] = $options + $this->_currencyDefaults; $this->_currencies[$formatName] = $options + $this->_currencyDefaults;
} }

View file

@ -46,7 +46,7 @@ class PaginatorHelper extends AppHelper {
* The class used for 'Ajax' pagination links. * The class used for 'Ajax' pagination links.
* *
* @var string * @var string
**/ */
var $_ajaxHelperClass = 'Js'; var $_ajaxHelperClass = 'Js';
/** /**
@ -54,20 +54,20 @@ class PaginatorHelper extends AppHelper {
* *
* The values that may be specified are: * The values that may be specified are:
* *
* - <i>$options['format']</i> Format of the counter. Supported formats are 'range' and 'pages' * - `$options['format']` Format of the counter. Supported formats are 'range' and 'pages'
* and custom (default). In the default mode the supplied string is parsed and constants are replaced * and custom (default). In the default mode the supplied string is parsed and constants are replaced
* by their actual values. * by their actual values.
* Constants: %page%, %pages%, %current%, %count%, %start%, %end% . * Constants: %page%, %pages%, %current%, %count%, %start%, %end% .
* - <i>$options['separator']</i> The separator of the actual page and number of pages (default: ' of '). * - `$options['separator']` The separator of the actual page and number of pages (default: ' of ').
* - <i>$options['url']</i> Url of the action. See Router::url() * - `$options['url']` Url of the action. See Router::url()
* - <i>$options['url']['sort']</i> the key that the recordset is sorted. * - `$options['url']['sort']` the key that the recordset is sorted.
* - <i>$options['url']['direction']</i> Direction of the sorting (default: 'asc'). * - `$options['url']['direction']` Direction of the sorting (default: 'asc').
* - <i>$options['url']['page']</i> Page # to display. * - `$options['url']['page']` Page # to display.
* - <i>$options['model']</i> The name of the model. * - `$options['model']` The name of the model.
* - <i>$options['escape']</i> Defines if the title field for the link should be escaped (default: true). * - `$options['escape']` Defines if the title field for the link should be escaped (default: true).
* - <i>$options['update']</i> DOM id of the element updated with the results of the AJAX call. * - `$options['update']` DOM id of the element updated with the results of the AJAX call.
* If this key isn't specified Paginator will use plain HTML links. * If this key isn't specified Paginator will use plain HTML links.
* - <i>$options['indicator']</i> DOM id of the element that will be shown when doing AJAX requests. * - `$options['indicator']` DOM id of the element that will be shown when doing AJAX requests.
* *
* @var array * @var array
*/ */
@ -83,7 +83,7 @@ class PaginatorHelper extends AppHelper {
* The chosen custom helper must implement a `link()` method. * The chosen custom helper must implement a `link()` method.
* *
* @return void * @return void
**/ */
function __construct($config = array()) { function __construct($config = array()) {
$ajaxProvider = isset($config['ajax']) ? $config['ajax'] : 'Js'; $ajaxProvider = isset($config['ajax']) ? $config['ajax'] : 'Js';
$this->helpers[] = $ajaxProvider; $this->helpers[] = $ajaxProvider;
@ -112,7 +112,7 @@ class PaginatorHelper extends AppHelper {
/** /**
* Gets the current paging parameters from the resultset for the given model * Gets the current paging parameters from the resultset for the given model
* *
* @param string $model Optional model name. Uses the default if none is specified. * @param string $model Optional model name. Uses the default if none is specified.
* @return array The array of paging parameters for the paginated resultset. * @return array The array of paging parameters for the paginated resultset.
*/ */
function params($model = null) { function params($model = null) {
@ -128,7 +128,7 @@ class PaginatorHelper extends AppHelper {
/** /**
* Sets default options for all pagination links * Sets default options for all pagination links
* *
* @param mixed $options Default options for pagination links. If a string is supplied - it * @param mixed $options Default options for pagination links. If a string is supplied - it
* is used as the DOM id element to update. See #options for list of keys. * is used as the DOM id element to update. See #options for list of keys.
*/ */
function options($options = array()) { function options($options = array()) {
@ -160,7 +160,7 @@ class PaginatorHelper extends AppHelper {
/** /**
* Gets the current page of the recordset for the given model * Gets the current page of the recordset for the given model
* *
* @param string $model Optional model name. Uses the default if none is specified. * @param string $model Optional model name. Uses the default if none is specified.
* @return string The current page number of the recordset. * @return string The current page number of the recordset.
*/ */
function current($model = null) { function current($model = null) {
@ -175,8 +175,8 @@ class PaginatorHelper extends AppHelper {
/** /**
* Gets the current key by which the recordset is sorted * Gets the current key by which the recordset is sorted
* *
* @param string $model Optional model name. Uses the default if none is specified. * @param string $model Optional model name. Uses the default if none is specified.
* @param mixed $options Options for pagination links. See #options for list of keys. * @param mixed $options Options for pagination links. See #options for list of keys.
* @return string The name of the key by which the recordset is being sorted, or * @return string The name of the key by which the recordset is being sorted, or
* null if the results are not currently sorted. * null if the results are not currently sorted.
*/ */
@ -207,8 +207,8 @@ class PaginatorHelper extends AppHelper {
/** /**
* Gets the current direction the recordset is sorted * Gets the current direction the recordset is sorted
* *
* @param string $model Optional model name. Uses the default if none is specified. * @param string $model Optional model name. Uses the default if none is specified.
* @param mixed $options Options for pagination links. See #options for list of keys. * @param mixed $options Options for pagination links. See #options for list of keys.
* @return string The direction by which the recordset is being sorted, or * @return string The direction by which the recordset is being sorted, or
* null if the results are not currently sorted. * null if the results are not currently sorted.
*/ */
@ -235,6 +235,12 @@ class PaginatorHelper extends AppHelper {
/** /**
* Generates a "previous" link for a set of paged records * Generates a "previous" link for a set of paged records
* *
* Options:
*
* - `tag` The tag wrapping tag you want to use, defaults to 'span'
* - `escape` Whether you want the contents html entity encoded, defaults to true
* - `model` The model to use, defaults to PaginatorHelper::defaultModel()
*
* @param string $title Title for the link. Defaults to '<< Previous'. * @param string $title Title for the link. Defaults to '<< Previous'.
* @param mixed $options Options for pagination link. See #options for list of keys. * @param mixed $options Options for pagination link. See #options for list of keys.
* @param string $disabledTitle Title when the link is disabled. * @param string $disabledTitle Title when the link is disabled.
@ -248,10 +254,16 @@ class PaginatorHelper extends AppHelper {
/** /**
* Generates a "next" link for a set of paged records * Generates a "next" link for a set of paged records
* *
* @param string $title Title for the link. Defaults to 'Next >>'. * Options:
* @param mixed $options Options for pagination link. See #options for list of keys. *
* @param string $disabledTitle Title when the link is disabled. * - `tag` The tag wrapping tag you want to use, defaults to 'span'
* @param mixed $disabledOptions Options for the disabled pagination link. See #options for list of keys. * - `escape` Whether you want the contents html entity encoded, defaults to true
* - `model` The model to use, defaults to PaginatorHelper::defaultModel()
*
* @param string $title Title for the link. Defaults to 'Next >>'.
* @param mixed $options Options for pagination link. See above for list of keys.
* @param string $disabledTitle Title when the link is disabled.
* @param mixed $disabledOptions Options for the disabled pagination link. See above for list of keys.
* @return string A "next" link or or $disabledTitle text if the link is disabled. * @return string A "next" link or or $disabledTitle text if the link is disabled.
*/ */
function next($title = 'Next >>', $options = array(), $disabledTitle = null, $disabledOptions = array()) { function next($title = 'Next >>', $options = array(), $disabledTitle = null, $disabledOptions = array()) {
@ -262,10 +274,15 @@ class PaginatorHelper extends AppHelper {
* Generates a sorting link. Sets named parameters for the sort and direction. Handles * Generates a sorting link. Sets named parameters for the sort and direction. Handles
* direction switching automatically. * direction switching automatically.
* *
* Options:
*
* - `escape` Whether you want the contents html entity encoded, defaults to true
* - `model` The model to use, defaults to PaginatorHelper::defaultModel()
*
* @param string $title Title for the link. * @param string $title Title for the link.
* @param string $key The name of the key that the recordset should be sorted. If $key is null * @param string $key The name of the key that the recordset should be sorted. If $key is null
* $title will be used for the key, and a title will be generated by inflection. * $title will be used for the key, and a title will be generated by inflection.
* @param array $options Options for sorting link. See #options for list of keys. * @param array $options Options for sorting link. See above for list of keys.
* @return string A link sorting default by 'asc'. If the resultset is sorted 'asc' by the specified * @return string A link sorting default by 'asc'. If the resultset is sorted 'asc' by the specified
* key the returned link will sort by 'desc'. * key the returned link will sort by 'desc'.
*/ */
@ -285,9 +302,7 @@ class PaginatorHelper extends AppHelper {
$isSorted = ($sortKey === $key || $sortKey === $this->defaultModel() . '.' . $key); $isSorted = ($sortKey === $key || $sortKey === $this->defaultModel() . '.' . $key);
if ($isSorted) { if ($isSorted) {
if ($this->sortDir($options['model']) === 'asc') { $dir = $this->sortDir($options['model']) === 'asc' ? 'desc' : 'asc';
$dir = 'desc';
}
$class = $dir === 'asc' ? 'desc' : 'asc'; $class = $dir === 'asc' ? 'desc' : 'asc';
if (!empty($options['class'])) { if (!empty($options['class'])) {
$options['class'] .= $class; $options['class'] .= $class;
@ -306,9 +321,16 @@ class PaginatorHelper extends AppHelper {
/** /**
* Generates a plain or Ajax link with pagination parameters * Generates a plain or Ajax link with pagination parameters
* *
* @param string $title Title for the link. * Options
* @param mixed $url Url for the action. See Router::url() *
* @param array $options Options for the link. See #options for list of keys. * - `update` The Id of the DOM element you wish to update. Creates Ajax enabled links
* with the AjaxHelper.
* - `escape` Whether you want the contents html entity encoded, defaults to true
* - `model` The model to use, defaults to PaginatorHelper::defaultModel()
*
* @param string $title Title for the link.
* @param mixed $url Url for the action. See Router::url()
* @param array $options Options for the link. See #options for list of keys.
* @return string A link with pagination parameters. * @return string A link with pagination parameters.
*/ */
function link($title, $url = array(), $options = array()) { function link($title, $url = array(), $options = array()) {
@ -334,9 +356,9 @@ class PaginatorHelper extends AppHelper {
/** /**
* Merges passed URL options with current pagination state to generate a pagination URL. * Merges passed URL options with current pagination state to generate a pagination URL.
* *
* @param array $options Pagination/URL options array * @param array $options Pagination/URL options array
* @param boolean $asArray * @param boolean $asArray Return the url as an array, or a URI string
* @param string $model Which model to paginate on * @param string $model Which model to paginate on
* @return mixed By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript) * @return mixed By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript)
*/ */
function url($options = array(), $asArray = false, $model = null) { function url($options = array(), $asArray = false, $model = null) {
@ -401,7 +423,7 @@ class PaginatorHelper extends AppHelper {
/** /**
* Returns true if the given result set is not at the first page * Returns true if the given result set is not at the first page
* *
* @param string $model Optional model name. Uses the default if none is specified. * @param string $model Optional model name. Uses the default if none is specified.
* @return boolean True if the result set is not at the first page. * @return boolean True if the result set is not at the first page.
*/ */
function hasPrev($model = null) { function hasPrev($model = null) {
@ -421,8 +443,8 @@ class PaginatorHelper extends AppHelper {
/** /**
* Returns true if the given result set has the page number given by $page * Returns true if the given result set has the page number given by $page
* *
* @param string $model Optional model name. Uses the default if none is specified. * @param string $model Optional model name. Uses the default if none is specified.
* @param int $page The page number - if not set defaults to 1. * @param int $page The page number - if not set defaults to 1.
* @return boolean True if the given result set has the specified page number. * @return boolean True if the given result set has the specified page number.
*/ */
function hasPage($model = null, $page = 1) { function hasPage($model = null, $page = 1) {
@ -467,8 +489,16 @@ class PaginatorHelper extends AppHelper {
/** /**
* Returns a counter string for the paged result set * Returns a counter string for the paged result set
* *
* @param mixed $options Options for the counter string. See #options for list of keys. * Options
* @todo See about deprecating the keys in $map for formatting *
* - `model` The model to use, defaults to PaginatorHelper::defaultModel();
* - `format` The format string you want to use, defaults to 'pages' Which generates output like '1 of 5'
* set to 'range' to generate output like '1 - 3 of 13'. Can also be set to a custom string, containing
* the following placeholders `%page%`, `%pages%`, `%current%`, `%count%`, `%start%`, `%end%` and any
* custom content you would like.
* - `separator` The separator string to use, default to ' of '
*
* @param mixed $options Options for the counter string. See #options for list of keys.
* @return string Counter string. * @return string Counter string.
*/ */
function counter($options = array()) { function counter($options = array()) {
@ -480,7 +510,7 @@ class PaginatorHelper extends AppHelper {
array( array(
'model' => $this->defaultModel(), 'model' => $this->defaultModel(),
'format' => 'pages', 'format' => 'pages',
'separator' => ' of ' 'separator' => __(' of ', true)
), ),
$options); $options);
@ -525,14 +555,27 @@ class PaginatorHelper extends AppHelper {
$out = str_replace($newKeys, array_values($map), $out); $out = str_replace($newKeys, array_values($map), $out);
break; break;
} }
return $this->output($out); return $out;
} }
/** /**
* Returns a set of numbers for the paged result set * Returns a set of numbers for the paged result set
* uses a modulus to decide how many numbers to show on each side of the current page (default: 8) * uses a modulus to decide how many numbers to show on each side of the current page (default: 8)
* *
* @param mixed $options Options for the numbers, (before, after, model, modulus, separator) * Options
*
* - `before` Content to be inserted before the numbers
* - `after` Content to be inserted after the numbers
* - `model` Model to create numbers for, defaults to PaginatorHelper::defaultModel()
* - `modulus` how many numbers to include on either side of the current page, defaults to 8.
* - `separator` Separator content defaults to ' | '
* - `tag` The tag to wrap links in, defaults to 'span'
* - `first` Whether you want first links generated, set to an integer to define the number of 'first'
* links to generate
* - `last` Whether you want last links generated, set to an integer to define the number of 'last'
* links to generate
*
* @param mixed $options Options for the numbers, (before, after, model, modulus, separator)
* @return string numbers string. * @return string numbers string.
*/ */
function numbers($options = array()) { function numbers($options = array()) {
@ -633,14 +676,21 @@ class PaginatorHelper extends AppHelper {
$out .= $after; $out .= $after;
} }
return $this->output($out); return $out;
} }
/** /**
* Returns a first or set of numbers for the first pages * Returns a first or set of numbers for the first pages
* *
* @param mixed $first if string use as label for the link, if numeric print page numbers * Options:
* @param mixed $options *
* - `tag` The tag wrapping tag you want to use, defaults to 'span'
* - `before` Content to insert before the link/tag
* - `model` The model to use defaults to PaginatorHelper::defaultModel()
* - `separator` Content between the generated links, defaults to ' | '
*
* @param mixed $first if string use as label for the link, if numeric print page numbers
* @param mixed $options
* @return string numbers string. * @return string numbers string.
*/ */
function first($first = '<< first', $options = array()) { function first($first = '<< first', $options = array()) {
@ -685,8 +735,15 @@ class PaginatorHelper extends AppHelper {
/** /**
* Returns a last or set of numbers for the last pages * Returns a last or set of numbers for the last pages
* *
* @param mixed $last if string use as label for the link, if numeric print page numbers * Options:
* @param mixed $options *
* - `tag` The tag wrapping tag you want to use, defaults to 'span'
* - `before` Content to insert before the link/tag
* - `model` The model to use defaults to PaginatorHelper::defaultModel()
* - `separator` Content between the generated links, defaults to ' | '
*
* @param mixed $last if string use as label for the link, if numeric print page numbers
* @param mixed $options Array of options
* @return string numbers string. * @return string numbers string.
*/ */
function last($last = 'last >>', $options = array()) { function last($last = 'last >>', $options = array()) {

View file

@ -27,13 +27,13 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* Is the current selection a multiple selection? or is it just a single element. * Is the current selection a multiple selection? or is it just a single element.
* *
* @var boolean * @var boolean
**/ */
var $_multiple = false; var $_multiple = false;
/** /**
* Option mappings for Prototype * Option mappings for Prototype
* *
* @var array * @var array
**/ */
var $_optionMap = array( var $_optionMap = array(
'request' => array( 'request' => array(
'async' => 'asynchronous', 'async' => 'asynchronous',
@ -73,7 +73,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* Contains a list of callback names -> default arguments. * Contains a list of callback names -> default arguments.
* *
* @var array * @var array
**/ */
var $_callbackArguments = array( var $_callbackArguments = array(
'slider' => array( 'slider' => array(
'onSlide' => 'value', 'onSlide' => 'value',
@ -108,7 +108,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* *
* @param string $selector The selector that is targeted * @param string $selector The selector that is targeted
* @return object instance of $this. Allows chained methods. * @return object instance of $this. Allows chained methods.
**/ */
function get($selector) { function get($selector) {
$this->_multiple = false; $this->_multiple = false;
if ($selector == 'window' || $selector == 'document') { if ($selector == 'window' || $selector == 'document') {
@ -135,7 +135,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param string $callback The Javascript function you wish to trigger or the function literal * @param string $callback The Javascript function you wish to trigger or the function literal
* @param array $options Options for the event. * @param array $options Options for the event.
* @return string completed event handler * @return string completed event handler
**/ */
function event($type, $callback, $options = array()) { function event($type, $callback, $options = array()) {
$defaults = array('wrap' => true, 'stop' => true); $defaults = array('wrap' => true, 'stop' => true);
$options = array_merge($defaults, $options); $options = array_merge($defaults, $options);
@ -155,7 +155,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* *
* @param string $functionBody The code to run on domReady * @param string $functionBody The code to run on domReady
* @return string completed domReady method * @return string completed domReady method
**/ */
function domReady($functionBody) { function domReady($functionBody) {
$this->selection = 'document'; $this->selection = 'document';
return $this->event('dom:loaded', $functionBody, array('stop' => false)); return $this->event('dom:loaded', $functionBody, array('stop' => false));
@ -166,7 +166,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param string $method The method you want to apply to the selection * @param string $method The method you want to apply to the selection
* @param string $callback The function body you wish to apply during the iteration. * @param string $callback The function body you wish to apply during the iteration.
* @return string completed iteration * @return string completed iteration
**/ */
function each($callback) { function each($callback) {
return $this->selection . '.each(function (item, index) {' . $callback . '});'; return $this->selection . '.each(function (item, index) {' . $callback . '});';
} }
@ -179,7 +179,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the effect. * @param array $options Array of options for the effect.
* @return string completed string with effect. * @return string completed string with effect.
* @see JsBaseEngineHelper::effect() * @see JsBaseEngineHelper::effect()
**/ */
function effect($name, $options = array()) { function effect($name, $options = array()) {
$effect = ''; $effect = '';
$optionString = null; $optionString = null;
@ -220,7 +220,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param mixed $url * @param mixed $url
* @param array $options * @param array $options
* @return string The completed ajax call. * @return string The completed ajax call.
**/ */
function request($url, $options = array()) { function request($url, $options = array()) {
$url = '"'. $this->url($url) . '"'; $url = '"'. $this->url($url) . '"';
$options = $this->_mapOptions('request', $options); $options = $this->_mapOptions('request', $options);
@ -255,7 +255,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the sortable. * @param array $options Array of options for the sortable.
* @return string Completed sortable script. * @return string Completed sortable script.
* @see JsHelper::sortable() for options list. * @see JsHelper::sortable() for options list.
**/ */
function sortable($options = array()) { function sortable($options = array()) {
$options = $this->_processOptions('sortable', $options); $options = $this->_processOptions('sortable', $options);
if (!empty($options)) { if (!empty($options)) {
@ -271,7 +271,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the draggable. * @param array $options Array of options for the draggable.
* @return string Completed draggable script. * @return string Completed draggable script.
* @see JsHelper::draggable() for options list. * @see JsHelper::draggable() for options list.
**/ */
function drag($options = array()) { function drag($options = array()) {
$options = $this->_processOptions('drag', $options); $options = $this->_processOptions('drag', $options);
if (!empty($options)) { if (!empty($options)) {
@ -290,7 +290,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the droppable. * @param array $options Array of options for the droppable.
* @return string Completed droppable script. * @return string Completed droppable script.
* @see JsHelper::droppable() for options list. * @see JsHelper::droppable() for options list.
**/ */
function drop($options = array()) { function drop($options = array()) {
$options = $this->_processOptions('drop', $options); $options = $this->_processOptions('drop', $options);
if (!empty($options)) { if (!empty($options)) {
@ -306,7 +306,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options for the slider. * @param array $options Array of options for the slider.
* @return string Completed slider script. * @return string Completed slider script.
* @see JsHelper::slider() for options list. * @see JsHelper::slider() for options list.
**/ */
function slider($options = array()) { function slider($options = array()) {
$slider = $this->selection; $slider = $this->selection;
$this->get($options['handle']); $this->get($options['handle']);
@ -330,7 +330,7 @@ class PrototypeEngineHelper extends JsBaseEngineHelper {
* @param array $options Array of options. * @param array $options Array of options.
* @return string Completed serializeForm() snippet * @return string Completed serializeForm() snippet
* @see JsHelper::serializeForm() * @see JsHelper::serializeForm()
**/ */
function serializeForm($options = array()) { function serializeForm($options = array()) {
$options = array_merge(array('isForm' => false, 'inline' => false), $options); $options = array_merge(array('isForm' => false, 'inline' => false), $options);
$selection = $this->selection; $selection = $this->selection;

View file

@ -34,7 +34,7 @@ class RssHelper extends XmlHelper {
* *
* @var array * @var array
* @access public * @access public
**/ */
var $helpers = array('Time'); var $helpers = array('Time');
/** /**
@ -269,7 +269,7 @@ class RssHelper extends XmlHelper {
if (!empty($elements)) { if (!empty($elements)) {
$content = join('', $elements); $content = join('', $elements);
} }
return $this->output($this->elem('item', $att, $content, !($content === null))); return $this->elem('item', $att, $content, !($content === null));
} }
/** /**

View file

@ -125,10 +125,12 @@ class SessionHelper extends CakeSession {
* Will default to flash if no param is passed * Will default to flash if no param is passed
* *
* @param string $key The [Message.]key you are rendering in the view. * @param string $key The [Message.]key you are rendering in the view.
* @return string Will echo the value if $key is set, or false if not set. * @return boolean|string Will return the value if $key is set, or false if not set.
* @access public * @access public
*/ */
function flash($key = 'flash') { function flash($key = 'flash') {
$out = false;
if ($this->__active === true && $this->__start()) { if ($this->__active === true && $this->__start()) {
if (parent::check('Message.' . $key)) { if (parent::check('Message.' . $key)) {
$flash = parent::read('Message.' . $key); $flash = parent::read('Message.' . $key);
@ -148,12 +150,10 @@ class SessionHelper extends CakeSession {
$tmpVars['message'] = $flash['message']; $tmpVars['message'] = $flash['message'];
$out = $view->element($flash['element'], $tmpVars); $out = $view->element($flash['element'], $tmpVars);
} }
echo($out);
parent::delete('Message.' . $key); parent::delete('Message.' . $key);
return true;
} }
} }
return false; return $out;
} }
/** /**

View file

@ -87,8 +87,7 @@ class TimeHelper extends AppHelper {
$date = time(); $date = time();
} }
$ret = date("D, M jS Y, H:i", $date); return date("D, M jS Y, H:i", $date);
return $this->output($ret);
} }
/** /**
@ -115,8 +114,7 @@ class TimeHelper extends AppHelper {
} else { } else {
$ret = date("M jS{$y}, H:i", $date); $ret = date("M jS{$y}, H:i", $date);
} }
return $ret;
return $this->output($ret);
} }
/** /**
@ -134,8 +132,7 @@ class TimeHelper extends AppHelper {
$begin = date('Y-m-d', $begin) . ' 00:00:00'; $begin = date('Y-m-d', $begin) . ' 00:00:00';
$end = date('Y-m-d', $end) . ' 23:59:59'; $end = date('Y-m-d', $end) . ' 23:59:59';
$ret ="($fieldName >= '$begin') AND ($fieldName <= '$end')"; return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
return $this->output($ret);
} }
/** /**
@ -149,8 +146,7 @@ class TimeHelper extends AppHelper {
*/ */
function dayAsSql($dateString, $fieldName, $userOffset = null) { function dayAsSql($dateString, $fieldName, $userOffset = null) {
$date = $this->fromString($dateString, $userOffset); $date = $this->fromString($dateString, $userOffset);
$ret = $this->daysAsSql($dateString, $dateString, $fieldName); return $this->daysAsSql($dateString, $dateString, $fieldName);
return $this->output($ret);
} }
/** /**
@ -254,7 +250,7 @@ class TimeHelper extends AppHelper {
break; break;
} }
} }
return $this->output($date); return $date;
} }
/** /**
@ -265,8 +261,7 @@ class TimeHelper extends AppHelper {
* @return integer Unix timestamp * @return integer Unix timestamp
*/ */
function toUnix($dateString, $userOffset = null) { function toUnix($dateString, $userOffset = null) {
$ret = $this->fromString($dateString, $userOffset); return $this->fromString($dateString, $userOffset);
return $this->output($ret);
} }
/** /**
@ -278,8 +273,7 @@ class TimeHelper extends AppHelper {
*/ */
function toAtom($dateString, $userOffset = null) { function toAtom($dateString, $userOffset = null) {
$date = $this->fromString($dateString, $userOffset); $date = $this->fromString($dateString, $userOffset);
$ret = date('Y-m-d\TH:i:s\Z', $date); return date('Y-m-d\TH:i:s\Z', $date);
return $this->output($ret);
} }
/** /**
@ -291,8 +285,7 @@ class TimeHelper extends AppHelper {
*/ */
function toRSS($dateString, $userOffset = null) { function toRSS($dateString, $userOffset = null) {
$date = $this->fromString($dateString, $userOffset); $date = $this->fromString($dateString, $userOffset);
$ret = date("r", $date); return date("r", $date);
return $this->output($ret);
} }
/** /**
@ -472,7 +465,7 @@ class TimeHelper extends AppHelper {
$relativeDate = sprintf(__('%s ago', true), $relativeDate); $relativeDate = sprintf(__('%s ago', true), $relativeDate);
} }
} }
return $this->output($relativeDate); return $relativeDate;
} }
/** /**

View file

@ -65,7 +65,7 @@ class XmlHelper extends AppHelper {
$attrib = 'xml ' . $attrib; $attrib = 'xml ' . $attrib;
} }
return $this->output($this->Xml->header($attrib)); return $this->Xml->header($attrib);
} }
/** /**
@ -131,7 +131,7 @@ class XmlHelper extends AppHelper {
if (!$endTag) { if (!$endTag) {
$this->Xml =& $elem; $this->Xml =& $elem;
} }
return $this->output($out); return $out;
} }
/** /**
@ -144,7 +144,7 @@ class XmlHelper extends AppHelper {
if ($parent =& $this->Xml->parent()) { if ($parent =& $this->Xml->parent()) {
$this->Xml =& $parent; $this->Xml =& $parent;
} }
return $this->output('</' . $name . '>'); return '</' . $name . '>';
} }
/** /**

View file

@ -40,7 +40,7 @@
</div> </div>
<div id="content"> <div id="content">
<?php $this->Session->flash(); ?> <?php echo $this->Session->flash(); ?>
<?php echo $content_for_layout; ?> <?php echo $content_for_layout; ?>

View file

@ -252,7 +252,7 @@ class View extends Object {
* Holds View output. * Holds View output.
* *
* @var string * @var string
**/ */
var $output = false; var $output = false;
/** /**
@ -722,7 +722,7 @@ class View extends Object {
$cache->helpers = $this->helpers; $cache->helpers = $this->helpers;
$cache->action = $this->action; $cache->action = $this->action;
$cache->controllerName = $this->name; $cache->controllerName = $this->name;
$cache->layout = $this->layout; $cache->layout = $this->layout;
$cache->cacheAction = $this->cacheAction; $cache->cacheAction = $this->cacheAction;
$cache->cache($___viewFn, $out, $cached); $cache->cache($___viewFn, $out, $cached);
} }
@ -750,18 +750,14 @@ class View extends Object {
$options = $helper; $options = $helper;
$helper = $i; $helper = $i;
} }
$plugin = $this->plugin; list($plugin, $helper) = pluginSplit($helper, true, $this->plugin);
if (strpos($helper, '.') !== false) {
list($plugin, $helper) = explode('.', $helper);
}
$helperCn = $helper . 'Helper'; $helperCn = $helper . 'Helper';
if (!isset($loaded[$helper])) { if (!isset($loaded[$helper])) {
if (!class_exists($helperCn)) { if (!class_exists($helperCn)) {
$isLoaded = false; $isLoaded = false;
if (!is_null($plugin)) { if (!is_null($plugin)) {
$isLoaded = App::import('Helper', $plugin . '.' . $helper); $isLoaded = App::import('Helper', $plugin . $helper);
} }
if (!$isLoaded) { if (!$isLoaded) {
if (!App::import('Helper', $helper)) { if (!App::import('Helper', $helper)) {

View file

@ -33,8 +33,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* setUp method * setUp method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function setUp() { function setUp() {
App::build(array( App::build(array(
@ -46,8 +46,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* tearDown method * tearDown method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function tearDown() { function tearDown() {
App::build(); App::build();
@ -58,7 +58,8 @@ class BasicsTest extends CakeTestCase {
* test the array_diff_key compatibility function. * test the array_diff_key compatibility function.
* *
* @return void * @return void
**/ * @access public
*/
function testArrayDiffKey() { function testArrayDiffKey() {
$one = array('one' => 1, 'two' => 2, 'three' => 3); $one = array('one' => 1, 'two' => 2, 'three' => 3);
$two = array('one' => 'one', 'two' => 'two'); $two = array('one' => 'one', 'two' => 'two');
@ -175,8 +176,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test uses() * test uses()
* *
* @access public
* @return void * @return void
* @access public
* @deprecated * @deprecated
*/ */
function testUses() { function testUses() {
@ -194,8 +195,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* Test h() * Test h()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testH() { function testH() {
$string = '<foo>'; $string = '<foo>';
@ -211,8 +212,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* Test a() * Test a()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testA() { function testA() {
$result = a('this', 'that', 'bar'); $result = a('this', 'that', 'bar');
@ -222,8 +223,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* Test aa() * Test aa()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testAa() { function testAa() {
$result = aa('a', 'b', 'c', 'd'); $result = aa('a', 'b', 'c', 'd');
@ -238,8 +239,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* Test am() * Test am()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testAm() { function testAm() {
$result = am(array('one', 'two'), 2, 3, 4); $result = am(array('one', 'two'), 2, 3, 4);
@ -254,8 +255,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test cache() * test cache()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testCache() { function testCache() {
$_cacheDisable = Configure::read('Cache.disable'); $_cacheDisable = Configure::read('Cache.disable');
@ -290,8 +291,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test clearCache() * test clearCache()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testClearCache() { function testClearCache() {
$cacheOff = Configure::read('Cache.disable'); $cacheOff = Configure::read('Cache.disable');
@ -338,8 +339,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test __() * test __()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function test__() { function test__() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
@ -362,8 +363,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test __n() * test __n()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function test__n() { function test__n() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
@ -390,8 +391,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test __d() * test __d()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function test__d() { function test__d() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
@ -418,8 +419,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test __dn() * test __dn()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function test__dn() { function test__dn() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
@ -450,8 +451,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test __c() * test __c()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function test__c() { function test__c() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
@ -474,8 +475,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test __dc() * test __dc()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function test__dc() { function test__dc() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
@ -506,8 +507,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test __dcn() * test __dcn()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function test__dcn() { function test__dcn() {
Configure::write('Config.language', 'rule_1_po'); Configure::write('Config.language', 'rule_1_po');
@ -534,8 +535,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test LogError() * test LogError()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testLogError() { function testLogError() {
@unlink(LOGS . 'error.log'); @unlink(LOGS . 'error.log');
@ -552,8 +553,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test fileExistsInPath() * test fileExistsInPath()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testFileExistsInPath() { function testFileExistsInPath() {
$this->skipUnless(function_exists('ini_set'), '%s ini_set function not available'); $this->skipUnless(function_exists('ini_set'), '%s ini_set function not available');
@ -597,8 +598,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test convertSlash() * test convertSlash()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testConvertSlash() { function testConvertSlash() {
$result = convertSlash('\path\to\location\\'); $result = convertSlash('\path\to\location\\');
@ -613,8 +614,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test debug() * test debug()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testDebug() { function testDebug() {
ob_start(); ob_start();
@ -637,8 +638,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test pr() * test pr()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testPr() { function testPr() {
ob_start(); ob_start();
@ -657,8 +658,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test params() * test params()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testParams() { function testParams() {
$this->assertNull(params('weekend')); $this->assertNull(params('weekend'));
@ -675,8 +676,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test stripslashes_deep() * test stripslashes_deep()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testStripslashesDeep() { function testStripslashesDeep() {
$this->skipIf(ini_get('magic_quotes_sybase') === '1', '%s magic_quotes_sybase is on'); $this->skipIf(ini_get('magic_quotes_sybase') === '1', '%s magic_quotes_sybase is on');
@ -713,8 +714,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test stripslashes_deep() with magic_quotes_sybase on * test stripslashes_deep() with magic_quotes_sybase on
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testStripslashesDeepSybase() { function testStripslashesDeepSybase() {
$this->skipUnless(ini_get('magic_quotes_sybase') === '1', '%s magic_quotes_sybase is off'); $this->skipUnless(ini_get('magic_quotes_sybase') === '1', '%s magic_quotes_sybase is off');
@ -747,8 +748,8 @@ class BasicsTest extends CakeTestCase {
/** /**
* test ife() * test ife()
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testIfe() { function testIfe() {
$this->assertEqual(ife(true, 'a', 'b'), 'a'); $this->assertEqual(ife(true, 'a', 'b'), 'a');
@ -763,5 +764,33 @@ class BasicsTest extends CakeTestCase {
$this->assertEqual(ife(0, 'a', 'b'), 'b'); $this->assertEqual(ife(0, 'a', 'b'), 'b');
$this->assertEqual(ife(array(), 'a', 'b'), 'b'); $this->assertEqual(ife(array(), 'a', 'b'), 'b');
} }
/**
* test pluginSplit
*
* @return void
*/
function testPluginSplit() {
$result = pluginSplit('Something.else');
$this->assertEqual($result, array('Something', 'else'));
$result = pluginSplit('Something.else.more.dots');
$this->assertEqual($result, array('Something', 'else.more.dots'));
$result = pluginSplit('Somethingelse');
$this->assertEqual($result, array(null, 'Somethingelse'));
$result = pluginSplit('Something.else', true);
$this->assertEqual($result, array('Something.', 'else'));
$result = pluginSplit('Something.else.more.dots', true);
$this->assertEqual($result, array('Something.', 'else.more.dots'));
$result = pluginSplit('Post', false, 'Blog');
$this->assertEqual($result, array('Blog', 'Post'));
$result = pluginSplit('Blog.Post', false, 'Ultimate');
$this->assertEqual($result, array('Blog', 'Post'));
}
} }
?> ?>

View file

@ -83,8 +83,8 @@ class TestShellDispatcher extends ShellDispatcher {
/** /**
* _initEnvironment method * _initEnvironment method
* *
* @access protected
* @return void * @return void
* @access protected
*/ */
function _initEnvironment() { function _initEnvironment() {
} }
@ -92,8 +92,8 @@ class TestShellDispatcher extends ShellDispatcher {
/** /**
* stderr method * stderr method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function stderr($string) { function stderr($string) {
$this->stderr .= rtrim($string, ' '); $this->stderr .= rtrim($string, ' ');
@ -102,8 +102,8 @@ class TestShellDispatcher extends ShellDispatcher {
/** /**
* stdout method * stdout method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function stdout($string, $newline = true) { function stdout($string, $newline = true) {
if ($newline) { if ($newline) {
@ -116,8 +116,8 @@ class TestShellDispatcher extends ShellDispatcher {
/** /**
* clear method * clear method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function clear() { function clear() {
@ -126,8 +126,8 @@ class TestShellDispatcher extends ShellDispatcher {
/** /**
* _stop method * _stop method
* *
* @access protected
* @return void * @return void
* @access protected
*/ */
function _stop($status = 0) { function _stop($status = 0) {
$this->stopped = 'Stopped with status: ' . $status; $this->stopped = 'Stopped with status: ' . $status;
@ -138,8 +138,8 @@ class TestShellDispatcher extends ShellDispatcher {
* getShell * getShell
* *
* @param mixed $plugin * @param mixed $plugin
* @access public
* @return mixed * @return mixed
* @access public
*/ */
function getShell($plugin = null) { function getShell($plugin = null) {
return $this->_getShell($plugin); return $this->_getShell($plugin);
@ -149,8 +149,8 @@ class TestShellDispatcher extends ShellDispatcher {
* _getShell * _getShell
* *
* @param mixed $plugin * @param mixed $plugin
* @access protected
* @return mixed * @return mixed
* @access protected
*/ */
function _getShell($plugin = null) { function _getShell($plugin = null) {
if (isset($this->TestShell)) { if (isset($this->TestShell)) {
@ -171,8 +171,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* setUp method * setUp method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function setUp() { function setUp() {
App::build(array( App::build(array(
@ -189,8 +189,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* tearDown method * tearDown method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function tearDown() { function tearDown() {
App::build(); App::build();
@ -199,8 +199,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* testParseParams method * testParseParams method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testParseParams() { function testParseParams() {
$Dispatcher =& new TestShellDispatcher(); $Dispatcher =& new TestShellDispatcher();
@ -458,8 +458,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* testBuildPaths method * testBuildPaths method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testBuildPaths() { function testBuildPaths() {
$Dispatcher =& new TestShellDispatcher(); $Dispatcher =& new TestShellDispatcher();
@ -481,8 +481,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* Verify loading of (plugin-) shells * Verify loading of (plugin-) shells
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testGetShell() { function testGetShell() {
$this->skipIf(class_exists('SampleShell'), '%s SampleShell Class already loaded'); $this->skipIf(class_exists('SampleShell'), '%s SampleShell Class already loaded');
@ -510,8 +510,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* Verify correct dispatch of Shell subclasses with a main method * Verify correct dispatch of Shell subclasses with a main method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testDispatchShellWithMain() { function testDispatchShellWithMain() {
Mock::generate('Shell', 'MockWithMainShell', array('main', '_secret')); Mock::generate('Shell', 'MockWithMainShell', array('main', '_secret'));
@ -601,8 +601,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* Verify correct dispatch of Shell subclasses without a main method * Verify correct dispatch of Shell subclasses without a main method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testDispatchShellWithoutMain() { function testDispatchShellWithoutMain() {
Mock::generate('Shell', 'MockWithoutMainShell', array('initDb', '_secret')); Mock::generate('Shell', 'MockWithoutMainShell', array('initDb', '_secret'));
@ -673,8 +673,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* Verify correct dispatch of custom classes with a main method * Verify correct dispatch of custom classes with a main method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testDispatchNotAShellWithMain() { function testDispatchNotAShellWithMain() {
Mock::generate('Object', 'MockWithMainNotAShell', Mock::generate('Object', 'MockWithMainNotAShell',
@ -753,8 +753,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* Verify correct dispatch of custom classes without a main method * Verify correct dispatch of custom classes without a main method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testDispatchNotAShellWithoutMain() { function testDispatchNotAShellWithoutMain() {
Mock::generate('Object', 'MockWithoutMainNotAShell', Mock::generate('Object', 'MockWithoutMainNotAShell',
@ -824,8 +824,8 @@ class ShellDispatcherTest extends CakeTestCase {
* Verify that a task is called instead of the shell if the first arg equals * Verify that a task is called instead of the shell if the first arg equals
* the name of the task * the name of the task
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testDispatchTask() { function testDispatchTask() {
Mock::generate('Shell', 'MockWeekShell', array('main')); Mock::generate('Shell', 'MockWeekShell', array('main'));
@ -872,8 +872,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* Verify shifting of arguments * Verify shifting of arguments
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testShiftArgs() { function testShiftArgs() {
$Dispatcher =& new TestShellDispatcher(); $Dispatcher =& new TestShellDispatcher();
@ -902,8 +902,8 @@ class ShellDispatcherTest extends CakeTestCase {
/** /**
* testHelpCommand method * testHelpCommand method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testHelpCommand() { function testHelpCommand() {
$Dispatcher =& new TestShellDispatcher(); $Dispatcher =& new TestShellDispatcher();

View file

@ -52,13 +52,21 @@ Mock::generate('AclComponent', 'MockAclShellAclComponent');
* @subpackage cake.tests.cases.console.libs.tasks * @subpackage cake.tests.cases.console.libs.tasks
*/ */
class AclShellTest extends CakeTestCase { class AclShellTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.aco', 'core.aro', 'core.aros_aco'); var $fixtures = array('core.aco', 'core.aro', 'core.aros_aco');
/** /**
* configure Configure for testcase * configure Configure for testcase
* *
* @return void * @return void
**/ * @access public
*/
function startCase() { function startCase() {
$this->_aclDb = Configure::read('Acl.database'); $this->_aclDb = Configure::read('Acl.database');
$this->_aclClass = Configure::read('Acl.classname'); $this->_aclClass = Configure::read('Acl.classname');
@ -71,7 +79,8 @@ class AclShellTest extends CakeTestCase {
* restore Environment settings * restore Environment settings
* *
* @return void * @return void
**/ * @access public
*/
function endCase() { function endCase() {
Configure::write('Acl.database', $this->_aclDb); Configure::write('Acl.database', $this->_aclDb);
Configure::write('Acl.classname', $this->_aclClass); Configure::write('Acl.classname', $this->_aclClass);
@ -107,7 +116,8 @@ class AclShellTest extends CakeTestCase {
* test that model.foreign_key output works when looking at acl rows * test that model.foreign_key output works when looking at acl rows
* *
* @return void * @return void
**/ * @access public
*/
function testViewWithModelForeignKeyOutput() { function testViewWithModelForeignKeyOutput() {
$this->Task->command = 'view'; $this->Task->command = 'view';
$this->Task->startup(); $this->Task->startup();
@ -132,7 +142,8 @@ class AclShellTest extends CakeTestCase {
* test view with an argument * test view with an argument
* *
* @return void * @return void
**/ * @access public
*/
function testViewWithArgument() { function testViewWithArgument() {
$this->Task->args = array('aro', 'admins'); $this->Task->args = array('aro', 'admins');
$this->Task->expectAt(0, 'out', array('Aro tree:')); $this->Task->expectAt(0, 'out', array('Aro tree:'));
@ -146,7 +157,8 @@ class AclShellTest extends CakeTestCase {
* test the method that splits model.foreign key. and that it returns an array. * test the method that splits model.foreign key. and that it returns an array.
* *
* @return void * @return void
**/ * @access public
*/
function testParsingModelAndForeignKey() { function testParsingModelAndForeignKey() {
$result = $this->Task->parseIdentifier('Model.foreignKey'); $result = $this->Task->parseIdentifier('Model.foreignKey');
$expected = array('model' => 'Model', 'foreign_key' => 'foreignKey'); $expected = array('model' => 'Model', 'foreign_key' => 'foreignKey');
@ -162,7 +174,8 @@ class AclShellTest extends CakeTestCase {
* test creating aro/aco nodes * test creating aro/aco nodes
* *
* @return void * @return void
**/ * @access public
*/
function testCreate() { function testCreate() {
$this->Task->args = array('aro', 'root', 'User.1'); $this->Task->args = array('aro', 'root', 'User.1');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/created/'), '*')); $this->Task->expectAt(0, 'out', array(new PatternExpectation('/created/'), '*'));
@ -202,7 +215,8 @@ class AclShellTest extends CakeTestCase {
* test the delete method with different node types. * test the delete method with different node types.
* *
* @return void * @return void
**/ * @access public
*/
function testDelete() { function testDelete() {
$this->Task->args = array('aro', 'AuthUser.1'); $this->Task->args = array('aro', 'AuthUser.1');
$this->Task->expectAt(0, 'out', array(new NoPatternExpectation('/not/'), true)); $this->Task->expectAt(0, 'out', array(new NoPatternExpectation('/not/'), true));
@ -217,7 +231,8 @@ class AclShellTest extends CakeTestCase {
* test setParent method. * test setParent method.
* *
* @return void * @return void
**/ * @access public
*/
function testSetParent() { function testSetParent() {
$this->Task->args = array('aro', 'AuthUser.2', 'root'); $this->Task->args = array('aro', 'AuthUser.2', 'root');
$this->Task->setParent(); $this->Task->setParent();
@ -231,7 +246,8 @@ class AclShellTest extends CakeTestCase {
* test grant * test grant
* *
* @return void * @return void
**/ * @access public
*/
function testGrant() { function testGrant() {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create'); $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission granted/'), true)); $this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission granted/'), true));
@ -246,7 +262,8 @@ class AclShellTest extends CakeTestCase {
* test deny * test deny
* *
* @return void * @return void
**/ * @access public
*/
function testDeny() { function testDeny() {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create'); $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission denied/'), true)); $this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission denied/'), true));
@ -261,7 +278,8 @@ class AclShellTest extends CakeTestCase {
* test checking allowed and denied perms * test checking allowed and denied perms
* *
* @return void * @return void
**/ * @access public
*/
function testCheck() { function testCheck() {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*'); $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/not allowed/'), true)); $this->Task->expectAt(0, 'out', array(new PatternExpectation('/not allowed/'), true));
@ -284,7 +302,8 @@ class AclShellTest extends CakeTestCase {
* test inherit and that it 0's the permission fields. * test inherit and that it 0's the permission fields.
* *
* @return void * @return void
**/ * @access public
*/
function testInherit() { function testInherit() {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create'); $this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission granted/'), true)); $this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission granted/'), true));
@ -303,7 +322,8 @@ class AclShellTest extends CakeTestCase {
* test getting the path for an aro/aco * test getting the path for an aro/aco
* *
* @return void * @return void
**/ * @access public
*/
function testGetPath() { function testGetPath() {
$this->Task->args = array('aro', 'AuthUser.2'); $this->Task->args = array('aro', 'AuthUser.2');
$this->Task->expectAt(1, 'out', array('[1] ROOT')); $this->Task->expectAt(1, 'out', array('[1] ROOT'));
@ -311,6 +331,5 @@ class AclShellTest extends CakeTestCase {
$this->Task->expectAt(3, 'out', array(' [4] Elrond')); $this->Task->expectAt(3, 'out', array(' [4] Elrond'));
$this->Task->getPath(); $this->Task->getPath();
} }
} }
?> ?>

View file

@ -76,8 +76,8 @@ class ApiShellTest extends CakeTestCase {
/** /**
* Test that method names are detected properly including those with no arguments. * Test that method names are detected properly including those with no arguments.
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testMethodNameDetection () { function testMethodNameDetection () {
$this->Shell->setReturnValueAt(0, 'in', 'q'); $this->Shell->setReturnValueAt(0, 'in', 'q');

View file

@ -61,14 +61,16 @@ class BakeShellTestCase extends CakeTestCase {
* fixtures * fixtures
* *
* @var array * @var array
**/ * @access public
*/
var $fixtures = array('core.user'); var $fixtures = array('core.user');
/** /**
* start test * start test
* *
* @return void * @return void
**/ * @access public
*/
function startTest() { function startTest() {
$this->Dispatch =& new BakeShellMockShellDispatcher(); $this->Dispatch =& new BakeShellMockShellDispatcher();
$this->Shell =& new MockBakeShell(); $this->Shell =& new MockBakeShell();
@ -80,7 +82,8 @@ class BakeShellTestCase extends CakeTestCase {
* endTest method * endTest method
* *
* @return void * @return void
**/ * @access public
*/
function endTest() { function endTest() {
unset($this->Dispatch, $this->Shell); unset($this->Dispatch, $this->Shell);
} }
@ -89,7 +92,8 @@ class BakeShellTestCase extends CakeTestCase {
* test bake all * test bake all
* *
* @return void * @return void
**/ * @access public
*/
function testAllWithModelName() { function testAllWithModelName() {
$this->Shell->Model =& new BakeShellMockModelTask(); $this->Shell->Model =& new BakeShellMockModelTask();
$this->Shell->Controller =& new BakeShellMockControllerTask(); $this->Shell->Controller =& new BakeShellMockControllerTask();
@ -118,4 +122,5 @@ class BakeShellTestCase extends CakeTestCase {
$this->Shell->args = array('User'); $this->Shell->args = array('User');
$this->Shell->all(); $this->Shell->all();
} }
} }
?>

View file

@ -115,7 +115,14 @@ class SchemaShellTestSchema extends CakeSchema {
*/ */
class SchemaShellTest extends CakeTestCase { class SchemaShellTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.user', 'core.post', 'core.auth_user'); var $fixtures = array('core.article', 'core.user', 'core.post', 'core.auth_user');
/** /**
* startTest method * startTest method
* *
@ -142,7 +149,8 @@ class SchemaShellTest extends CakeTestCase {
* test startup method * test startup method
* *
* @return void * @return void
**/ * @access public
*/
function testStartup() { function testStartup() {
$this->Shell->startup(); $this->Shell->startup();
$this->assertTrue(isset($this->Shell->Schema)); $this->assertTrue(isset($this->Shell->Schema));
@ -177,7 +185,8 @@ class SchemaShellTest extends CakeTestCase {
* Test View - and that it dumps the schema file to stdout * Test View - and that it dumps the schema file to stdout
* *
* @return void * @return void
**/ * @access public
*/
function testView() { function testView() {
$this->Shell->startup(); $this->Shell->startup();
$this->Shell->Schema->path = APP . 'config' . DS . 'schema'; $this->Shell->Schema->path = APP . 'config' . DS . 'schema';
@ -191,7 +200,8 @@ class SchemaShellTest extends CakeTestCase {
* test that view() can find plugin schema files. * test that view() can find plugin schema files.
* *
* @return void * @return void
**/ * @access public
*/
function testViewWithPlugins() { function testViewWithPlugins() {
App::build(array( App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS) 'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
@ -214,7 +224,8 @@ class SchemaShellTest extends CakeTestCase {
* test dump() with sql file generation * test dump() with sql file generation
* *
* @return void * @return void
**/ * @access public
*/
function testDumpWithFileWriting() { function testDumpWithFileWriting() {
$this->Shell->params = array( $this->Shell->params = array(
'name' => 'i18n', 'name' => 'i18n',
@ -242,7 +253,8 @@ class SchemaShellTest extends CakeTestCase {
* test that dump() can find and work with plugin schema files. * test that dump() can find and work with plugin schema files.
* *
* @return void * @return void
**/ * @access public
*/
function testDumpFileWritingWithPlugins() { function testDumpFileWritingWithPlugins() {
App::build(array( App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS) 'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
@ -271,6 +283,7 @@ class SchemaShellTest extends CakeTestCase {
* test generate with snapshot generation * test generate with snapshot generation
* *
* @return void * @return void
* @access public
*/ */
function testGenerateSnaphot() { function testGenerateSnaphot() {
$this->Shell->path = TMP; $this->Shell->path = TMP;
@ -290,7 +303,8 @@ class SchemaShellTest extends CakeTestCase {
* test generate without a snapshot. * test generate without a snapshot.
* *
* @return void * @return void
**/ * @access public
*/
function testGenerateNoOverwrite() { function testGenerateNoOverwrite() {
touch(TMP . 'schema.php'); touch(TMP . 'schema.php');
$this->Shell->params['file'] = 'schema.php'; $this->Shell->params['file'] = 'schema.php';
@ -309,7 +323,8 @@ class SchemaShellTest extends CakeTestCase {
* test generate with overwriting of the schema files. * test generate with overwriting of the schema files.
* *
* @return void * @return void
**/ * @access public
*/
function testGenerateOverwrite() { function testGenerateOverwrite() {
touch(TMP . 'schema.php'); touch(TMP . 'schema.php');
$this->Shell->params['file'] = 'schema.php'; $this->Shell->params['file'] = 'schema.php';
@ -334,7 +349,8 @@ class SchemaShellTest extends CakeTestCase {
* in a plugin. * in a plugin.
* *
* @return void * @return void
**/ * @access public
*/
function testGenerateWithPlugins() { function testGenerateWithPlugins() {
App::build(array( App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS) 'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
@ -363,7 +379,8 @@ class SchemaShellTest extends CakeTestCase {
* Test schema run create with no table args. * Test schema run create with no table args.
* *
* @return void * @return void
**/ * @access public
*/
function testCreateNoArgs() { function testCreateNoArgs() {
$this->Shell->params = array( $this->Shell->params = array(
'connection' => 'test_suite', 'connection' => 'test_suite',
@ -386,7 +403,8 @@ class SchemaShellTest extends CakeTestCase {
* Test schema run create with no table args. * Test schema run create with no table args.
* *
* @return void * @return void
**/ * @access public
*/
function testCreateWithTableArgs() { function testCreateWithTableArgs() {
$this->Shell->params = array( $this->Shell->params = array(
'connection' => 'test_suite', 'connection' => 'test_suite',
@ -411,7 +429,8 @@ class SchemaShellTest extends CakeTestCase {
* test run update with a table arg. * test run update with a table arg.
* *
* @return void * @return void
**/ * @access public
*/
function testUpdateWithTable() { function testUpdateWithTable() {
$this->Shell->params = array( $this->Shell->params = array(
'connection' => 'test_suite', 'connection' => 'test_suite',
@ -434,7 +453,8 @@ class SchemaShellTest extends CakeTestCase {
* test that the plugin param creates the correct path in the schema object. * test that the plugin param creates the correct path in the schema object.
* *
* @return void * @return void
**/ * @access public
*/
function testPluginParam() { function testPluginParam() {
App::build(array( App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS) 'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
@ -454,7 +474,8 @@ class SchemaShellTest extends CakeTestCase {
* test that using Plugin.name with write. * test that using Plugin.name with write.
* *
* @return void * @return void
**/ * @access public
*/
function testPluginDotSyntaxWithCreate() { function testPluginDotSyntaxWithCreate() {
App::build(array( App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS) 'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)

View file

@ -46,7 +46,7 @@ Mock::generatePartial('ShellDispatcher', 'TestShellMockShellDispatcher', array(
*/ */
class TestShell extends Shell { class TestShell extends Shell {
/* /**
* name property * name property
* *
* @var name * @var name
@ -65,8 +65,8 @@ class TestShell extends Shell {
* stop method * stop method
* *
* @param integer $status * @param integer $status
* @access protected
* @return void * @return void
* @access protected
*/ */
function _stop($status = 0) { function _stop($status = 0) {
$this->stopped = $status; $this->stopped = $status;
@ -257,8 +257,8 @@ class ShellTest extends CakeTestCase {
/** /**
* testNl * testNl
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testNl() { function testNl() {
$this->assertEqual($this->Shell->nl(), "\n"); $this->assertEqual($this->Shell->nl(), "\n");
@ -271,8 +271,8 @@ class ShellTest extends CakeTestCase {
/** /**
* testHr * testHr
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testHr() { function testHr() {
$bar = '---------------------------------------------------------------'; $bar = '---------------------------------------------------------------';
@ -296,8 +296,8 @@ class ShellTest extends CakeTestCase {
/** /**
* testError * testError
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testError() { function testError() {
$this->Shell->Dispatch->expectAt(0, 'stderr', array("Error: Foo Not Found\n")); $this->Shell->Dispatch->expectAt(0, 'stderr', array("Error: Foo Not Found\n"));

View file

@ -88,7 +88,8 @@ class ControllerTaskTest extends CakeTestCase {
* fixtures * fixtures
* *
* @var array * @var array
**/ * @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag'); var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/** /**
@ -124,7 +125,8 @@ class ControllerTaskTest extends CakeTestCase {
* test ListAll * test ListAll
* *
* @return void * @return void
**/ * @access public
*/
function testListAll() { function testListAll() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->interactive = true; $this->Task->interactive = true;
@ -153,7 +155,8 @@ class ControllerTaskTest extends CakeTestCase {
* Test that getName interacts with the user and returns the controller name. * Test that getName interacts with the user and returns the controller name.
* *
* @return void * @return void
**/ * @access public
*/
function testGetName() { function testGetName() {
$this->Task->setReturnValue('in', 1); $this->Task->setReturnValue('in', 1);
@ -180,7 +183,8 @@ class ControllerTaskTest extends CakeTestCase {
* test helper interactions * test helper interactions
* *
* @return void * @return void
**/ * @access public
*/
function testDoHelpers() { function testDoHelpers() {
$this->Task->setReturnValue('in', 'n'); $this->Task->setReturnValue('in', 'n');
$result = $this->Task->doHelpers(); $result = $this->Task->doHelpers();
@ -203,7 +207,8 @@ class ControllerTaskTest extends CakeTestCase {
* test component interactions * test component interactions
* *
* @return void * @return void
**/ * @access public
*/
function testDoComponents() { function testDoComponents() {
$this->Task->setReturnValue('in', 'n'); $this->Task->setReturnValue('in', 'n');
$result = $this->Task->doComponents(); $result = $this->Task->doComponents();
@ -226,7 +231,8 @@ class ControllerTaskTest extends CakeTestCase {
* test Confirming controller user interaction * test Confirming controller user interaction
* *
* @return void * @return void
**/ * @access public
*/
function testConfirmController() { function testConfirmController() {
$controller = 'Posts'; $controller = 'Posts';
$scaffold = false; $scaffold = false;
@ -244,7 +250,8 @@ class ControllerTaskTest extends CakeTestCase {
* test the bake method * test the bake method
* *
* @return void * @return void
**/ * @access public
*/
function testBake() { function testBake() {
$helpers = array('Ajax', 'Time'); $helpers = array('Ajax', 'Time');
$components = array('Acl', 'Auth'); $components = array('Acl', 'Auth');
@ -267,7 +274,8 @@ class ControllerTaskTest extends CakeTestCase {
* test bake() with a -plugin param * test bake() with a -plugin param
* *
* @return void * @return void
**/ * @access public
*/
function testBakeWithPlugin() { function testBakeWithPlugin() {
$this->Task->plugin = 'ControllerTest'; $this->Task->plugin = 'ControllerTest';
$helpers = array('Ajax', 'Time'); $helpers = array('Ajax', 'Time');
@ -289,7 +297,8 @@ class ControllerTaskTest extends CakeTestCase {
* test that bakeActions is creating the correct controller Code. (Using sessions) * test that bakeActions is creating the correct controller Code. (Using sessions)
* *
* @return void * @return void
**/ * @access public
*/
function testBakeActionsUsingSessions() { function testBakeActionsUsingSessions() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), $skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Testing bakeActions requires Article, Comment & Tag Model to be undefined. %s'); 'Testing bakeActions requires Article, Comment & Tag Model to be undefined. %s');
@ -332,7 +341,8 @@ class ControllerTaskTest extends CakeTestCase {
* Test baking with Controller::flash() or no sessions. * Test baking with Controller::flash() or no sessions.
* *
* @return void * @return void
**/ * @access public
*/
function testBakeActionsWithNoSessions() { function testBakeActionsWithNoSessions() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), $skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Testing bakeActions requires Article, Tag, Comment Models to be undefined. %s'); 'Testing bakeActions requires Article, Tag, Comment Models to be undefined. %s');
@ -367,7 +377,8 @@ class ControllerTaskTest extends CakeTestCase {
* test baking a test * test baking a test
* *
* @return void * @return void
**/ * @access public
*/
function testBakeTest() { function testBakeTest() {
$this->Task->plugin = 'ControllerTest'; $this->Task->plugin = 'ControllerTest';
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
@ -383,7 +394,8 @@ class ControllerTaskTest extends CakeTestCase {
* test Interactive mode. * test Interactive mode.
* *
* @return void * @return void
**/ * @access public
*/
function testInteractive() { function testInteractive() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path'; $this->Task->path = '/my/path';
@ -407,7 +419,8 @@ class ControllerTaskTest extends CakeTestCase {
* test that execute runs all when the first arg == all * test that execute runs all when the first arg == all
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteIntoAll() { function testExecuteIntoAll() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), $skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute into all could not be run as an Article, Tag or Comment model was already loaded. %s'); 'Execute into all could not be run as an Article, Tag or Comment model was already loaded. %s');
@ -432,7 +445,8 @@ class ControllerTaskTest extends CakeTestCase {
* test that `cake bake controller foos` works. * test that `cake bake controller foos` works.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithController() { function testExecuteWithController() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), $skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s'); 'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
@ -455,7 +469,8 @@ class ControllerTaskTest extends CakeTestCase {
* test that `cake bake controller foo scaffold` works. * test that `cake bake controller foo scaffold` works.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithPublicParam() { function testExecuteWithPublicParam() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), $skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s'); 'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
@ -478,7 +493,8 @@ class ControllerTaskTest extends CakeTestCase {
* test that `cake bake controller foos both` works. * test that `cake bake controller foos both` works.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithControllerAndBoth() { function testExecuteWithControllerAndBoth() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), $skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s'); 'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
@ -502,7 +518,8 @@ class ControllerTaskTest extends CakeTestCase {
* test that `cake bake controller foos admin` works. * test that `cake bake controller foos admin` works.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithControllerAndAdmin() { function testExecuteWithControllerAndAdmin() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'), $skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s'); 'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');

View file

@ -104,7 +104,8 @@ class DbConfigTaskTest extends CakeTestCase {
* Test the getConfig method. * Test the getConfig method.
* *
* @return void * @return void
**/ * @access public
*/
function testGetConfig() { function testGetConfig() {
$this->Task->setReturnValueAt(0, 'in', 'otherOne'); $this->Task->setReturnValueAt(0, 'in', 'otherOne');
$result = $this->Task->getConfig(); $result = $this->Task->getConfig();
@ -115,7 +116,8 @@ class DbConfigTaskTest extends CakeTestCase {
* test that initialize sets the path up. * test that initialize sets the path up.
* *
* @return void * @return void
**/ * @access public
*/
function testInitialize() { function testInitialize() {
$this->assertTrue(empty($this->Task->path)); $this->assertTrue(empty($this->Task->path));
$this->Task->initialize(); $this->Task->initialize();
@ -128,7 +130,8 @@ class DbConfigTaskTest extends CakeTestCase {
* test execute and by extension __interactive * test execute and by extension __interactive
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteIntoInteractive() { function testExecuteIntoInteractive() {
$this->Task->initialize(); $this->Task->initialize();

View file

@ -60,8 +60,9 @@ class FixtureTaskTest extends CakeTestCase {
* fixtures * fixtures
* *
* @var array * @var array
**/ * @access public
var $fixtures = array('core.article', 'core.comment'); */
var $fixtures = array('core.article', 'core.comment', 'core.datatype', 'core.binary_test');
/** /**
* startTest method * startTest method
@ -94,7 +95,8 @@ class FixtureTaskTest extends CakeTestCase {
* test that initialize sets the path * test that initialize sets the path
* *
* @return void * @return void
**/ * @access public
*/
function testConstruct() { function testConstruct() {
$this->Dispatch->params['working'] = DS . 'my' . DS . 'path'; $this->Dispatch->params['working'] = DS . 'my' . DS . 'path';
$Task =& new FixtureTask($this->Dispatch); $Task =& new FixtureTask($this->Dispatch);
@ -107,7 +109,8 @@ class FixtureTaskTest extends CakeTestCase {
* test import option array generation * test import option array generation
* *
* @return void * @return void
**/ * @access public
*/
function testImportOptions() { function testImportOptions() {
$this->Task->setReturnValueAt(0, 'in', 'y'); $this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'y'); $this->Task->setReturnValueAt(1, 'in', 'y');
@ -136,7 +139,8 @@ class FixtureTaskTest extends CakeTestCase {
* test generating a fixture with database conditions. * test generating a fixture with database conditions.
* *
* @return void * @return void
**/ * @access public
*/
function testImportRecordsFromDatabaseWithConditions() { function testImportRecordsFromDatabaseWithConditions() {
$this->Task->setReturnValueAt(0, 'in', 'WHERE 1=1 LIMIT 10'); $this->Task->setReturnValueAt(0, 'in', 'WHERE 1=1 LIMIT 10');
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
@ -155,7 +159,8 @@ class FixtureTaskTest extends CakeTestCase {
* test that execute passes runs bake depending with named model. * test that execute passes runs bake depending with named model.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithNamedModel() { function testExecuteWithNamedModel() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -169,7 +174,8 @@ class FixtureTaskTest extends CakeTestCase {
* test that execute runs all() when args[0] = all * test that execute runs all() when args[0] = all
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteIntoAll() { function testExecuteIntoAll() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -189,7 +195,8 @@ class FixtureTaskTest extends CakeTestCase {
* test using all() with -count and -records * test using all() with -count and -records
* *
* @return void * @return void
**/ * @access public
*/
function testAllWithCountAndRecordsFlags() { function testAllWithCountAndRecordsFlags() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -210,7 +217,8 @@ class FixtureTaskTest extends CakeTestCase {
* test interactive mode of execute * test interactive mode of execute
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteInteractive() { function testExecuteInteractive() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -228,7 +236,8 @@ class FixtureTaskTest extends CakeTestCase {
* Test that bake works * Test that bake works
* *
* @return void * @return void
**/ * @access public
*/
function testBake() { function testBake() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -259,11 +268,29 @@ class FixtureTaskTest extends CakeTestCase {
$this->assertNoPattern('/var \$records/', $result); $this->assertNoPattern('/var \$records/', $result);
} }
/**
* test record generation with float and binary types
*
* @return void
* @access public
*/
function testRecordGenerationForBinaryAndFloat() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article', 'datatypes');
$this->assertPattern("/'float_field' => 1/", $result);
$result = $this->Task->bake('Article', 'binary_tests');
$this->assertPattern("/'data' => 'Lorem ipsum dolor sit amet'/", $result);
}
/** /**
* Test that file generation includes headers and correct path for plugins. * Test that file generation includes headers and correct path for plugins.
* *
* @return void * @return void
**/ * @access public
*/
function testGenerateFixtureFile() { function testGenerateFixtureFile() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -280,7 +307,8 @@ class FixtureTaskTest extends CakeTestCase {
* test generating files into plugins. * test generating files into plugins.
* *
* @return void * @return void
**/ * @access public
*/
function testGeneratePluginFixtureFile() { function testGeneratePluginFixtureFile() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';

View file

@ -65,7 +65,8 @@ class ModelTaskTest extends CakeTestCase {
* fixtures * fixtures
* *
* @var array * @var array
**/ * @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag', 'core.category_thread'); var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag', 'core.category_thread');
/** /**
@ -99,7 +100,8 @@ class ModelTaskTest extends CakeTestCase {
* Test that listAll scans the database connection and lists all the tables in it.s * Test that listAll scans the database connection and lists all the tables in it.s
* *
* @return void * @return void
**/ * @access public
*/
function testListAll() { function testListAll() {
$this->Task->expectAt(1, 'out', array('1. Article')); $this->Task->expectAt(1, 'out', array('1. Article'));
$this->Task->expectAt(2, 'out', array('2. ArticlesTag')); $this->Task->expectAt(2, 'out', array('2. ArticlesTag'));
@ -126,7 +128,8 @@ class ModelTaskTest extends CakeTestCase {
* Test that getName interacts with the user and returns the model name. * Test that getName interacts with the user and returns the model name.
* *
* @return void * @return void
**/ * @access public
*/
function testGetName() { function testGetName() {
$this->Task->setReturnValue('in', 1); $this->Task->setReturnValue('in', 1);
@ -153,7 +156,8 @@ class ModelTaskTest extends CakeTestCase {
* Test table name interactions * Test table name interactions
* *
* @return void * @return void
**/ * @access public
*/
function testGetTableName() { function testGetTableName() {
$this->Task->setReturnValueAt(0, 'in', 'y'); $this->Task->setReturnValueAt(0, 'in', 'y');
$result = $this->Task->getTable('Article', 'test_suite'); $result = $this->Task->getTable('Article', 'test_suite');
@ -171,7 +175,8 @@ class ModelTaskTest extends CakeTestCase {
* test that initializing the validations works. * test that initializing the validations works.
* *
* @return void * @return void
**/ * @access public
*/
function testInitValidations() { function testInitValidations() {
$result = $this->Task->initValidations(); $result = $this->Task->initValidations();
$this->assertTrue(in_array('notempty', $result)); $this->assertTrue(in_array('notempty', $result));
@ -182,7 +187,8 @@ class ModelTaskTest extends CakeTestCase {
* tests the guessing features of validation * tests the guessing features of validation
* *
* @return void * @return void
**/ * @access public
*/
function testFieldValidationGuessing() { function testFieldValidationGuessing() {
$this->Task->interactive = false; $this->Task->interactive = false;
$this->Task->initValidations(); $this->Task->initValidations();
@ -210,7 +216,8 @@ class ModelTaskTest extends CakeTestCase {
* test that interactive field validation works and returns multiple validators. * test that interactive field validation works and returns multiple validators.
* *
* @return void * @return void
**/ * @access public
*/
function testInteractiveFieldValidation() { function testInteractiveFieldValidation() {
$this->Task->initValidations(); $this->Task->initValidations();
$this->Task->interactive = true; $this->Task->interactive = true;
@ -228,7 +235,8 @@ class ModelTaskTest extends CakeTestCase {
* test the validation Generation routine * test the validation Generation routine
* *
* @return void * @return void
**/ * @access public
*/
function testNonInteractiveDoValidation() { function testNonInteractiveDoValidation() {
$Model =& new MockModelTaskModel(); $Model =& new MockModelTaskModel();
$Model->primaryKey = 'id'; $Model->primaryKey = 'id';
@ -289,7 +297,8 @@ class ModelTaskTest extends CakeTestCase {
* test that finding primary key works * test that finding primary key works
* *
* @return void * @return void
**/ * @access public
*/
function testFindPrimaryKey() { function testFindPrimaryKey() {
$fields = array( $fields = array(
'one' => array(), 'one' => array(),
@ -307,7 +316,8 @@ class ModelTaskTest extends CakeTestCase {
* test finding Display field * test finding Display field
* *
* @return void * @return void
**/ * @access public
*/
function testFindDisplayField() { function testFindDisplayField() {
$fields = array('id' => array(), 'tagname' => array(), 'body' => array(), $fields = array('id' => array(), 'tagname' => array(), 'body' => array(),
'created' => array(), 'modified' => array()); 'created' => array(), 'modified' => array());
@ -327,7 +337,8 @@ class ModelTaskTest extends CakeTestCase {
* test that belongsTo generation works. * test that belongsTo generation works.
* *
* @return void * @return void
**/ * @access public
*/
function testBelongsToGeneration() { function testBelongsToGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Comment')); $model = new Model(array('ds' => 'test_suite', 'name' => 'Comment'));
$result = $this->Task->findBelongsTo($model, array()); $result = $this->Task->findBelongsTo($model, array());
@ -347,7 +358,6 @@ class ModelTaskTest extends CakeTestCase {
); );
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread')); $model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$result = $this->Task->findBelongsTo($model, array()); $result = $this->Task->findBelongsTo($model, array());
$expected = array( $expected = array(
@ -366,7 +376,8 @@ class ModelTaskTest extends CakeTestCase {
* test that hasOne and/or hasMany relations are generated properly. * test that hasOne and/or hasMany relations are generated properly.
* *
* @return void * @return void
**/ * @access public
*/
function testHasManyHasOneGeneration() { function testHasManyHasOneGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Article')); $model = new Model(array('ds' => 'test_suite', 'name' => 'Article'));
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
@ -390,7 +401,6 @@ class ModelTaskTest extends CakeTestCase {
); );
$this->assertEqual($result, $expected); $this->assertEqual($result, $expected);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread')); $model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$result = $this->Task->findHasOneAndMany($model, array()); $result = $this->Task->findHasOneAndMany($model, array());
$expected = array( $expected = array(
@ -413,10 +423,11 @@ class ModelTaskTest extends CakeTestCase {
} }
/** /**
* test that habtm generation works * Test that HABTM generation works
* *
* @return void * @return void
**/ * @access public
*/
function testHasAndBelongsToManyGeneration() { function testHasAndBelongsToManyGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Article')); $model = new Model(array('ds' => 'test_suite', 'name' => 'Article'));
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
@ -440,7 +451,8 @@ class ModelTaskTest extends CakeTestCase {
* test non interactive doAssociations * test non interactive doAssociations
* *
* @return void * @return void
**/ * @access public
*/
function testDoAssociationsNonInteractive() { function testDoAssociationsNonInteractive() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->interactive = false; $this->Task->interactive = false;
@ -464,14 +476,14 @@ class ModelTaskTest extends CakeTestCase {
), ),
), ),
); );
} }
/** /**
* Ensure that the fixutre object is correctly called. * Ensure that the fixutre object is correctly called.
* *
* @return void * @return void
**/ * @access public
*/
function testBakeFixture() { function testBakeFixture() {
$this->Task->Fixture->expectAt(0, 'bake', array('Article', 'articles')); $this->Task->Fixture->expectAt(0, 'bake', array('Article', 'articles'));
$this->Task->bakeFixture('Article', 'articles'); $this->Task->bakeFixture('Article', 'articles');
@ -484,7 +496,8 @@ class ModelTaskTest extends CakeTestCase {
* Ensure that the test object is correctly called. * Ensure that the test object is correctly called.
* *
* @return void * @return void
**/ * @access public
*/
function testBakeTest() { function testBakeTest() {
$this->Task->Test->expectAt(0, 'bake', array('Model', 'Article')); $this->Task->Test->expectAt(0, 'bake', array('Model', 'Article'));
$this->Task->bakeTest('Article'); $this->Task->bakeTest('Article');
@ -498,7 +511,8 @@ class ModelTaskTest extends CakeTestCase {
* a question for the hasOne is also not asked. * a question for the hasOne is also not asked.
* *
* @return void * @return void
**/ * @access public
*/
function testConfirmAssociations() { function testConfirmAssociations() {
$associations = array( $associations = array(
'hasOne' => array( 'hasOne' => array(
@ -538,7 +552,8 @@ class ModelTaskTest extends CakeTestCase {
* test that inOptions generates questions and only accepts a valid answer * test that inOptions generates questions and only accepts a valid answer
* *
* @return void * @return void
**/ * @access public
*/
function testInOptions() { function testInOptions() {
$options = array('one', 'two', 'three'); $options = array('one', 'two', 'three');
$this->Task->expectAt(0, 'out', array('1. one')); $this->Task->expectAt(0, 'out', array('1. one'));
@ -558,7 +573,8 @@ class ModelTaskTest extends CakeTestCase {
* test baking validation * test baking validation
* *
* @return void * @return void
**/ * @access public
*/
function testBakeValidation() { function testBakeValidation() {
$validate = array( $validate = array(
'name' => array( 'name' => array(
@ -586,7 +602,8 @@ class ModelTaskTest extends CakeTestCase {
* test baking relations * test baking relations
* *
* @return void * @return void
**/ * @access public
*/
function testBakeRelations() { function testBakeRelations() {
$associations = array( $associations = array(
'belongsTo' => array( 'belongsTo' => array(
@ -640,7 +657,8 @@ class ModelTaskTest extends CakeTestCase {
* test bake() with a -plugin param * test bake() with a -plugin param
* *
* @return void * @return void
**/ * @access public
*/
function testBakeWithPlugin() { function testBakeWithPlugin() {
$this->Task->plugin = 'ControllerTest'; $this->Task->plugin = 'ControllerTest';
@ -660,7 +678,8 @@ class ModelTaskTest extends CakeTestCase {
* test that execute passes runs bake depending with named model. * test that execute passes runs bake depending with named model.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithNamedModel() { function testExecuteWithNamedModel() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -675,7 +694,8 @@ class ModelTaskTest extends CakeTestCase {
* test that execute runs all() when args[0] = all * test that execute runs all() when args[0] = all
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteIntoAll() { function testExecuteIntoAll() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -707,7 +727,8 @@ class ModelTaskTest extends CakeTestCase {
* test the interactive side of bake. * test the interactive side of bake.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteIntoInteractive() { function testExecuteIntoInteractive() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';
@ -736,7 +757,8 @@ class ModelTaskTest extends CakeTestCase {
* test using bake interactively with a table that does not exist. * test using bake interactively with a table that does not exist.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithNonExistantTableName() { function testExecuteWithNonExistantTableName() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/'; $this->Task->path = '/my/path/';

View file

@ -72,7 +72,8 @@ class PluginTaskTest extends CakeTestCase {
* startCase methods * startCase methods
* *
* @return void * @return void
**/ * @access public
*/
function startCase() { function startCase() {
$this->_paths = $paths = App::path('plugins'); $this->_paths = $paths = App::path('plugins');
$this->_testPath = array_push($paths, TMP . 'tests' . DS); $this->_testPath = array_push($paths, TMP . 'tests' . DS);
@ -83,7 +84,8 @@ class PluginTaskTest extends CakeTestCase {
* endCase * endCase
* *
* @return void * @return void
**/ * @access public
*/
function endCase() { function endCase() {
App::build(array('plugins' => $this->_paths)); App::build(array('plugins' => $this->_paths));
} }
@ -102,7 +104,8 @@ class PluginTaskTest extends CakeTestCase {
* test bake() * test bake()
* *
* @return void * @return void
**/ * @access public
*/
function testBakeFoldersAndFiles() { function testBakeFoldersAndFiles() {
$this->Task->setReturnValueAt(0, 'in', $this->_testPath); $this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y'); $this->Task->setReturnValueAt(1, 'in', 'y');
@ -196,7 +199,8 @@ class PluginTaskTest extends CakeTestCase {
* test execute with no args, flowing into interactive, * test execute with no args, flowing into interactive,
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithNoArgs() { function testExecuteWithNoArgs() {
$this->Task->setReturnValueAt(0, 'in', 'TestPlugin'); $this->Task->setReturnValueAt(0, 'in', 'TestPlugin');
$this->Task->setReturnValueAt(1, 'in', '3'); $this->Task->setReturnValueAt(1, 'in', '3');
@ -221,7 +225,8 @@ class PluginTaskTest extends CakeTestCase {
* Test Execute * Test Execute
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithOneArg() { function testExecuteWithOneArg() {
$this->Task->setReturnValueAt(0, 'in', $this->_testPath); $this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y'); $this->Task->setReturnValueAt(1, 'in', 'y');
@ -245,7 +250,8 @@ class PluginTaskTest extends CakeTestCase {
* test execute chaining into MVC parts * test execute chaining into MVC parts
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithTwoArgs() { function testExecuteWithTwoArgs() {
$this->Task->Model =& new PluginTestMockModelTask(); $this->Task->Model =& new PluginTestMockModelTask();
$this->Task->setReturnValueAt(0, 'in', $this->_testPath); $this->Task->setReturnValueAt(0, 'in', $this->_testPath);

View file

@ -84,7 +84,8 @@ class ProjectTaskTest extends CakeTestCase {
* creates a test project that is used for testing project task. * creates a test project that is used for testing project task.
* *
* @return void * @return void
**/ * @access protected
*/
function _setupTestProject() { function _setupTestProject() {
$skel = CAKE_CORE_INCLUDE_PATH . DS . CAKE . 'console' . DS . 'templates' . DS . 'skel'; $skel = CAKE_CORE_INCLUDE_PATH . DS . CAKE . 'console' . DS . 'templates' . DS . 'skel';
$this->Task->setReturnValueAt(0, 'in', 'y'); $this->Task->setReturnValueAt(0, 'in', 'y');
@ -96,7 +97,8 @@ class ProjectTaskTest extends CakeTestCase {
* test bake() method and directory creation. * test bake() method and directory creation.
* *
* @return void * @return void
**/ * @access public
*/
function testBake() { function testBake() {
$this->_setupTestProject(); $this->_setupTestProject();
@ -113,11 +115,57 @@ class ProjectTaskTest extends CakeTestCase {
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s'); $this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
} }
/**
* test bake() method with -empty flag, directory creation and empty files.
*
* @return void
* @access public
*/
function testBakeEmptyFlag() {
$this->Task->params['empty'] = true;
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app';
$this->assertTrue(is_dir($path), 'No project dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers'), 'No controllers dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers' . DS .'components'), 'No components dir %s');
$this->assertTrue(is_dir($path . DS . 'models'), 'No models dir %s');
$this->assertTrue(is_dir($path . DS . 'views'), 'No views dir %s');
$this->assertTrue(is_dir($path . DS . 'views' . DS . 'helpers'), 'No helpers dir %s');
$this->assertTrue(is_dir($path . DS . 'tests'), 'No tests dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases'), 'No cases dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'groups'), 'No groups dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
$this->assertTrue(is_file($path . DS . 'controllers' . DS .'components' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'locale' . DS . 'eng' . DS . 'LC_MESSAGES' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'models' . DS . 'behaviors' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'models' . DS . 'datasources' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'plugins' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'behaviors' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'components' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'controllers' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'datasources' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'helpers' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'models' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'shells' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'fixtures' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'groups' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'vendors' . DS . 'css' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'vendors' . DS . 'img' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'vendors' . DS . 'js' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'vendors' . DS . 'shells' . DS . 'tasks' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'views' . DS . 'errors' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'views' . DS . 'helpers' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'views' . DS . 'scaffolds' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'webroot' . DS . 'js' . DS . 'empty'), 'No empty file in dir %s');
}
/** /**
* test generation of Security.salt * test generation of Security.salt
* *
* @return void * @return void
**/ * @access public
*/
function testSecuritySaltGeneration() { function testSecuritySaltGeneration() {
$this->_setupTestProject(); $this->_setupTestProject();
@ -130,11 +178,33 @@ class ProjectTaskTest extends CakeTestCase {
$this->assertNoPattern('/DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi/', $contents, 'Default Salt left behind. %s'); $this->assertNoPattern('/DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi/', $contents, 'Default Salt left behind. %s');
} }
/**
* Test that index.php is generated correctly.
*
* @return void
* @access public
*/
function testIndexPhpGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$this->Task->corePath($path);
$file =& new File($path . 'webroot' . DS . 'index.php');
$contents = $file->read();
$this->assertNoPattern('/define\(\'CAKE_CORE_INCLUDE_PATH\', \'ROOT/', $contents);
$file =& new File($path . 'webroot' . DS . 'test.php');
$contents = $file->read();
$this->assertNoPattern('/define\(\'CAKE_CORE_INCLUDE_PATH\', \'ROOT/', $contents);
}
/** /**
* test getPrefix method, and that it returns Routing.prefix or writes to config file. * test getPrefix method, and that it returns Routing.prefix or writes to config file.
* *
* @return void * @return void
**/ * @access public
*/
function testGetPrefix() { function testGetPrefix() {
Configure::write('Routing.prefixes', array('admin')); Configure::write('Routing.prefixes', array('admin'));
$result = $this->Task->getPrefix(); $result = $this->Task->getPrefix();
@ -156,7 +226,8 @@ class ProjectTaskTest extends CakeTestCase {
* test cakeAdmin() writing core.php * test cakeAdmin() writing core.php
* *
* @return void * @return void
**/ * @access public
*/
function testCakeAdmin() { function testCakeAdmin() {
$file =& new File(CONFIGS . 'core.php'); $file =& new File(CONFIGS . 'core.php');
$contents = $file->read();; $contents = $file->read();;
@ -176,7 +247,8 @@ class ProjectTaskTest extends CakeTestCase {
* test getting the prefix with more than one prefix setup * test getting the prefix with more than one prefix setup
* *
* @return void * @return void
**/ * @access public
*/
function testGetPrefixWithMultiplePrefixes() { function testGetPrefixWithMultiplePrefixes() {
Configure::write('Routing.prefixes', array('admin', 'ninja', 'shinobi')); Configure::write('Routing.prefixes', array('admin', 'ninja', 'shinobi'));
$this->_setupTestProject(); $this->_setupTestProject();
@ -191,7 +263,8 @@ class ProjectTaskTest extends CakeTestCase {
* Test execute method with one param to destination folder. * Test execute method with one param to destination folder.
* *
* @return void * @return void
**/ * @access public
*/
function testExecute() { function testExecute() {
$this->Task->params['skel'] = CAKE_CORE_INCLUDE_PATH . DS . CAKE . DS . 'console' . DS. 'templates' . DS . 'skel'; $this->Task->params['skel'] = CAKE_CORE_INCLUDE_PATH . DS . CAKE . DS . 'console' . DS. 'templates' . DS . 'skel';
$this->Task->params['working'] = TMP . 'tests' . DS; $this->Task->params['working'] = TMP . 'tests' . DS;

View file

@ -81,7 +81,8 @@ class TemplateTaskTest extends CakeTestCase {
* test that set sets variables * test that set sets variables
* *
* @return void * @return void
**/ * @access public
*/
function testSet() { function testSet() {
$this->Task->set('one', 'two'); $this->Task->set('one', 'two');
$this->assertTrue(isset($this->Task->templateVars['one'])); $this->assertTrue(isset($this->Task->templateVars['one']));
@ -98,7 +99,8 @@ class TemplateTaskTest extends CakeTestCase {
* test finding themes installed in * test finding themes installed in
* *
* @return void * @return void
**/ * @access public
*/
function testFindingInstalledThemesForBake() { function testFindingInstalledThemesForBake() {
$consoleLibs = CAKE_CORE_INCLUDE_PATH . DS . CAKE . 'console' . DS; $consoleLibs = CAKE_CORE_INCLUDE_PATH . DS . CAKE . 'console' . DS;
$this->Task->Dispatch->shellPaths = array($consoleLibs); $this->Task->Dispatch->shellPaths = array($consoleLibs);
@ -111,7 +113,8 @@ class TemplateTaskTest extends CakeTestCase {
* that the user is not bugged. If there are more, find and return the correct theme name * that the user is not bugged. If there are more, find and return the correct theme name
* *
* @return void * @return void
**/ * @access public
*/
function testGetThemePath() { function testGetThemePath() {
$defaultTheme = CAKE_CORE_INCLUDE_PATH . DS . dirname(CONSOLE_LIBS) . 'templates' . DS . 'default' .DS; $defaultTheme = CAKE_CORE_INCLUDE_PATH . DS . dirname(CONSOLE_LIBS) . 'templates' . DS . 'default' .DS;
$this->Task->templatePaths = array('default' => $defaultTheme); $this->Task->templatePaths = array('default' => $defaultTheme);
@ -136,7 +139,8 @@ class TemplateTaskTest extends CakeTestCase {
* test generate * test generate
* *
* @return void * @return void
**/ * @access public
*/
function testGenerate() { function testGenerate() {
App::build(array( App::build(array(
'shells' => array( 'shells' => array(
@ -155,7 +159,8 @@ class TemplateTaskTest extends CakeTestCase {
* ensure fallback to default works. * ensure fallback to default works.
* *
* @return void * @return void
**/ * @access public
*/
function testGenerateWithTemplateFallbacks() { function testGenerateWithTemplateFallbacks() {
App::build(array( App::build(array(
'shells' => array( 'shells' => array(

View file

@ -49,17 +49,48 @@ Mock::generatePartial(
); );
/** /**
* Test subject models for fixture generation * Test Article model
**/ *
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskArticle extends Model { class TestTaskArticle extends Model {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'TestTaskArticle'; var $name = 'TestTaskArticle';
/**
* Table name to use
*
* @var string
* @access public
*/
var $useTable = 'articles'; var $useTable = 'articles';
/**
* HasMany Associations
*
* @var array
* @access public
*/
var $hasMany = array( var $hasMany = array(
'Comment' => array( 'Comment' => array(
'className' => 'TestTask.TestTaskComment', 'className' => 'TestTask.TestTaskComment',
'foreignKey' => 'article_id', 'foreignKey' => 'article_id',
) )
); );
/**
* Has and Belongs To Many Associations
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array( var $hasAndBelongsToMany = array(
'Tag' => array( 'Tag' => array(
'className' => 'TestTaskTag', 'className' => 'TestTaskTag',
@ -68,19 +99,65 @@ class TestTaskArticle extends Model {
'associationForeignKey' => 'tag_id' 'associationForeignKey' => 'tag_id'
) )
); );
/**
* Example public method
*
* @return void
* @access public
*/
function doSomething() { function doSomething() {
} }
/**
* Example Secondary public method
*
* @return void
* @access public
*/
function doSomethingElse() { function doSomethingElse() {
} }
function _innerMethod() {
/**
* Example protected method
*
* @return void
* @access protected
*/
function _innerMethod() {
} }
} }
/**
* Tag Testing Model
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskTag extends Model { class TestTaskTag extends Model {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'TestTaskTag'; var $name = 'TestTaskTag';
/**
* Table name
*
* @var string
* @access public
*/
var $useTable = 'tags'; var $useTable = 'tags';
/**
* Has and Belongs To Many Associations
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array( var $hasAndBelongsToMany = array(
'Article' => array( 'Article' => array(
'className' => 'TestTaskArticle', 'className' => 'TestTaskArticle',
@ -92,14 +169,44 @@ class TestTaskTag extends Model {
} }
/** /**
* Simulated Plugin * Simulated plugin
**/ *
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskAppModel extends Model { class TestTaskAppModel extends Model {
} }
/**
* Testing AppMode (TaskComment)
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskComment extends TestTaskAppModel { class TestTaskComment extends TestTaskAppModel {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'TestTaskComment'; var $name = 'TestTaskComment';
/**
* Table name
*
* @var string
* @access public
*/
var $useTable = 'comments'; var $useTable = 'comments';
/**
* Belongs To Associations
*
* @var array
* @access public
*/
var $belongsTo = array( var $belongsTo = array(
'Article' => array( 'Article' => array(
'className' => 'TestTaskArticle', 'className' => 'TestTaskArticle',
@ -108,8 +215,28 @@ class TestTaskComment extends TestTaskAppModel {
); );
} }
/**
* Test Task Comments Controller
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskCommentsController extends Controller { class TestTaskCommentsController extends Controller {
/**
* Controller Name
*
* @var string
* @access public
*/
var $name = 'TestTaskComments'; var $name = 'TestTaskComments';
/**
* Models to use
*
* @var array
* @access public
*/
var $uses = array('TestTaskComment', 'TestTaskTag'); var $uses = array('TestTaskComment', 'TestTaskTag');
} }
@ -121,6 +248,12 @@ class TestTaskCommentsController extends Controller {
*/ */
class TestTaskTest extends CakeTestCase { class TestTaskTest extends CakeTestCase {
/**
* Fixtures
*
* @var string
* @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag'); var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/** /**
@ -150,8 +283,8 @@ class TestTaskTest extends CakeTestCase {
/** /**
* Test that file path generation doesn't continuously append paths. * Test that file path generation doesn't continuously append paths.
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testFilePathGeneration() { function testFilePathGeneration() {
$file = TESTS . 'cases' . DS . 'models' . DS . 'my_class.test.php'; $file = TESTS . 'cases' . DS . 'models' . DS . 'my_class.test.php';
@ -176,7 +309,7 @@ class TestTaskTest extends CakeTestCase {
* methods into the test case. * methods into the test case.
* *
* @return void * @return void
**/ */
function testMethodIntrospection() { function testMethodIntrospection() {
$result = $this->Task->getTestableMethods('TestTaskArticle'); $result = $this->Task->getTestableMethods('TestTaskArticle');
$expected = array('dosomething', 'dosomethingelse'); $expected = array('dosomething', 'dosomethingelse');
@ -187,7 +320,8 @@ class TestTaskTest extends CakeTestCase {
* test that the generation of fixtures works correctly. * test that the generation of fixtures works correctly.
* *
* @return void * @return void
**/ * @access public
*/
function testFixtureArrayGenerationFromModel() { function testFixtureArrayGenerationFromModel() {
$subject = ClassRegistry::init('TestTaskArticle'); $subject = ClassRegistry::init('TestTaskArticle');
$result = $this->Task->generateFixtureList($subject); $result = $this->Task->generateFixtureList($subject);
@ -201,7 +335,8 @@ class TestTaskTest extends CakeTestCase {
* test that the generation of fixtures works correctly. * test that the generation of fixtures works correctly.
* *
* @return void * @return void
**/ * @access public
*/
function testFixtureArrayGenerationFromController() { function testFixtureArrayGenerationFromController() {
$subject = new TestTaskCommentsController(); $subject = new TestTaskCommentsController();
$result = $this->Task->generateFixtureList($subject); $result = $this->Task->generateFixtureList($subject);
@ -215,7 +350,8 @@ class TestTaskTest extends CakeTestCase {
* test user interaction to get object type * test user interaction to get object type
* *
* @return void * @return void
**/ * @access public
*/
function testGetObjectType() { function testGetObjectType() {
$this->Task->expectOnce('_stop'); $this->Task->expectOnce('_stop');
$this->Task->setReturnValueAt(0, 'in', 'q'); $this->Task->setReturnValueAt(0, 'in', 'q');
@ -230,7 +366,8 @@ class TestTaskTest extends CakeTestCase {
* creating test subjects should clear the registry so the registry is always fresh * creating test subjects should clear the registry so the registry is always fresh
* *
* @return void * @return void
**/ * @access public
*/
function testRegistryClearWhenBuildingTestObjects() { function testRegistryClearWhenBuildingTestObjects() {
ClassRegistry::flush(); ClassRegistry::flush();
$model = ClassRegistry::init('TestTaskComment'); $model = ClassRegistry::init('TestTaskComment');
@ -254,7 +391,8 @@ class TestTaskTest extends CakeTestCase {
* test that getClassName returns the user choice as a classname. * test that getClassName returns the user choice as a classname.
* *
* @return void * @return void
**/ * @access public
*/
function testGetClassName() { function testGetClassName() {
$objects = App::objects('model'); $objects = App::objects('model');
$skip = $this->skipIf(empty($objects), 'No models in app, this test will fail. %s'); $skip = $this->skipIf(empty($objects), 'No models in app, this test will fail. %s');
@ -275,7 +413,8 @@ class TestTaskTest extends CakeTestCase {
* Test the user interaction for defining additional fixtures. * Test the user interaction for defining additional fixtures.
* *
* @return void * @return void
**/ * @access public
*/
function testGetUserFixtures() { function testGetUserFixtures() {
$this->Task->setReturnValueAt(0, 'in', 'y'); $this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'app.pizza, app.topping, app.side_dish'); $this->Task->setReturnValueAt(1, 'in', 'app.pizza, app.topping, app.side_dish');
@ -288,7 +427,8 @@ class TestTaskTest extends CakeTestCase {
* test that resolving classnames works * test that resolving classnames works
* *
* @return void * @return void
**/ * @access public
*/
function testGetRealClassname() { function testGetRealClassname() {
$result = $this->Task->getRealClassname('Model', 'Post'); $result = $this->Task->getRealClassname('Model', 'Post');
$this->assertEqual($result, 'Post'); $this->assertEqual($result, 'Post');
@ -311,7 +451,8 @@ class TestTaskTest extends CakeTestCase {
* as PHP4 classnames are all lower case, breaking the plugin path inflection. * as PHP4 classnames are all lower case, breaking the plugin path inflection.
* *
* @return void * @return void
**/ * @access public
*/
function testBakeModelTest() { function testBakeModelTest() {
$this->Task->setReturnValue('createFile', true); $this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('isLoadableClass', true); $this->Task->setReturnValue('isLoadableClass', true);
@ -344,7 +485,8 @@ class TestTaskTest extends CakeTestCase {
* causing issues with inflection of path name from classname. * causing issues with inflection of path name from classname.
* *
* @return void * @return void
**/ * @access public
*/
function testBakeControllerTest() { function testBakeControllerTest() {
$this->Task->setReturnValue('createFile', true); $this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('isLoadableClass', true); $this->Task->setReturnValue('isLoadableClass', true);
@ -377,7 +519,8 @@ class TestTaskTest extends CakeTestCase {
* test Constructor generation ensure that constructClasses is called for controllers * test Constructor generation ensure that constructClasses is called for controllers
* *
* @return void * @return void
**/ * @access public
*/
function testGenerateContsructor() { function testGenerateContsructor() {
$result = $this->Task->generateConstructor('controller', 'PostsController'); $result = $this->Task->generateConstructor('controller', 'PostsController');
$expected = "new TestPostsController();\n\t\t\$this->Posts->constructClasses();\n"; $expected = "new TestPostsController();\n\t\t\$this->Posts->constructClasses();\n";
@ -396,7 +539,8 @@ class TestTaskTest extends CakeTestCase {
* Test that mock class generation works for the appropriate classes * Test that mock class generation works for the appropriate classes
* *
* @return void * @return void
**/ * @access public
*/
function testMockClassGeneration() { function testMockClassGeneration() {
$result = $this->Task->hasMockClass('controller'); $result = $this->Task->hasMockClass('controller');
$this->assertTrue($result); $this->assertTrue($result);
@ -406,7 +550,8 @@ class TestTaskTest extends CakeTestCase {
* test bake() with a -plugin param * test bake() with a -plugin param
* *
* @return void * @return void
**/ * @access public
*/
function testBakeWithPlugin() { function testBakeWithPlugin() {
$this->Task->plugin = 'TestTest'; $this->Task->plugin = 'TestTest';
@ -419,7 +564,8 @@ class TestTaskTest extends CakeTestCase {
* Test filename generation for each type + plugins * Test filename generation for each type + plugins
* *
* @return void * @return void
**/ * @access public
*/
function testTestCaseFileName() { function testTestCaseFileName() {
$this->Task->path = '/my/path/tests/'; $this->Task->path = '/my/path/tests/';
@ -453,7 +599,8 @@ class TestTaskTest extends CakeTestCase {
* test execute with a type defined * test execute with a type defined
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithOneArg() { function testExecuteWithOneArg() {
$this->Task->args[0] = 'Model'; $this->Task->args[0] = 'Model';
$this->Task->setReturnValueAt(0, 'in', 'TestTaskTag'); $this->Task->setReturnValueAt(0, 'in', 'TestTaskTag');
@ -466,7 +613,8 @@ class TestTaskTest extends CakeTestCase {
* test execute with type and class name defined * test execute with type and class name defined
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithTwoArgs() { function testExecuteWithTwoArgs() {
$this->Task->args = array('Model', 'TestTaskTag'); $this->Task->args = array('Model', 'TestTaskTag');
$this->Task->setReturnValueAt(0, 'in', 'TestTaskTag'); $this->Task->setReturnValueAt(0, 'in', 'TestTaskTag');

View file

@ -49,10 +49,36 @@ Mock::generatePartial(
Mock::generate('ControllerTask', 'ViewTaskMockControllerTask'); Mock::generate('ControllerTask', 'ViewTaskMockControllerTask');
Mock::generate('ProjectTask', 'ViewTaskMockProjectTask'); Mock::generate('ProjectTask', 'ViewTaskMockProjectTask');
/**
* Test View Task Comment Model
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskComment extends Model { class ViewTaskComment extends Model {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'ViewTaskComment'; var $name = 'ViewTaskComment';
/**
* Table name
*
* @var string
* @access public
*/
var $useTable = 'comments'; var $useTable = 'comments';
/**
* Belongs To Associations
*
* @var array
* @access public
*/
var $belongsTo = array( var $belongsTo = array(
'Article' => array( 'Article' => array(
'className' => 'ViewTaskArticle', 'className' => 'ViewTaskArticle',
@ -61,46 +87,143 @@ class ViewTaskComment extends Model {
); );
} }
/**
* Test View Task Article Model
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskArticle extends Model { class ViewTaskArticle extends Model {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'ViewTaskArticle'; var $name = 'ViewTaskArticle';
/**
* Table name
*
* @var string
* @access public
*/
var $useTable = 'articles'; var $useTable = 'articles';
} }
/**
* Test View Task Comments Controller
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskCommentsController extends Controller { class ViewTaskCommentsController extends Controller {
/**
* Controller name
*
* @var string
* @access public
*/
var $name = 'ViewTaskComments'; var $name = 'ViewTaskComments';
/**
* Testing public controller action
*
* @return void
* @access public
*/
function index() { function index() {
} }
function add() {
/**
* Testing public controller action
*
* @return void
* @access public
*/
function add() {
} }
} }
/**
* Test View Task Articles Controller
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskArticlesController extends Controller { class ViewTaskArticlesController extends Controller {
/**
* Controller name
*
* @var string
* @access public
*/
var $name = 'ViewTaskArticles'; var $name = 'ViewTaskArticles';
/**
* Test public controller action
*
* @return void
* @access public
*/
function index() { function index() {
} }
/**
* Test public controller action
*
* @return void
* @access public
*/
function add() { function add() {
} }
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_index() { function admin_index() {
} }
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_add() { function admin_add() {
} }
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_view() { function admin_view() {
} }
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_edit() { function admin_edit() {
} }
function admin_delete() {
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_delete() {
} }
} }
@ -112,6 +235,12 @@ class ViewTaskArticlesController extends Controller {
*/ */
class ViewTaskTest extends CakeTestCase { class ViewTaskTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag'); var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/** /**
@ -148,7 +277,8 @@ class ViewTaskTest extends CakeTestCase {
* Test getContent and parsing of Templates. * Test getContent and parsing of Templates.
* *
* @return void * @return void
**/ * @access public
*/
function testGetContent() { function testGetContent() {
$vars = array( $vars = array(
'modelClass' => 'TestViewModel', 'modelClass' => 'TestViewModel',
@ -178,7 +308,8 @@ class ViewTaskTest extends CakeTestCase {
* test getContent() using an admin_prefixed action. * test getContent() using an admin_prefixed action.
* *
* @return void * @return void
**/ * @access public
*/
function testGetContentWithAdminAction() { function testGetContentWithAdminAction() {
$_back = Configure::read('Routing'); $_back = Configure::read('Routing');
Configure::write('Routing.prefixes', array('admin')); Configure::write('Routing.prefixes', array('admin'));
@ -212,7 +343,8 @@ class ViewTaskTest extends CakeTestCase {
* test Bake method * test Bake method
* *
* @return void * @return void
**/ * @access public
*/
function testBake() { function testBake() {
$this->Task->controllerName = 'ViewTaskComments'; $this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments'; $this->Task->controllerPath = 'view_task_comments';
@ -237,7 +369,8 @@ class ViewTaskTest extends CakeTestCase {
* test bake() with a -plugin param * test bake() with a -plugin param
* *
* @return void * @return void
**/ * @access public
*/
function testBakeWithPlugin() { function testBakeWithPlugin() {
$this->Task->controllerName = 'ViewTaskComments'; $this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments'; $this->Task->controllerPath = 'view_task_comments';
@ -252,7 +385,8 @@ class ViewTaskTest extends CakeTestCase {
* test bake actions baking multiple actions. * test bake actions baking multiple actions.
* *
* @return void * @return void
**/ * @access public
*/
function testBakeActions() { function testBakeActions() {
$this->Task->controllerName = 'ViewTaskComments'; $this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments'; $this->Task->controllerPath = 'view_task_comments';
@ -277,7 +411,8 @@ class ViewTaskTest extends CakeTestCase {
* test baking a customAction (non crud) * test baking a customAction (non crud)
* *
* @return void * @return void
**/ * @access public
*/
function testCustomAction() { function testCustomAction() {
$this->Task->controllerName = 'ViewTaskComments'; $this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments'; $this->Task->controllerPath = 'view_task_comments';
@ -295,7 +430,8 @@ class ViewTaskTest extends CakeTestCase {
* Test all() * Test all()
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteIntoAll() { function testExecuteIntoAll() {
$this->Task->args[0] = 'all'; $this->Task->args[0] = 'all';
@ -313,7 +449,8 @@ class ViewTaskTest extends CakeTestCase {
* test `cake bake view $controller view` * test `cake bake view $controller view`
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithActionParam() { function testExecuteWithActionParam() {
$this->Task->args[0] = 'ViewTaskComments'; $this->Task->args[0] = 'ViewTaskComments';
$this->Task->args[1] = 'view'; $this->Task->args[1] = 'view';
@ -328,7 +465,8 @@ class ViewTaskTest extends CakeTestCase {
* Ensure that views are only baked for actions that exist in the controller. * Ensure that views are only baked for actions that exist in the controller.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithController() { function testExecuteWithController() {
$this->Task->args[0] = 'ViewTaskComments'; $this->Task->args[0] = 'ViewTaskComments';
@ -344,7 +482,8 @@ class ViewTaskTest extends CakeTestCase {
* Which only bakes admin methods, not non-admin methods. * Which only bakes admin methods, not non-admin methods.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithControllerAndAdminFlag() { function testExecuteWithControllerAndAdminFlag() {
$_back = Configure::read('Routing'); $_back = Configure::read('Routing');
Configure::write('Routing.prefixes', array('admin')); Configure::write('Routing.prefixes', array('admin'));
@ -366,7 +505,8 @@ class ViewTaskTest extends CakeTestCase {
* test execute into interactive. * test execute into interactive.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteInteractive() { function testExecuteInteractive() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->args = array(); $this->Task->args = array();
@ -403,7 +543,8 @@ class ViewTaskTest extends CakeTestCase {
* test `cake bake view posts index list` * test `cake bake view posts index list`
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteWithAlternateTemplates() { function testExecuteWithAlternateTemplates() {
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';
$this->Task->args = array('ViewTaskComments', 'index', 'list'); $this->Task->args = array('ViewTaskComments', 'index', 'list');
@ -421,7 +562,8 @@ class ViewTaskTest extends CakeTestCase {
* test execute into interactive() with admin methods. * test execute into interactive() with admin methods.
* *
* @return void * @return void
**/ * @access public
*/
function testExecuteInteractiveWithAdmin() { function testExecuteInteractiveWithAdmin() {
Configure::write('Routing.prefixes', array('admin')); Configure::write('Routing.prefixes', array('admin'));
$this->Task->connection = 'test_suite'; $this->Task->connection = 'test_suite';

View file

@ -41,8 +41,8 @@ class TestDispatcher extends Dispatcher {
* @param mixed $controller * @param mixed $controller
* @param mixed $params * @param mixed $params
* @param mixed $missingAction * @param mixed $missingAction
* @access protected
* @return void * @return void
* @access protected
*/ */
function _invoke(&$controller, $params) { function _invoke(&$controller, $params) {
restore_error_handler(); restore_error_handler();
@ -60,8 +60,8 @@ class TestDispatcher extends Dispatcher {
* cakeError method * cakeError method
* *
* @param mixed $filename * @param mixed $filename
* @access public
* @return void * @return void
* @access public
*/ */
function cakeError($filename, $params) { function cakeError($filename, $params) {
return array($filename, $params); return array($filename, $params);
@ -70,8 +70,8 @@ class TestDispatcher extends Dispatcher {
/** /**
* _stop method * _stop method
* *
* @access protected
* @return void * @return void
* @access protected
*/ */
function _stop() { function _stop() {
return true; return true;
@ -114,8 +114,8 @@ class MyPluginController extends MyPluginAppController {
/** /**
* index method * index method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function index() { function index() {
return true; return true;
@ -124,8 +124,8 @@ class MyPluginController extends MyPluginAppController {
/** /**
* add method * add method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function add() { function add() {
return true; return true;
@ -135,8 +135,8 @@ class MyPluginController extends MyPluginAppController {
* admin_add method * admin_add method
* *
* @param mixed $id * @param mixed $id
* @access public
* @return void * @return void
* @access public
*/ */
function admin_add($id = null) { function admin_add($id = null) {
return $id; return $id;
@ -171,8 +171,8 @@ class SomePagesController extends AppController {
* display method * display method
* *
* @param mixed $page * @param mixed $page
* @access public
* @return void * @return void
* @access public
*/ */
function display($page = null) { function display($page = null) {
return $page; return $page;
@ -181,8 +181,8 @@ class SomePagesController extends AppController {
/** /**
* index method * index method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function index() { function index() {
return true; return true;
@ -191,8 +191,8 @@ class SomePagesController extends AppController {
/** /**
* protected method * protected method
* *
* @access protected
* @return void * @return void
* @access protected
*/ */
function _protected() { function _protected() {
return true; return true;
@ -201,8 +201,8 @@ class SomePagesController extends AppController {
/** /**
* redirect method overriding * redirect method overriding
* *
* @access public
* @return void * @return void
* @access public
*/ */
function redirect() { function redirect() {
echo 'this should not be accessible'; echo 'this should not be accessible';
@ -237,8 +237,8 @@ class OtherPagesController extends MyPluginAppController {
* display method * display method
* *
* @param mixed $page * @param mixed $page
* @access public
* @return void * @return void
* @access public
*/ */
function display($page = null) { function display($page = null) {
return $page; return $page;
@ -247,8 +247,8 @@ class OtherPagesController extends MyPluginAppController {
/** /**
* index method * index method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function index() { function index() {
return true; return true;
@ -282,8 +282,8 @@ class TestDispatchPagesController extends AppController {
/** /**
* admin_index method * admin_index method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function admin_index() { function admin_index() {
return true; return true;
@ -292,8 +292,8 @@ class TestDispatchPagesController extends AppController {
/** /**
* camelCased method * camelCased method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function camelCased() { function camelCased() {
return true; return true;
@ -336,8 +336,8 @@ class ArticlesTestController extends ArticlesTestAppController {
/** /**
* admin_index method * admin_index method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function admin_index() { function admin_index() {
return true; return true;
@ -379,8 +379,8 @@ class SomePostsController extends AppController {
/** /**
* beforeFilter method * beforeFilter method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function beforeFilter() { function beforeFilter() {
if ($this->params['action'] == 'index') { if ($this->params['action'] == 'index') {
@ -394,8 +394,8 @@ class SomePostsController extends AppController {
/** /**
* index method * index method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function index() { function index() {
return true; return true;
@ -404,8 +404,8 @@ class SomePostsController extends AppController {
/** /**
* change method * change method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function change() { function change() {
return true; return true;
@ -466,8 +466,8 @@ class TestCachedPagesController extends AppController {
/** /**
* index method * index method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function index() { function index() {
$this->render(); $this->render();
@ -476,8 +476,8 @@ class TestCachedPagesController extends AppController {
/** /**
* test_nocache_tags method * test_nocache_tags method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function test_nocache_tags() { function test_nocache_tags() {
$this->render(); $this->render();
@ -486,8 +486,8 @@ class TestCachedPagesController extends AppController {
/** /**
* view method * view method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function view($id = null) { function view($id = null) {
$this->render('index'); $this->render('index');
@ -521,8 +521,8 @@ class TimesheetsController extends AppController {
/** /**
* index method * index method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function index() { function index() {
return true; return true;
@ -540,8 +540,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* setUp method * setUp method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function startTest() { function startTest() {
$this->_get = $_GET; $this->_get = $_GET;
@ -567,8 +567,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* tearDown method * tearDown method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function endTest() { function endTest() {
$_GET = $this->_get; $_GET = $this->_get;
@ -584,8 +584,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testParseParamsWithoutZerosAndEmptyPost method * testParseParamsWithoutZerosAndEmptyPost method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testParseParamsWithoutZerosAndEmptyPost() { function testParseParamsWithoutZerosAndEmptyPost() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -601,8 +601,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testParseParamsReturnsPostedData method * testParseParamsReturnsPostedData method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testParseParamsReturnsPostedData() { function testParseParamsReturnsPostedData() {
$_POST['testdata'] = "My Posted Content"; $_POST['testdata'] = "My Posted Content";
@ -615,8 +615,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testParseParamsWithSingleZero method * testParseParamsWithSingleZero method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testParseParamsWithSingleZero() { function testParseParamsWithSingleZero() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -631,8 +631,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testParseParamsWithManySingleZeros method * testParseParamsWithManySingleZeros method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testParseParamsWithManySingleZeros() { function testParseParamsWithManySingleZeros() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -648,8 +648,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testParseParamsWithManyZerosInEachSectionOfUrl method * testParseParamsWithManyZerosInEachSectionOfUrl method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testParseParamsWithManyZerosInEachSectionOfUrl() { function testParseParamsWithManyZerosInEachSectionOfUrl() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -665,8 +665,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl method * testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl() { function testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -682,8 +682,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testQueryStringOnRoot method * testQueryStringOnRoot method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testQueryStringOnRoot() { function testQueryStringOnRoot() {
Router::reload(); Router::reload();
@ -712,8 +712,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testFileUploadArrayStructure method * testFileUploadArrayStructure method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testFileUploadArrayStructure() { function testFileUploadArrayStructure() {
$_FILES = array('data' => array('name' => array( $_FILES = array('data' => array('name' => array(
@ -965,8 +965,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testGetUrl method * testGetUrl method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testGetUrl() { function testGetUrl() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -1005,8 +1005,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testBaseUrlAndWebrootWithModRewrite method * testBaseUrlAndWebrootWithModRewrite method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testBaseUrlAndWebrootWithModRewrite() { function testBaseUrlAndWebrootWithModRewrite() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -1081,8 +1081,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testBaseUrlwithModRewriteAlias method * testBaseUrlwithModRewriteAlias method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testBaseUrlwithModRewriteAlias() { function testBaseUrlwithModRewriteAlias() {
$_SERVER['DOCUMENT_ROOT'] = '/home/aplusnur/public_html'; $_SERVER['DOCUMENT_ROOT'] = '/home/aplusnur/public_html';
@ -1116,8 +1116,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testBaseUrlAndWebrootWithBaseUrl method * testBaseUrlAndWebrootWithBaseUrl method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testBaseUrlAndWebrootWithBaseUrl() { function testBaseUrlAndWebrootWithBaseUrl() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -1186,8 +1186,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testBaseUrlAndWebrootWithBase method * testBaseUrlAndWebrootWithBase method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testBaseUrlAndWebrootWithBase() { function testBaseUrlAndWebrootWithBase() {
$Dispatcher =& new Dispatcher(); $Dispatcher =& new Dispatcher();
@ -1217,8 +1217,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testMissingController method * testMissingController method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testMissingController() { function testMissingController() {
$Dispatcher =& new TestDispatcher(); $Dispatcher =& new TestDispatcher();
@ -1237,8 +1237,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testPrivate method * testPrivate method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testPrivate() { function testPrivate() {
$Dispatcher =& new TestDispatcher(); $Dispatcher =& new TestDispatcher();
@ -1260,8 +1260,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testMissingAction method * testMissingAction method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testMissingAction() { function testMissingAction() {
$Dispatcher =& new TestDispatcher(); $Dispatcher =& new TestDispatcher();
@ -1298,8 +1298,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testDispatch method * testDispatch method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testDispatch() { function testDispatch() {
$Dispatcher =& new TestDispatcher(); $Dispatcher =& new TestDispatcher();
@ -1353,8 +1353,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testDispatchWithArray method * testDispatchWithArray method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testDispatchWithArray() { function testDispatchWithArray() {
$Dispatcher =& new TestDispatcher(); $Dispatcher =& new TestDispatcher();
@ -1373,8 +1373,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testAdminDispatch method * testAdminDispatch method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testAdminDispatch() { function testAdminDispatch() {
$_POST = array(); $_POST = array();
@ -1404,8 +1404,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testPluginDispatch method * testPluginDispatch method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testPluginDispatch() { function testPluginDispatch() {
$_POST = array(); $_POST = array();
@ -1453,8 +1453,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testAutomaticPluginDispatch method * testAutomaticPluginDispatch method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testAutomaticPluginDispatch() { function testAutomaticPluginDispatch() {
$_POST = array(); $_POST = array();
@ -1491,8 +1491,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testAutomaticPluginControllerDispatch method * testAutomaticPluginControllerDispatch method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testAutomaticPluginControllerDispatch() { function testAutomaticPluginControllerDispatch() {
$_POST = array(); $_POST = array();
@ -1594,7 +1594,8 @@ class DispatcherTest extends CakeTestCase {
* plugin short form instead. * plugin short form instead.
* *
* @return void * @return void
**/ * @access public
*/
function testAutomaticPluginDispatchWithShortAccess() { function testAutomaticPluginDispatchWithShortAccess() {
$_POST = array(); $_POST = array();
$_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php';
@ -1642,8 +1643,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testAutomaticPluginControllerMissingActionDispatch method * testAutomaticPluginControllerMissingActionDispatch method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testAutomaticPluginControllerMissingActionDispatch() { function testAutomaticPluginControllerMissingActionDispatch() {
$_POST = array(); $_POST = array();
@ -1685,8 +1686,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testPrefixProtection method * testPrefixProtection method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testPrefixProtection() { function testPrefixProtection() {
$_POST = array(); $_POST = array();
@ -1715,7 +1716,8 @@ class DispatcherTest extends CakeTestCase {
* undocumented function * undocumented function
* *
* @return void * @return void
**/ * @access public
*/
function testTestPluginDispatch() { function testTestPluginDispatch() {
$Dispatcher =& new TestDispatcher(); $Dispatcher =& new TestDispatcher();
App::build(array( App::build(array(
@ -1734,8 +1736,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testChangingParamsFromBeforeFilter method * testChangingParamsFromBeforeFilter method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testChangingParamsFromBeforeFilter() { function testChangingParamsFromBeforeFilter() {
$_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php';
@ -1768,8 +1770,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testStaticAssets method * testStaticAssets method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testStaticAssets() { function testStaticAssets() {
Router::reload(); Router::reload();
@ -1785,7 +1787,7 @@ class DispatcherTest extends CakeTestCase {
Configure::write('debug', 0); Configure::write('debug', 0);
ob_start(); ob_start();
$Dispatcher->dispatch('/img/test.jpg'); $Dispatcher->dispatch('img/test.jpg');
$result = ob_get_clean(); $result = ob_get_clean();
$file = file_get_contents(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'img' . DS . 'test.jpg'); $file = file_get_contents(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'img' . DS . 'test.jpg');
$this->assertEqual($file, $result); $this->assertEqual($file, $result);
@ -1830,14 +1832,23 @@ class DispatcherTest extends CakeTestCase {
$file = file_get_contents(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' .DS . 'vendors' . DS . 'img' . DS . 'cake.icon.gif'); $file = file_get_contents(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' .DS . 'vendors' . DS . 'img' . DS . 'cake.icon.gif');
$this->assertEqual($file, $result); $this->assertEqual($file, $result);
Configure::write('debug', 2);
$Dispatcher->params = $Dispatcher->parseParams('plugin_js/js/plugin_js.js');
ob_start();
$Dispatcher->cached('plugin_js/js/plugin_js.js');
$result = ob_get_clean();
$expected = "alert('win sauce');";
$this->assertEqual($result, $expected);
header('Content-type: text/html');//reset the header content-type without page can render as plain text. header('Content-type: text/html');//reset the header content-type without page can render as plain text.
} }
/** /**
* testFullPageCachingDispatch method * testFullPageCachingDispatch method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testFullPageCachingDispatch() { function testFullPageCachingDispatch() {
Configure::write('Cache.disable', false); Configure::write('Cache.disable', false);
@ -1972,8 +1983,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testHttpMethodOverrides method * testHttpMethodOverrides method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testHttpMethodOverrides() { function testHttpMethodOverrides() {
Router::reload(); Router::reload();
@ -2027,6 +2038,7 @@ class DispatcherTest extends CakeTestCase {
* Tests that invalid characters cannot be injected into the application base path. * Tests that invalid characters cannot be injected into the application base path.
* *
* @return void * @return void
* @access public
*/ */
function testBasePathInjection() { function testBasePathInjection() {
$self = $_SERVER['PHP_SELF']; $self = $_SERVER['PHP_SELF'];
@ -2043,8 +2055,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* testEnvironmentDetection method * testEnvironmentDetection method
* *
* @access public
* @return void * @return void
* @access public
*/ */
function testEnvironmentDetection() { function testEnvironmentDetection() {
$dispatcher =& new Dispatcher(); $dispatcher =& new Dispatcher();
@ -2149,8 +2161,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* Tests that the Dispatcher does not return an empty action * Tests that the Dispatcher does not return an empty action
* *
* @access private
* @return void * @return void
* @access public
*/ */
function testTrailingSlash() { function testTrailingSlash() {
$_POST = array(); $_POST = array();
@ -2175,8 +2187,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* backupEnvironment method * backupEnvironment method
* *
* @access private
* @return void * @return void
* @access private
*/ */
function __backupEnvironment() { function __backupEnvironment() {
return array( return array(
@ -2190,8 +2202,8 @@ class DispatcherTest extends CakeTestCase {
/** /**
* reloadEnvironment method * reloadEnvironment method
* *
* @access private
* @return void * @return void
* @access private
*/ */
function __reloadEnvironment() { function __reloadEnvironment() {
foreach ($_GET as $key => $val) { foreach ($_GET as $key => $val) {
@ -2210,8 +2222,8 @@ class DispatcherTest extends CakeTestCase {
* loadEnvironment method * loadEnvironment method
* *
* @param mixed $env * @param mixed $env
* @access private
* @return void * @return void
* @access private
*/ */
function __loadEnvironment($env) { function __loadEnvironment($env) {
if ($env['reload']) { if ($env['reload']) {
@ -2245,8 +2257,8 @@ class DispatcherTest extends CakeTestCase {
* cachePath method * cachePath method
* *
* @param mixed $her * @param mixed $her
* @access private
* @return string * @return string
* @access private
*/ */
function __cachePath($here) { function __cachePath($here) {
$path = $here; $path = $here;

View file

@ -43,8 +43,6 @@ class CacheTest extends CakeTestCase {
$this->_defaultCacheConfig = Cache::config('default'); $this->_defaultCacheConfig = Cache::config('default');
Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests')); Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests'));
Cache::engine('File', array('path' => TMP . 'tests'));
} }
/** /**
@ -56,7 +54,6 @@ class CacheTest extends CakeTestCase {
function tearDown() { function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable); Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default', $this->_defaultCacheConfig['settings']); Cache::config('default', $this->_defaultCacheConfig['settings']);
Cache::engine('File');
} }
/** /**
@ -71,6 +68,31 @@ class CacheTest extends CakeTestCase {
$this->assertEqual($results, Cache::config('new')); $this->assertEqual($results, Cache::config('new'));
} }
/**
* test configuring CacheEngines in App/libs
*
* @return void
*/
function testConfigWithLibAndPluginEngines() {
App::build(array(
'libs' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
), true);
$settings = array('engine' => 'TestAppCache', 'path' => TMP, 'prefix' => 'cake_test_');
$result = Cache::config('libEngine', $settings);
$this->assertEqual($result, Cache::config('libEngine'));
$settings = array('engine' => 'TestPlugin.TestPluginCache', 'path' => TMP, 'prefix' => 'cake_test_');
$result = Cache::config('pluginLibEngine', $settings);
$this->assertEqual($result, Cache::config('pluginLibEngine'));
Cache::drop('libEngine');
Cache::drop('pluginLibEngine');
App::build();
}
/** /**
* testInvalidConfig method * testInvalidConfig method
* *
@ -102,15 +124,45 @@ class CacheTest extends CakeTestCase {
$_cacheConfigTests = Cache::config('tests'); $_cacheConfigTests = Cache::config('tests');
$result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'sessions')); $result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'sessions'));
$this->assertEqual($result['settings'], Cache::settings('File')); $this->assertEqual($result['settings'], Cache::settings('sessions'));
$result = Cache::config('tests', array('engine'=> 'File', 'path' => TMP . 'tests')); $result = Cache::config('tests', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertEqual($result['settings'], Cache::settings('File')); $this->assertEqual($result['settings'], Cache::settings('tests'));
Cache::config('sessions', $_cacheConfigSessions['settings']); Cache::config('sessions', $_cacheConfigSessions['settings']);
Cache::config('tests', $_cacheConfigTests['settings']); Cache::config('tests', $_cacheConfigTests['settings']);
} }
/**
* test that calling config() sets the 'default' configuration up.
*
* @return void
*/
function testConfigSettingDefaultConfigKey() {
Cache::config('test_name', array('engine' => 'File', 'prefix' => 'test_name_'));
Cache::config('test_name');
Cache::write('value_one', 'I am cached');
$result = Cache::read('value_one');
$this->assertEqual($result, 'I am cached');
Cache::config('default');
$result = Cache::read('value_one');
$this->assertEqual($result, null);
Cache::write('value_one', 'I am in another cache config!');
$result = Cache::read('value_one');
$this->assertEqual($result, 'I am in another cache config!');
Cache::config('test_name');
$result = Cache::read('value_one');
$this->assertEqual($result, 'I am cached');
Cache::delete('value_one');
Cache::config('default');
Cache::delete('value_one');
}
/** /**
* testWritingWithConfig method * testWritingWithConfig method
* *
@ -132,11 +184,23 @@ class CacheTest extends CakeTestCase {
'engine' => 'File', 'engine' => 'File',
'isWindows' => DIRECTORY_SEPARATOR == '\\' 'isWindows' => DIRECTORY_SEPARATOR == '\\'
); );
$this->assertEqual($expected, Cache::settings('File')); $this->assertEqual($expected, Cache::settings('sessions'));
Cache::config('sessions', $_cacheConfigSessions['settings']); Cache::config('sessions', $_cacheConfigSessions['settings']);
} }
/**
* test that configured returns an array of the currently configured cache
* settings
*
* @return void
*/
function testConfigured() {
$result = Cache::configured();
$this->assertTrue(in_array('_cake_core_', $result));
$this->assertTrue(in_array('default', $result));
}
/** /**
* testInitSettings method * testInitSettings method
* *
@ -144,7 +208,7 @@ class CacheTest extends CakeTestCase {
* @return void * @return void
*/ */
function testInitSettings() { function testInitSettings() {
Cache::engine('File', array('path' => TMP . 'tests')); Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests'));
$settings = Cache::settings(); $settings = Cache::settings();
$expecting = array( $expecting = array(
@ -158,8 +222,37 @@ class CacheTest extends CakeTestCase {
'isWindows' => DIRECTORY_SEPARATOR == '\\' 'isWindows' => DIRECTORY_SEPARATOR == '\\'
); );
$this->assertEqual($settings, $expecting); $this->assertEqual($settings, $expecting);
}
Cache::engine('File'); /**
* test that drop removes cache configs, and that further attempts to use that config
* do not work.
*
* @return void
*/
function testDrop() {
App::build(array(
'libs' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
), true);
$result = Cache::drop('some_config_that_does_not_exist');
$this->assertFalse($result);
$_testsConfig = Cache::config('tests');
$result = Cache::drop('tests');
$this->assertTrue($result);
Cache::config('unconfigTest', array(
'engine' => 'TestAppCache'
));
$this->assertTrue(Cache::isInitialized('unconfigTest'));
$this->assertTrue(Cache::drop('unconfigTest'));
$this->assertFalse(Cache::isInitialized('TestAppCache'));
Cache::config('tests', $_testsConfig);
App::build();
} }
/** /**
@ -256,5 +349,6 @@ class CacheTest extends CakeTestCase {
Cache::set($_cacheSet); Cache::set($_cacheSet);
} }
} }
?> ?>

View file

@ -39,7 +39,7 @@ class ApcEngineTest extends UnitTestCase {
*/ */
function skip() { function skip() {
$skip = true; $skip = true;
if (Cache::engine('Apc')) { if (function_exists('apc_store')) {
$skip = false; $skip = false;
} }
$this->skipIf($skip, '%s Apc is not installed or configured properly'); $this->skipIf($skip, '%s Apc is not installed or configured properly');
@ -65,6 +65,7 @@ class ApcEngineTest extends UnitTestCase {
*/ */
function tearDown() { function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable); Configure::write('Cache.disable', $this->_cacheDisable);
Cache::drop('apc');
Cache::config('default'); Cache::config('default');
} }
@ -112,7 +113,7 @@ class ApcEngineTest extends UnitTestCase {
$result = Cache::read('other_test'); $result = Cache::read('other_test');
$this->assertFalse($result); $this->assertFalse($result);
Cache::set(array('duration' => "+1 second")); Cache::set(array('duration' => 1));
$data = 'this is a test of the emergency broadcasting system'; $data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data); $result = Cache::write('other_test', $data);

View file

@ -2,8 +2,6 @@
/** /**
* FileEngineTest file * FileEngineTest file
* *
* Long description for file
*
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite> * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
@ -22,9 +20,6 @@
if (!class_exists('Cache')) { if (!class_exists('Cache')) {
require LIBS . 'cache.php'; require LIBS . 'cache.php';
} }
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
/** /**
* FileEngineTest class * FileEngineTest class
@ -74,12 +69,11 @@ class FileEngineTest extends CakeTestCase {
*/ */
function testCacheDirChange() { function testCacheDirChange() {
$result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'sessions')); $result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'sessions'));
$this->assertEqual($result['settings'], Cache::settings('File')); $this->assertEqual($result['settings'], Cache::settings('sessions'));
$this->assertNotEqual($result, Cache::settings('File'));
$result = Cache::config('tests', array('engine'=> 'File', 'path' => TMP . 'tests')); $result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertEqual($result['settings'], Cache::settings('File')); $this->assertEqual($result['settings'], Cache::settings('sessions'));
$this->assertNotEqual($result, Cache::settings('File')); $this->assertNotEqual($result['settings'], Cache::settings('default'));
} }
/** /**
@ -159,7 +153,6 @@ class FileEngineTest extends CakeTestCase {
$result = Cache::delete('delete_test'); $result = Cache::delete('delete_test');
$this->assertFalse($result); $this->assertFalse($result);
} }
/** /**
@ -169,12 +162,12 @@ class FileEngineTest extends CakeTestCase {
* @return void * @return void
*/ */
function testSerialize() { function testSerialize() {
Cache::engine('File', array('serialize' => true)); Cache::config('default', array('engine' => 'File', 'serialize' => true));
$data = 'this is a test of the emergency broadcasting system'; $data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('serialize_test', $data, 1); $write = Cache::write('serialize_test', $data);
$this->assertTrue($write); $this->assertTrue($write);
Cache::engine('File', array('serialize' => false)); Cache::config('default', array('serialize' => false));
$read = Cache::read('serialize_test'); $read = Cache::read('serialize_test');
$newread = Cache::read('serialize_test'); $newread = Cache::read('serialize_test');
@ -184,7 +177,6 @@ class FileEngineTest extends CakeTestCase {
$this->assertIdentical($read, serialize($data)); $this->assertIdentical($read, serialize($data));
$this->assertIdentical(unserialize($newread), $data); $this->assertIdentical(unserialize($newread), $data);
} }
/** /**
@ -194,7 +186,7 @@ class FileEngineTest extends CakeTestCase {
* @return void * @return void
*/ */
function testClear() { function testClear() {
Cache::engine('File', array('duration' => 1)); Cache::config('default', array('engine' => 'File', 'duration' => 1));
$data = 'this is a test of the emergency broadcasting system'; $data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('serialize_test1', $data); $write = Cache::write('serialize_test1', $data);
$write = Cache::write('serialize_test2', $data); $write = Cache::write('serialize_test2', $data);
@ -223,7 +215,7 @@ class FileEngineTest extends CakeTestCase {
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test2')); $this->assertFalse(file_exists(CACHE . 'cake_serialize_test2'));
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test3')); $this->assertFalse(file_exists(CACHE . 'cake_serialize_test3'));
$result = Cache::engine('File', array('path' => CACHE . 'views')); Cache::config('default', array('engine' => 'File', 'path' => CACHE . 'views'));
$data = 'this is a test of the emergency broadcasting system'; $data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('controller_view_1', $data); $write = Cache::write('controller_view_1', $data);
@ -278,7 +270,7 @@ class FileEngineTest extends CakeTestCase {
clearCache('controller_view'); clearCache('controller_view');
Cache::engine('File', array('path' => CACHE)); Cache::config('default', array('engine' => 'File', 'path' => CACHE));
} }
/** /**
@ -306,40 +298,43 @@ class FileEngineTest extends CakeTestCase {
* @return void * @return void
*/ */
function testRemoveWindowsSlashesFromCache() { function testRemoveWindowsSlashesFromCache() {
Cache::engine('File', array('isWindows' => true, 'prefix' => null, 'path' => TMP)); Cache::config('windows_test', array('engine' => 'File', 'isWindows' => true, 'prefix' => null, 'path' => TMP));
$expected = array ( $expected = array (
'C:\dev\prj2\sites\cake\libs' => array( 'C:\dev\prj2\sites\cake\libs' => array(
0 => 'C:\dev\prj2\sites\cake\libs', 1 => 'C:\dev\prj2\sites\cake\libs\view', 0 => 'C:\dev\prj2\sites\cake\libs', 1 => 'C:\dev\prj2\sites\cake\libs\view',
2 => 'C:\dev\prj2\sites\cake\libs\view\scaffolds', 3 => 'C:\dev\prj2\sites\cake\libs\view\pages', 2 => 'C:\dev\prj2\sites\cake\libs\view\scaffolds', 3 => 'C:\dev\prj2\sites\cake\libs\view\pages',
4 => 'C:\dev\prj2\sites\cake\libs\view\layouts', 5 => 'C:\dev\prj2\sites\cake\libs\view\layouts\xml', 4 => 'C:\dev\prj2\sites\cake\libs\view\layouts', 5 => 'C:\dev\prj2\sites\cake\libs\view\layouts\xml',
6 => 'C:\dev\prj2\sites\cake\libs\view\layouts\rss', 7 => 'C:\dev\prj2\sites\cake\libs\view\layouts\js', 6 => 'C:\dev\prj2\sites\cake\libs\view\layouts\rss', 7 => 'C:\dev\prj2\sites\cake\libs\view\layouts\js',
8 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email', 9 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email\text', 8 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email', 9 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email\text',
10 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email\html', 11 => 'C:\dev\prj2\sites\cake\libs\view\helpers', 10 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email\html', 11 => 'C:\dev\prj2\sites\cake\libs\view\helpers',
12 => 'C:\dev\prj2\sites\cake\libs\view\errors', 13 => 'C:\dev\prj2\sites\cake\libs\view\elements', 12 => 'C:\dev\prj2\sites\cake\libs\view\errors', 13 => 'C:\dev\prj2\sites\cake\libs\view\elements',
14 => 'C:\dev\prj2\sites\cake\libs\view\elements\email', 15 => 'C:\dev\prj2\sites\cake\libs\view\elements\email\text', 14 => 'C:\dev\prj2\sites\cake\libs\view\elements\email', 15 => 'C:\dev\prj2\sites\cake\libs\view\elements\email\text',
16 => 'C:\dev\prj2\sites\cake\libs\view\elements\email\html', 17 => 'C:\dev\prj2\sites\cake\libs\model', 16 => 'C:\dev\prj2\sites\cake\libs\view\elements\email\html', 17 => 'C:\dev\prj2\sites\cake\libs\model',
18 => 'C:\dev\prj2\sites\cake\libs\model\datasources', 19 => 'C:\dev\prj2\sites\cake\libs\model\datasources\dbo', 18 => 'C:\dev\prj2\sites\cake\libs\model\datasources', 19 => 'C:\dev\prj2\sites\cake\libs\model\datasources\dbo',
20 => 'C:\dev\prj2\sites\cake\libs\model\behaviors', 21 => 'C:\dev\prj2\sites\cake\libs\controller', 20 => 'C:\dev\prj2\sites\cake\libs\model\behaviors', 21 => 'C:\dev\prj2\sites\cake\libs\controller',
22 => 'C:\dev\prj2\sites\cake\libs\controller\components', 23 => 'C:\dev\prj2\sites\cake\libs\cache'), 22 => 'C:\dev\prj2\sites\cake\libs\controller\components', 23 => 'C:\dev\prj2\sites\cake\libs\cache'),
'C:\dev\prj2\sites\main_site\vendors' => array( 'C:\dev\prj2\sites\main_site\vendors' => array(
0 => 'C:\dev\prj2\sites\main_site\vendors', 1 => 'C:\dev\prj2\sites\main_site\vendors\shells', 0 => 'C:\dev\prj2\sites\main_site\vendors', 1 => 'C:\dev\prj2\sites\main_site\vendors\shells',
2 => 'C:\dev\prj2\sites\main_site\vendors\shells\templates', 3 => 'C:\dev\prj2\sites\main_site\vendors\shells\templates\cdc_project', 2 => 'C:\dev\prj2\sites\main_site\vendors\shells\templates', 3 => 'C:\dev\prj2\sites\main_site\vendors\shells\templates\cdc_project',
4 => 'C:\dev\prj2\sites\main_site\vendors\shells\tasks', 5 => 'C:\dev\prj2\sites\main_site\vendors\js', 4 => 'C:\dev\prj2\sites\main_site\vendors\shells\tasks', 5 => 'C:\dev\prj2\sites\main_site\vendors\js',
6 => 'C:\dev\prj2\sites\main_site\vendors\css'), 6 => 'C:\dev\prj2\sites\main_site\vendors\css'),
'C:\dev\prj2\sites\vendors' => array( 'C:\dev\prj2\sites\vendors' => array(
0 => 'C:\dev\prj2\sites\vendors', 1 => 'C:\dev\prj2\sites\vendors\simpletest', 0 => 'C:\dev\prj2\sites\vendors', 1 => 'C:\dev\prj2\sites\vendors\simpletest',
2 => 'C:\dev\prj2\sites\vendors\simpletest\test', 3 => 'C:\dev\prj2\sites\vendors\simpletest\test\support', 2 => 'C:\dev\prj2\sites\vendors\simpletest\test', 3 => 'C:\dev\prj2\sites\vendors\simpletest\test\support',
4 => 'C:\dev\prj2\sites\vendors\simpletest\test\support\collector', 5 => 'C:\dev\prj2\sites\vendors\simpletest\extensions', 4 => 'C:\dev\prj2\sites\vendors\simpletest\test\support\collector', 5 => 'C:\dev\prj2\sites\vendors\simpletest\extensions',
6 => 'C:\dev\prj2\sites\vendors\simpletest\extensions\testdox', 7 => 'C:\dev\prj2\sites\vendors\simpletest\docs', 6 => 'C:\dev\prj2\sites\vendors\simpletest\extensions\testdox', 7 => 'C:\dev\prj2\sites\vendors\simpletest\docs',
8 => 'C:\dev\prj2\sites\vendors\simpletest\docs\fr', 9 => 'C:\dev\prj2\sites\vendors\simpletest\docs\en'), 8 => 'C:\dev\prj2\sites\vendors\simpletest\docs\fr', 9 => 'C:\dev\prj2\sites\vendors\simpletest\docs\en'),
'C:\dev\prj2\sites\main_site\views\helpers' => array( 'C:\dev\prj2\sites\main_site\views\helpers' => array(
0 => 'C:\dev\prj2\sites\main_site\views\helpers')); 0 => 'C:\dev\prj2\sites\main_site\views\helpers')
);
$data = Cache::write('test_dir_map', $expected); Cache::write('test_dir_map', $expected, 'windows_test');
$data = Cache::read('test_dir_map'); $data = Cache::read('test_dir_map', 'windows_test');
Cache::delete('test_dir_map'); Cache::delete('test_dir_map', 'windows_test');
$this->assertEqual($expected, $data); $this->assertEqual($expected, $data);
Cache::drop('windows_test');
} }
/** /**
@ -349,13 +344,13 @@ class FileEngineTest extends CakeTestCase {
* @return void * @return void
*/ */
function testWriteQuotedString() { function testWriteQuotedString() {
Cache::engine('File', array('path' => TMP . 'tests')); Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests'));
Cache::write('App.doubleQuoteTest', '"this is a quoted string"'); Cache::write('App.doubleQuoteTest', '"this is a quoted string"');
$this->assertIdentical(Cache::read('App.doubleQuoteTest'), '"this is a quoted string"'); $this->assertIdentical(Cache::read('App.doubleQuoteTest'), '"this is a quoted string"');
Cache::write('App.singleQuoteTest', "'this is a quoted string'"); Cache::write('App.singleQuoteTest', "'this is a quoted string'");
$this->assertIdentical(Cache::read('App.singleQuoteTest'), "'this is a quoted string'"); $this->assertIdentical(Cache::read('App.singleQuoteTest'), "'this is a quoted string'");
Cache::engine('File', array('isWindows' => true, 'path' => TMP . 'tests')); Cache::config('default', array('isWindows' => true, 'path' => TMP . 'tests'));
$this->assertIdentical(Cache::read('App.doubleQuoteTest'), '"this is a quoted string"'); $this->assertIdentical(Cache::read('App.doubleQuoteTest'), '"this is a quoted string"');
Cache::write('App.singleQuoteTest', "'this is a quoted string'"); Cache::write('App.singleQuoteTest', "'this is a quoted string'");
$this->assertIdentical(Cache::read('App.singleQuoteTest'), "'this is a quoted string'"); $this->assertIdentical(Cache::read('App.singleQuoteTest'), "'this is a quoted string'");

View file

@ -2,8 +2,6 @@
/** /**
* MemcacheEngineTest file * MemcacheEngineTest file
* *
* Long description for file
*
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite> * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
@ -23,13 +21,6 @@ if (!class_exists('Cache')) {
require LIBS . 'cache.php'; require LIBS . 'cache.php';
} }
/**
* MemcacheEngineTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.cache
*/
/** /**
* MemcacheEngineTest class * MemcacheEngineTest class
* *
@ -46,10 +37,10 @@ class MemcacheEngineTest extends CakeTestCase {
*/ */
function skip() { function skip() {
$skip = true; $skip = true;
if (Cache::engine('Memcache')) { if (class_exists('Memcache')) {
$skip = false; $skip = false;
} }
$this->skipIf($skip, '%s Memcache is not installed or configured properly'); $this->skipIf($skip, '%s Memcache is not installed or configured properly.');
} }
/** /**
@ -72,6 +63,7 @@ class MemcacheEngineTest extends CakeTestCase {
*/ */
function tearDown() { function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable); Configure::write('Cache.disable', $this->_cacheDisable);
Cache::drop('memcache');
Cache::config('default'); Cache::config('default');
} }
@ -83,13 +75,15 @@ class MemcacheEngineTest extends CakeTestCase {
*/ */
function testSettings() { function testSettings() {
$settings = Cache::settings(); $settings = Cache::settings();
$expecting = array('prefix' => 'cake_', unset($settings['serialize'], $settings['path']);
'duration'=> 3600, $expecting = array(
'probability' => 100, 'prefix' => 'cake_',
'servers' => array('127.0.0.1'), 'duration'=> 3600,
'compress' => false, 'probability' => 100,
'engine' => 'Memcache' 'servers' => array('127.0.0.1'),
); 'compress' => false,
'engine' => 'Memcache'
);
$this->assertEqual($settings, $expecting); $this->assertEqual($settings, $expecting);
} }
@ -101,14 +95,12 @@ class MemcacheEngineTest extends CakeTestCase {
*/ */
function testMultipleServers() { function testMultipleServers() {
$servers = array('127.0.0.1:11211', '127.0.0.1:11222'); $servers = array('127.0.0.1:11211', '127.0.0.1:11222');
$Cache =& Cache::getInstance();
$MemCache =& $Cache->_Engine['Memcache'];
$available = true; $available = true;
$Memcache =& new Memcache();
foreach($servers as $server) { foreach($servers as $server) {
list($host, $port) = explode(':', $server); list($host, $port) = explode(':', $server);
if (!@$MemCache->__Memcache->connect($host, $port)) { if (!$Memcache->addServer($host, $port)) {
$available = false; $available = false;
} }
} }
@ -116,13 +108,13 @@ class MemcacheEngineTest extends CakeTestCase {
if ($this->skipIf(!$available, '%s Need memcache servers at ' . implode(', ', $servers) . ' to run this test')) { if ($this->skipIf(!$available, '%s Need memcache servers at ' . implode(', ', $servers) . ' to run this test')) {
return; return;
} }
$Memcache =& new MemcacheEngine();
$Memcache->init(array('engine' => 'Memcache', 'servers' => $servers));
unset($MemCache->__Memcache); $servers = array_keys($Memcache->__Memcache->getExtendedStats());
$MemCache->init(array('engine' => 'Memcache', 'servers' => $servers)); $settings = $Memcache->settings();
$servers = array_keys($MemCache->__Memcache->getExtendedStats());
$settings = Cache::settings();
$this->assertEqual($servers, $settings['servers']); $this->assertEqual($servers, $settings['servers']);
Cache::drop('dual_server');
} }
/** /**
@ -132,8 +124,9 @@ class MemcacheEngineTest extends CakeTestCase {
* @return void * @return void
*/ */
function testConnect() { function testConnect() {
$Cache =& Cache::getInstance(); $Memcache =& new MemcacheEngine();
$result = $Cache->_Engine['Memcache']->connect('127.0.0.1'); $Memcache->init(Cache::settings('memcache'));
$result = $Memcache->connect('127.0.0.1');
$this->assertTrue($result); $this->assertTrue($result);
} }
@ -191,13 +184,13 @@ class MemcacheEngineTest extends CakeTestCase {
$result = Cache::read('other_test'); $result = Cache::read('other_test');
$this->assertFalse($result); $this->assertFalse($result);
Cache::engine('Memcache', array('duration' => '+1 second')); Cache::config('memcache', array('duration' => '+1 second'));
sleep(2); sleep(2);
$result = Cache::read('other_test'); $result = Cache::read('other_test');
$this->assertFalse($result); $this->assertFalse($result);
Cache::engine('Memcache', array('duration' => '+31 day')); Cache::config('memcache', array('duration' => '+31 day'));
$data = 'this is a test of the emergency broadcasting system'; $data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('long_expiry_test', $data); $result = Cache::write('long_expiry_test', $data);
$this->assertTrue($result); $this->assertTrue($result);
@ -210,7 +203,7 @@ class MemcacheEngineTest extends CakeTestCase {
$result = Cache::read('long_expiry_test'); $result = Cache::read('long_expiry_test');
$this->assertTrue($result); $this->assertTrue($result);
Cache::engine('Memcache', array('duration' => 3600)); Cache::config('memcache', array('duration' => 3600));
} }
/** /**

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