diff --git a/Cake/Console/Command/AclShell.php b/Cake/Console/Command/AclShell.php deleted file mode 100644 index 8e89cdd5279..00000000000 --- a/Cake/Console/Command/AclShell.php +++ /dev/null @@ -1,615 +0,0 @@ -params['connection'])) { - $this->connection = $this->params['connection']; - } - - $class = Configure::read('Acl.classname'); - $className = App::classname($class, 'Controller/Component/Acl'); - if ( - $class !== 'Cake\Controller\Component\Acl\DbAcl' && - !is_subclass_of($className, 'Cake\Controller\Component\Acl\DbAcl') - ) { - $out = "--------------------------------------------------\n"; - $out .= __d('cake_console', 'Error: Your current CakePHP configuration is set to an ACL implementation other than DB.') . "\n"; - $out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n"; - $out .= "--------------------------------------------------\n"; - $out .= __d('cake_console', 'Current ACL Classname: %s', $class) . "\n"; - $out .= "--------------------------------------------------\n"; - $this->err($out); - return $this->_stop(); - } - - if ($this->command) { - if (Configure::check('Datasource') === null) { - $this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.')); - $this->args = null; - return $this->DbConfig->execute(); - } - - if (!in_array($this->command, ['initdb'])) { - $registry = new ComponentRegistry(); - $this->Acl = new AclComponent($registry); - $controller = new Controller(); - $this->Acl->startup($controller); - } - } - } - -/** - * Override main() for help message hook - * - * @return void - */ - public function main() { - $this->out($this->OptionParser->help()); - } - -/** - * Creates an ARO/ACO node - * - * @return void - */ - public function create() { - extract($this->_dataVars()); - - $class = ucfirst($this->args[0]); - $parent = $this->parseIdentifier($this->args[1]); - - if (!empty($parent) && $parent !== '/' && $parent !== 'root') { - $parent = $this->_getNodeId($class, $parent); - } else { - $parent = null; - } - - $data = $this->parseIdentifier($this->args[2]); - if (is_string($data) && $data !== '/') { - $data = ['alias' => $data]; - } elseif (is_string($data)) { - $this->error(__d('cake_console', '/ can not be used as an alias!') . __d('cake_console', " / is the root, please supply a sub alias")); - } - - $data['parent_id'] = $parent; - $this->Acl->{$class}->create(); - if ($this->Acl->{$class}->save($data)) { - $this->out(__d('cake_console', "New %s '%s' created.", $class, $this->args[2]), 2); - } else { - $this->err(__d('cake_console', "There was a problem creating a new %s '%s'.", $class, $this->args[2])); - } - } - -/** - * Delete an ARO/ACO node. - * - * @return void - */ - public function delete() { - extract($this->_dataVars()); - - $identifier = $this->parseIdentifier($this->args[1]); - $nodeId = $this->_getNodeId($class, $identifier); - - if (!$this->Acl->{$class}->delete($nodeId)) { - $this->error(__d('cake_console', 'Node Not Deleted') . __d('cake_console', 'There was an error deleting the %s. Check that the node exists.', $class) . "\n"); - } - $this->out(__d('cake_console', '%s deleted.', $class), 2); - } - -/** - * Set parent for an ARO/ACO node. - * - * @return void - */ - public function setParent() { - extract($this->_dataVars()); - $target = $this->parseIdentifier($this->args[1]); - $parent = $this->parseIdentifier($this->args[2]); - - $data = [ - $class => [ - 'id' => $this->_getNodeId($class, $target), - 'parent_id' => $this->_getNodeId($class, $parent) - ] - ]; - $this->Acl->{$class}->create(); - if (!$this->Acl->{$class}->save($data)) { - $this->out(__d('cake_console', 'Error in setting new parent. Please make sure the parent node exists, and is not a descendant of the node specified.')); - } else { - $this->out(__d('cake_console', 'Node parent set to %s', $this->args[2]) . "\n"); - } - } - -/** - * Get path to specified ARO/ACO node. - * - * @return void - */ - public function getPath() { - extract($this->_dataVars()); - $identifier = $this->parseIdentifier($this->args[1]); - - $id = $this->_getNodeId($class, $identifier); - $nodes = $this->Acl->{$class}->getPath($id); - - if (empty($nodes)) { - $this->error( - __d('cake_console', "Supplied Node '%s' not found", $this->args[1]), - __d('cake_console', 'No tree returned.') - ); - } - $this->out(__d('cake_console', 'Path:')); - $this->hr(); - for ($i = 0, $len = count($nodes); $i < $len; $i++) { - $this->_outputNode($class, $nodes[$i], $i); - } - } - -/** - * Outputs a single node, Either using the alias or Model.key - * - * @param string $class Class name that is being used. - * @param array $node Array of node information. - * @param integer $indent indent level. - * @return void - */ - protected function _outputNode($class, $node, $indent) { - $indent = str_repeat(' ', $indent); - $data = $node[$class]; - if ($data['alias']) { - $this->out($indent . "[" . $data['id'] . "] " . $data['alias']); - } else { - $this->out($indent . "[" . $data['id'] . "] " . $data['model'] . '.' . $data['foreign_key']); - } - } - -/** - * Check permission for a given ARO to a given ACO. - * - * @return void - */ - public function check() { - extract($this->_getParams()); - - if ($this->Acl->check($aro, $aco, $action)) { - $this->out(__d('cake_console', '%s is allowed.', $aroName)); - } else { - $this->out(__d('cake_console', '%s is not allowed.', $aroName)); - } - } - -/** - * Grant permission for a given ARO to a given ACO. - * - * @return void - */ - public function grant() { - extract($this->_getParams()); - - if ($this->Acl->allow($aro, $aco, $action)) { - $this->out(__d('cake_console', 'Permission granted.')); - } else { - $this->out(__d('cake_console', 'Permission was not granted.')); - } - } - -/** - * Deny access for an ARO to an ACO. - * - * @return void - */ - public function deny() { - extract($this->_getParams()); - - if ($this->Acl->deny($aro, $aco, $action)) { - $this->out(__d('cake_console', 'Permission denied.')); - } else { - $this->out(__d('cake_console', 'Permission was not denied.')); - } - } - -/** - * Set an ARO to inherit permission to an ACO. - * - * @return void - */ - public function inherit() { - extract($this->_getParams()); - - if ($this->Acl->inherit($aro, $aco, $action)) { - $this->out(__d('cake_console', 'Permission inherited.')); - } else { - $this->out(__d('cake_console', 'Permission was not inherited.')); - } - } - -/** - * Show a specific ARO/ACO node. - * - * @return void - */ - public function view() { - extract($this->_dataVars()); - - if (isset($this->args[1])) { - $identity = $this->parseIdentifier($this->args[1]); - - $topNode = $this->Acl->{$class}->find('first', [ - 'conditions' => [$class . '.id' => $this->_getNodeId($class, $identity)] - ]); - - $nodes = $this->Acl->{$class}->find('all', [ - 'conditions' => [ - $class . '.lft >=' => $topNode[$class]['lft'], - $class . '.lft <=' => $topNode[$class]['rght'] - ], - 'order' => $class . '.lft ASC' - ]); - } else { - $nodes = $this->Acl->{$class}->find('all', ['order' => $class . '.lft ASC']); - } - - if (empty($nodes)) { - if (isset($this->args[1])) { - $this->error(__d('cake_console', '%s not found', $this->args[1]), __d('cake_console', 'No tree returned.')); - } elseif (isset($this->args[0])) { - $this->error(__d('cake_console', '%s not found', $this->args[0]), __d('cake_console', 'No tree returned.')); - } - } - $this->out($class . ' tree:'); - $this->hr(); - - $stack = []; - $last = null; - - foreach ($nodes as $n) { - $stack[] = $n; - if (!empty($last)) { - $end = end($stack); - if ($end[$class]['rght'] > $last) { - foreach ($stack as $k => $v) { - $end = end($stack); - if ($v[$class]['rght'] < $end[$class]['rght']) { - unset($stack[$k]); - } - } - } - } - $last = $n[$class]['rght']; - $count = count($stack); - - $this->_outputNode($class, $n, $count); - } - $this->hr(); - } - -/** - * Initialize ACL database. - * - * @return mixed - */ - public function initdb() { - return $this->dispatchShell('schema create DbAcl'); - } - -/** - * Gets the option parser instance and configures it. - * - * @return ConsoleOptionParser - */ - public function getOptionParser() { - $parser = parent::getOptionParser(); - - $type = [ - 'choices' => ['aro', 'aco'], - 'required' => true, - 'help' => __d('cake_console', 'Type of node to create.') - ]; - - $parser->description( - __d('cake_console', 'A console tool for managing the DbAcl') - )->addSubcommand('create', [ - 'help' => __d('cake_console', 'Create a new ACL node'), - 'parser' => [ - 'description' => __d('cake_console', 'Creates a new ACL object under the parent'), - 'epilog' => __d('cake_console', 'You can use `root` as the parent when creating nodes to create top level nodes.'), - 'arguments' => [ - 'type' => $type, - 'parent' => [ - 'help' => __d('cake_console', 'The node selector for the parent.'), - 'required' => true - ], - 'alias' => [ - 'help' => __d('cake_console', 'The alias to use for the newly created node.'), - 'required' => true - ] - ] - ] - ])->addSubcommand('delete', [ - 'help' => __d('cake_console', 'Deletes the ACL object with the given reference'), - 'parser' => [ - 'description' => __d('cake_console', 'Delete an ACL node.'), - 'arguments' => [ - 'type' => $type, - 'node' => [ - 'help' => __d('cake_console', 'The node identifier to delete.'), - 'required' => true, - ] - ] - ] - ])->addSubcommand('setparent', [ - 'help' => __d('cake_console', 'Moves the ACL node under a new parent.'), - 'parser' => [ - 'description' => __d('cake_console', 'Moves the ACL object specified by beneath '), - 'arguments' => [ - 'type' => $type, - 'node' => [ - 'help' => __d('cake_console', 'The node to move'), - 'required' => true, - ], - 'parent' => [ - 'help' => __d('cake_console', 'The new parent for .'), - 'required' => true - ] - ] - ] - ])->addSubcommand('getpath', [ - 'help' => __d('cake_console', 'Print out the path to an ACL node.'), - 'parser' => [ - 'description' => [ - __d('cake_console', "Returns the path to the ACL object specified by ."), - __d('cake_console', "This command is useful in determining the inheritance of permissions for a certain object in the tree.") - ], - 'arguments' => [ - 'type' => $type, - 'node' => [ - 'help' => __d('cake_console', 'The node to get the path of'), - 'required' => true, - ] - ] - ] - ])->addSubcommand('check', [ - 'help' => __d('cake_console', 'Check the permissions between an ACO and ARO.'), - 'parser' => [ - 'description' => [ - __d('cake_console', 'Use this command to check ACL permissions.') - ], - 'arguments' => [ - 'aro' => ['help' => __d('cake_console', 'ARO to check.'), 'required' => true], - 'aco' => ['help' => __d('cake_console', 'ACO to check.'), 'required' => true], - 'action' => ['help' => __d('cake_console', 'Action to check'), 'default' => 'all'] - ] - ] - ])->addSubcommand('grant', [ - 'help' => __d('cake_console', 'Grant an ARO permissions to an ACO.'), - 'parser' => [ - 'description' => [ - __d('cake_console', 'Use this command to grant ACL permissions. Once executed, the ARO specified (and its children, if any) will have ALLOW access to the specified ACO action (and the ACO\'s children, if any).') - ], - 'arguments' => [ - 'aro' => ['help' => __d('cake_console', 'ARO to grant permission to.'), 'required' => true], - 'aco' => ['help' => __d('cake_console', 'ACO to grant access to.'), 'required' => true], - 'action' => ['help' => __d('cake_console', 'Action to grant'), 'default' => 'all'] - ] - ] - ])->addSubcommand('deny', [ - 'help' => __d('cake_console', 'Deny an ARO permissions to an ACO.'), - 'parser' => [ - 'description' => [ - __d('cake_console', 'Use this command to deny ACL permissions. Once executed, the ARO specified (and its children, if any) will have DENY access to the specified ACO action (and the ACO\'s children, if any).') - ], - 'arguments' => [ - 'aro' => ['help' => __d('cake_console', 'ARO to deny.'), 'required' => true], - 'aco' => ['help' => __d('cake_console', 'ACO to deny.'), 'required' => true], - 'action' => ['help' => __d('cake_console', 'Action to deny'), 'default' => 'all'] - ] - ] - ])->addSubcommand('inherit', [ - 'help' => __d('cake_console', 'Inherit an ARO\'s parent permissions.'), - 'parser' => [ - 'description' => [ - __d('cake_console', "Use this command to force a child ARO object to inherit its permissions settings from its parent.") - ], - 'arguments' => [ - 'aro' => ['help' => __d('cake_console', 'ARO to have permissions inherit.'), 'required' => true], - 'aco' => ['help' => __d('cake_console', 'ACO to inherit permissions on.'), 'required' => true], - 'action' => ['help' => __d('cake_console', 'Action to inherit'), 'default' => 'all'] - ] - ] - ])->addSubcommand('view', [ - 'help' => __d('cake_console', 'View a tree or a single node\'s subtree.'), - 'parser' => [ - 'description' => [ - __d('cake_console', "The view command will return the ARO or ACO tree."), - __d('cake_console', "The optional node parameter allows you to return"), - __d('cake_console', "only a portion of the requested tree.") - ], - 'arguments' => [ - 'type' => $type, - 'node' => ['help' => __d('cake_console', 'The optional node to view the subtree of.')] - ] - ] - ])->addSubcommand('initdb', [ - 'help' => __d('cake_console', 'Initialize the DbAcl tables. Uses this command : cake schema create DbAcl') - ])->epilog( - [ - 'Node and parent arguments can be in one of the following formats:', - '', - ' - . - The node will be bound to a specific record of the given model.', - '', - ' - - The node will be given a string alias (or path, in the case of )', - " i.e. 'John'. When used with , this takes the form of an alias path,", - " i.e. //.", - '', - "To add a node at the root level, enter 'root' or '/' as the parameter." - ] - ); - return $parser; - } - -/** - * Checks that given node exists - * - * @return boolean Success - */ - public function nodeExists() { - if (!isset($this->args[0]) || !isset($this->args[1])) { - return false; - } - $dataVars = $this->_dataVars($this->args[0]); - extract($dataVars); - $key = is_numeric($this->args[1]) ? $dataVars['secondary_id'] : 'alias'; - $conditions = [$class . '.' . $key => $this->args[1]]; - $possibility = $this->Acl->{$class}->find('all', compact('conditions')); - if (empty($possibility)) { - $this->error(__d('cake_console', '%s not found', $this->args[1]), __d('cake_console', 'No tree returned.')); - } - return $possibility; - } - -/** - * Parse an identifier into Model.foreignKey or an alias. - * Takes an identifier determines its type and returns the result as used by other methods. - * - * @param string $identifier Identifier to parse - * @return mixed a string for aliases, and an array for model.foreignKey - */ - public function parseIdentifier($identifier) { - if (preg_match('/^([\w]+)\.(.*)$/', $identifier, $matches)) { - return [ - 'model' => $matches[1], - 'foreign_key' => $matches[2], - ]; - } - return $identifier; - } - -/** - * Get the node for a given identifier. $identifier can either be a string alias - * or an array of properties to use in AcoNode::node() - * - * @param string $class Class type you want (Aro/Aco) - * @param string|array $identifier A mixed identifier for finding the node. - * @return integer Integer of NodeId. Will trigger an error if nothing is found. - */ - protected function _getNodeId($class, $identifier) { - $node = $this->Acl->{$class}->node($identifier); - if (empty($node)) { - if (is_array($identifier)) { - $identifier = var_export($identifier, true); - } - $this->error(__d('cake_console', 'Could not find node using reference "%s"', $identifier)); - return; - } - return Hash::get($node, "0.{$class}.id"); - } - -/** - * get params for standard Acl methods - * - * @return array aro, aco, action - */ - protected function _getParams() { - $aro = is_numeric($this->args[0]) ? intval($this->args[0]) : $this->args[0]; - $aco = is_numeric($this->args[1]) ? intval($this->args[1]) : $this->args[1]; - $aroName = $aro; - $acoName = $aco; - - if (is_string($aro)) { - $aro = $this->parseIdentifier($aro); - } - if (is_string($aco)) { - $aco = $this->parseIdentifier($aco); - } - $action = '*'; - if (isset($this->args[2]) && !in_array($this->args[2], ['', 'all'])) { - $action = $this->args[2]; - } - return compact('aro', 'aco', 'action', 'aroName', 'acoName'); - } - -/** - * Build data parameters based on node type - * - * @param string $type Node type (ARO/ACO) - * @return array Variables - */ - protected function _dataVars($type = null) { - if (!$type) { - $type = $this->args[0]; - } - $vars = []; - $class = ucwords($type); - $vars['secondary_id'] = (strtolower($class) === 'aro') ? 'foreign_key' : 'object_id'; - $vars['data_name'] = $type; - $vars['table_name'] = $type . 's'; - $vars['class'] = $class; - return $vars; - } - -} diff --git a/Cake/Console/Command/Task/TestTask.php b/Cake/Console/Command/Task/TestTask.php index 02353d27cf2..8fd309653e2 100644 --- a/Cake/Console/Command/Task/TestTask.php +++ b/Cake/Console/Command/Task/TestTask.php @@ -21,7 +21,7 @@ use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Error; -use Cake\Utility\ClassRegistry; +use Cake\ORM\TableRegistry; use Cake\Utility\Inflector; /** @@ -287,10 +287,10 @@ public function isLoadableClass($package, $class) { * @return object And instance of the class that is going to be tested. */ public function buildTestSubject($type, $class) { - ClassRegistry::flush(); + TableRegistry::clear(); $class = $this->getRealClassName($type, $class); if (strtolower($type) === 'model') { - $instance = ClassRegistry::init($class); + $instance = TableRegistry::get($class); } else { $instance = new $class(); } diff --git a/Cake/Controller/Component/Acl/DbAcl.php b/Cake/Controller/Component/Acl/DbAcl.php deleted file mode 100644 index e57566349ca..00000000000 --- a/Cake/Controller/Component/Acl/DbAcl.php +++ /dev/null @@ -1,164 +0,0 @@ -Permission = ClassRegistry::init(array('class' => 'Permission', 'alias' => 'Permission')); - $this->Aro = $this->Permission->Aro; - $this->Aco = $this->Permission->Aco; - } - -/** - * Initializes the containing component and sets the Aro/Aco objects to it. - * - * @param AclComponent $component - * @return void - */ - public function initialize(Component $component) { - $component->Aro = $this->Aro; - $component->Aco = $this->Aco; - } - -/** - * Checks if the given $aro has access to action $action in $aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @param string $action Action (defaults to *) - * @return boolean Success (true if ARO has access to action in ACO, false otherwise) - * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#checking-permissions-the-acl-component - */ - public function check($aro, $aco, $action = "*") { - return $this->Permission->check($aro, $aco, $action); - } - -/** - * Allow $aro to have access to action $actions in $aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @param string $actions Action (defaults to *) - * @param integer $value Value to indicate access type (1 to give access, -1 to deny, 0 to inherit) - * @return boolean Success - * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#assigning-permissions - */ - public function allow($aro, $aco, $actions = "*", $value = 1) { - return $this->Permission->allow($aro, $aco, $actions, $value); - } - -/** - * Deny access for $aro to action $action in $aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @param string $action Action (defaults to *) - * @return boolean Success - * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#assigning-permissions - */ - public function deny($aro, $aco, $action = "*") { - return $this->allow($aro, $aco, $action, -1); - } - -/** - * Let access for $aro to action $action in $aco be inherited - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @param string $action Action (defaults to *) - * @return boolean Success - */ - public function inherit($aro, $aco, $action = "*") { - return $this->allow($aro, $aco, $action, 0); - } - -/** - * Allow $aro to have access to action $actions in $aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @param string $action Action (defaults to *) - * @return boolean Success - * @see allow() - */ - public function grant($aro, $aco, $action = "*") { - return $this->allow($aro, $aco, $action); - } - -/** - * Deny access for $aro to action $action in $aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @param string $action Action (defaults to *) - * @return boolean Success - * @see deny() - */ - public function revoke($aro, $aco, $action = "*") { - return $this->deny($aro, $aco, $action); - } - -/** - * Get an array of access-control links between the given Aro and Aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @return array Indexed array with: 'aro', 'aco' and 'link' - */ - public function getAclLink($aro, $aco) { - return $this->Permission->getAclLink($aro, $aco); - } - -/** - * Get the keys used in an ACO - * - * @param array $keys Permission model info - * @return array ACO keys - */ - protected function _getAcoKeys($keys) { - return $this->Permission->getAcoKeys($keys); - } - -} diff --git a/Cake/Controller/Controller.php b/Cake/Controller/Controller.php index 7e08b5fc236..94e1d1bbe78 100644 --- a/Cake/Controller/Controller.php +++ b/Cake/Controller/Controller.php @@ -27,7 +27,6 @@ use Cake\ORM\TableRegistry; use Cake\Routing\RequestActionTrait; use Cake\Routing\Router; -use Cake\Utility\ClassRegistry; use Cake\Utility\Inflector; use Cake\Utility\MergeVariablesTrait; use Cake\Utility\RepositoryAwareTrait; @@ -657,16 +656,6 @@ public function render($view = null, $layout = null) { $this->View = $this->_getViewObject(); - $models = ClassRegistry::keys(); - foreach ($models as $currentModel) { - $currentObject = ClassRegistry::getObject($currentModel); - if ($currentObject instanceof \Cake\Model\Model) { - $className = get_class($currentObject); - $this->request->params['models'][$currentObject->alias] = compact('className'); - $this->View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors; - } - } - $this->autoRender = false; $this->response->body($this->View->render($view, $layout)); return $this->response; diff --git a/Cake/Controller/Scaffold.php b/Cake/Controller/Scaffold.php deleted file mode 100644 index f70d2091b5f..00000000000 --- a/Cake/Controller/Scaffold.php +++ /dev/null @@ -1,452 +0,0 @@ -controller = $controller; - - $count = count($this->_passedVars); - for ($j = 0; $j < $count; $j++) { - $var = $this->_passedVars[$j]; - $this->{$var} = $controller->{$var}; - } - - $this->redirect = array('action' => 'index'); - - $this->modelClass = $controller->modelClass; - $this->modelKey = Inflector::underscore($this->modelClass); - - if (!is_object($this->controller->{$this->modelClass})) { - throw new Error\MissingModelException($this->modelClass); - } - - $this->ScaffoldModel = $this->controller->{$this->modelClass}; - $this->scaffoldTitle = Inflector::humanize(Inflector::underscore($this->viewPath)); - $this->scaffoldActions = $controller->scaffold; - $title = __d('cake', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle; - $modelClass = $this->controller->modelClass; - $primaryKey = $this->ScaffoldModel->primaryKey; - $displayField = $this->ScaffoldModel->displayField; - $singularVar = Inflector::variable($modelClass); - $pluralVar = Inflector::variable($this->controller->name); - $singularHumanName = Inflector::humanize(Inflector::underscore($modelClass)); - $pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name)); - $scaffoldFields = array_keys($this->ScaffoldModel->schema()); - $associations = $this->_associations(); - - $this->controller->set(compact( - 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar', - 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations' - )); - $this->controller->set('title_for_layout', $title); - - if ($this->controller->viewClass) { - $this->controller->viewClass = 'Scaffold'; - } - $this->_validSession = ( - isset($this->controller->Session) && $this->controller->Session->valid() - ); - $this->_scaffold($request); - } - -/** - * Renders a view action of scaffolded model. - * - * @param Cake\Network\Request $request Request Object for scaffolding - * @return mixed A rendered view of a row from Models database table - * @throws Cake\Error\NotFoundException - */ - protected function _scaffoldView(Request $request) { - if ($this->controller->beforeScaffold('view')) { - if (isset($request->params['pass'][0])) { - $this->ScaffoldModel->id = $request->params['pass'][0]; - } - if (!$this->ScaffoldModel->exists()) { - throw new Error\NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey))); - } - $this->ScaffoldModel->recursive = 1; - $this->controller->request->data = $this->ScaffoldModel->read(); - $this->controller->set( - Inflector::variable($this->controller->modelClass), $this->request->data - ); - $this->controller->render($this->request['action'], $this->layout); - } elseif ($this->controller->scaffoldError('view') === false) { - return $this->_scaffoldError(); - } - } - -/** - * Renders index action of scaffolded model. - * - * @param array $params Parameters for scaffolding - * @return mixed A rendered view listing rows from Models database table - */ - protected function _scaffoldIndex($params) { - if ($this->controller->beforeScaffold('index')) { - $this->ScaffoldModel->recursive = 0; - $this->controller->set( - Inflector::variable($this->controller->name), $this->controller->paginate() - ); - $this->controller->render($this->request['action'], $this->layout); - } elseif ($this->controller->scaffoldError('index') === false) { - return $this->_scaffoldError(); - } - } - -/** - * Renders an add or edit action for scaffolded model. - * - * @param string $action Action (add or edit) - * @return void - */ - protected function _scaffoldForm($action = 'edit') { - $this->controller->viewVars['scaffoldFields'] = array_merge( - $this->controller->viewVars['scaffoldFields'], - array_keys($this->ScaffoldModel->hasAndBelongsToMany) - ); - $this->controller->render($action, $this->layout); - } - -/** - * Saves or updates the scaffolded model. - * - * @param Cake\Network\Request $request Request Object for scaffolding - * @param string $action add or edit - * @return mixed Success on save/update, add/edit form if data is empty or error if save or update fails - * @throws Cake\Error\NotFoundException - */ - protected function _scaffoldSave(Request $request, $action = 'edit') { - $formAction = 'edit'; - $success = __d('cake', 'updated'); - if ($action === 'add') { - $formAction = 'add'; - $success = __d('cake', 'saved'); - } - - if ($this->controller->beforeScaffold($action)) { - if ($action === 'edit') { - if (isset($request->params['pass'][0])) { - $this->ScaffoldModel->id = $request['pass'][0]; - } - if (!$this->ScaffoldModel->exists()) { - throw new Error\NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelKey))); - } - } - - if (!empty($request->data)) { - if ($action === 'create') { - $this->ScaffoldModel->create(); - } - - if ($this->ScaffoldModel->save($request->data)) { - if ($this->controller->afterScaffoldSave($action)) { - $message = __d('cake', - 'The %1$s has been %2$s', - Inflector::humanize($this->modelKey), - $success - ); - return $this->_sendMessage($message); - } - return $this->controller->afterScaffoldSaveError($action); - } - if ($this->_validSession) { - $this->controller->Session->setFlash(__d('cake', 'Please correct errors below.')); - } - } - - if (empty($request->data)) { - if ($this->ScaffoldModel->id) { - $this->controller->data = $request->data = $this->ScaffoldModel->read(); - } else { - $this->controller->data = $request->data = $this->ScaffoldModel->create(); - } - } - - foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) { - $varName = Inflector::variable(Inflector::pluralize( - preg_replace('/(?:_id)$/', '', $assocData['foreignKey']) - )); - $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list')); - } - foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) { - $varName = Inflector::variable(Inflector::pluralize($assocName)); - $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list')); - } - - return $this->_scaffoldForm($formAction); - } elseif ($this->controller->scaffoldError($action) === false) { - return $this->_scaffoldError(); - } - } - -/** - * Performs a delete on given scaffolded Model. - * - * @param Cake\Network\Request $request Request for scaffolding - * @return mixed Success on delete, error if delete fails - * @throws Cake\Error\MethodNotAllowedException When HTTP method is not a DELETE - * @throws Cake\Error\NotFoundException When id being deleted does not exist. - */ - protected function _scaffoldDelete(Request $request) { - if ($this->controller->beforeScaffold('delete')) { - if (!$request->is('post')) { - throw new Error\MethodNotAllowedException(); - } - $id = false; - if (isset($request->params['pass'][0])) { - $id = $request->params['pass'][0]; - } - $this->ScaffoldModel->id = $id; - if (!$this->ScaffoldModel->exists()) { - throw new Error\NotFoundException(__d('cake', 'Invalid %s', Inflector::humanize($this->modelClass))); - } - if ($this->ScaffoldModel->delete()) { - $message = __d('cake', 'The %1$s with id: %2$s has been deleted.', Inflector::humanize($this->modelClass), $id); - return $this->_sendMessage($message); - } - $message = __d('cake', - 'There was an error deleting the %1$s with id: %2$s', - Inflector::humanize($this->modelClass), - $id - ); - return $this->_sendMessage($message); - } elseif ($this->controller->scaffoldError('delete') === false) { - return $this->_scaffoldError(); - } - } - -/** - * Sends a message to the user. Either uses Sessions or flash messages depending - * on the availability of a session - * - * @param string $message Message to display - * @return void - */ - protected function _sendMessage($message) { - if ($this->_validSession) { - $this->controller->Session->setFlash($message); - return $this->controller->redirect($this->redirect); - } - $this->controller->flash($message, $this->redirect); - } - -/** - * Show a scaffold error - * - * @return mixed A rendered view showing the error - */ - protected function _scaffoldError() { - return $this->controller->render('error', $this->layout); - } - -/** - * When methods are now present in a controller - * scaffoldView is used to call default Scaffold methods if: - * `public $scaffold;` is placed in the controller's class definition. - * - * @param Cake\Network\Request $request Request object for scaffolding - * @return void - * @throws Cake\Error\MissingActionException When methods are not scaffolded. - * @throws Cake\Error\MissingDatabaseException When the database connection is undefined. - */ - protected function _scaffold(Request $request) { - $db = ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig); - $prefixes = Configure::read('Routing.prefixes'); - $scaffoldPrefix = $this->scaffoldActions; - - if (isset($db)) { - if (empty($this->scaffoldActions)) { - $this->scaffoldActions = array( - 'index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete' - ); - } elseif (!empty($prefixes) && in_array($scaffoldPrefix, $prefixes)) { - $this->scaffoldActions = array( - $scaffoldPrefix . '_index', - $scaffoldPrefix . '_list', - $scaffoldPrefix . '_view', - $scaffoldPrefix . '_add', - $scaffoldPrefix . '_create', - $scaffoldPrefix . '_edit', - $scaffoldPrefix . '_update', - $scaffoldPrefix . '_delete' - ); - } - - if (in_array($request->params['action'], $this->scaffoldActions)) { - if (!empty($prefixes)) { - $request->params['action'] = str_replace($scaffoldPrefix . '_', '', $request->params['action']); - } - switch ($request->params['action']) { - case 'index': - case 'list': - $this->_scaffoldIndex($request); - break; - case 'view': - $this->_scaffoldView($request); - break; - case 'add': - case 'create': - $this->_scaffoldSave($request, 'add'); - break; - case 'edit': - case 'update': - $this->_scaffoldSave($request, 'edit'); - break; - case 'delete': - $this->_scaffoldDelete($request); - break; - } - } else { - throw new Error\MissingActionException(array( - 'controller' => $this->controller->name, - 'action' => $request->action - )); - } - } else { - throw new Error\MissingDatabaseException(array('connection' => $this->ScaffoldModel->useDbConfig)); - } - } - -/** - * Returns associations for controllers models. - * - * @return array Associations for model - */ - protected function _associations() { - $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); - $associations = array(); - - foreach ($keys as $type) { - foreach ($this->ScaffoldModel->{$type} as $assocKey => $assocData) { - $associations[$type][$assocKey]['primaryKey'] = - $this->ScaffoldModel->{$assocKey}->primaryKey; - - $associations[$type][$assocKey]['displayField'] = - $this->ScaffoldModel->{$assocKey}->displayField; - - $associations[$type][$assocKey]['foreignKey'] = - $assocData['foreignKey']; - - list($plugin, $model) = pluginSplit($assocData['className']); - if ($plugin) { - $plugin = Inflector::underscore($plugin); - } - $associations[$type][$assocKey]['plugin'] = $plugin; - - $associations[$type][$assocKey]['controller'] = - Inflector::pluralize(Inflector::underscore($model)); - - if ($type === 'hasAndBelongsToMany') { - $associations[$type][$assocKey]['with'] = $assocData['with']; - } - } - } - return $associations; - } - -} diff --git a/Cake/Model/AclNode.php b/Cake/Model/AclNode.php deleted file mode 100644 index 598ace2fa75..00000000000 --- a/Cake/Model/AclNode.php +++ /dev/null @@ -1,184 +0,0 @@ - array('type' => 'nested')); - -/** - * Constructor - * - */ - public function __construct() { - $config = Configure::read('Acl.database'); - if (isset($config)) { - $this->useDbConfig = $config; - } - parent::__construct(); - } - -/** - * Retrieves the Aro/Aco node for this model - * - * @param string|array|Model $ref Array with 'model' and 'foreign_key', model object, or string value - * @return array Node found in database - * @throws Cake\Error\Exception when binding to a model that doesn't exist. - */ - public function node($ref = null) { - $db = $this->getDataSource(); - $type = $this->alias; - $result = null; - - if (!empty($this->useTable)) { - $table = $this->useTable; - } else { - $table = Inflector::pluralize(Inflector::underscore($type)); - } - - if (empty($ref)) { - return null; - } elseif (is_string($ref)) { - $path = explode('/', $ref); - $start = $path[0]; - unset($path[0]); - - $queryData = array( - 'conditions' => array( - $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"), - $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght")), - 'fields' => array('id', 'parent_id', 'model', 'foreign_key', 'alias'), - 'joins' => array(array( - 'table' => $table, - 'alias' => "{$type}0", - 'type' => 'INNER', - 'conditions' => array("{$type}0.alias" => $start) - )), - 'order' => $db->name("{$type}.lft") . ' DESC' - ); - - foreach ($path as $i => $alias) { - $j = $i - 1; - - $queryData['joins'][] = array( - 'table' => $table, - 'alias' => "{$type}{$i}", - 'type' => 'INNER', - 'conditions' => array( - $db->name("{$type}{$i}.lft") . ' > ' . $db->name("{$type}{$j}.lft"), - $db->name("{$type}{$i}.rght") . ' < ' . $db->name("{$type}{$j}.rght"), - $db->name("{$type}{$i}.alias") . ' = ' . $db->value($alias, 'string'), - $db->name("{$type}{$j}.id") . ' = ' . $db->name("{$type}{$i}.parent_id") - ) - ); - - $queryData['conditions'] = array('or' => array( - $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft") . ' AND ' . $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght"), - $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}{$i}.lft") . ' AND ' . $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}{$i}.rght")) - ); - } - $result = $db->read($this, $queryData, -1); - $path = array_values($path); - - if ( - !isset($result[0][$type]) || - (!empty($path) && $result[0][$type]['alias'] != $path[count($path) - 1]) || - (empty($path) && $result[0][$type]['alias'] != $start) - ) { - return false; - } - } elseif (is_object($ref) && $ref instanceof Model) { - $ref = array('model' => $ref->name, 'foreign_key' => $ref->id); - } elseif (is_array($ref) && !(isset($ref['model']) && isset($ref['foreign_key']))) { - $name = key($ref); - list(, $alias) = pluginSplit($name); - - $model = ClassRegistry::init(array('class' => $name, 'alias' => $alias)); - - if (empty($model)) { - throw new Error\Exception('cake_dev', "Model class '%s' not found in AclNode::node() when trying to bind %s object", $type, $this->alias); - } - - $tmpRef = null; - if (method_exists($model, 'bindNode')) { - $tmpRef = $model->bindNode($ref); - } - if (empty($tmpRef)) { - $ref = array('model' => $alias, 'foreign_key' => $ref[$name][$model->primaryKey]); - } else { - if (is_string($tmpRef)) { - return $this->node($tmpRef); - } - $ref = $tmpRef; - } - } - if (is_array($ref)) { - if (is_array(current($ref)) && is_string(key($ref))) { - $name = key($ref); - $ref = current($ref); - } - foreach ($ref as $key => $val) { - if (strpos($key, $type) !== 0 && strpos($key, '.') === false) { - unset($ref[$key]); - $ref["{$type}0.{$key}"] = $val; - } - } - $queryData = array( - 'conditions' => $ref, - 'fields' => array('id', 'parent_id', 'model', 'foreign_key', 'alias'), - 'joins' => array(array( - 'table' => $table, - 'alias' => "{$type}0", - 'type' => 'INNER', - 'conditions' => array( - $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"), - $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght") - ) - )), - 'order' => $db->name("{$type}.lft") . ' DESC' - ); - $result = $db->read($this, $queryData, -1); - - if (!$result) { - throw new Error\Exception(__d('cake_dev', "AclNode::node() - Couldn't find %s node identified by \"%s\"", $type, print_r($ref, true))); - } - } - return $result; - } - -} diff --git a/Cake/Model/Aco.php b/Cake/Model/Aco.php deleted file mode 100644 index 664d58a56c5..00000000000 --- a/Cake/Model/Aco.php +++ /dev/null @@ -1,38 +0,0 @@ - array('with' => 'Permission')); -} diff --git a/Cake/Model/AcoAction.php b/Cake/Model/AcoAction.php deleted file mode 100644 index 690bc579f73..00000000000 --- a/Cake/Model/AcoAction.php +++ /dev/null @@ -1,38 +0,0 @@ - array('with' => 'Permission')); -} diff --git a/Cake/Model/Behavior/AclBehavior.php b/Cake/Model/Behavior/AclBehavior.php deleted file mode 100644 index ea9bdafa0c9..00000000000 --- a/Cake/Model/Behavior/AclBehavior.php +++ /dev/null @@ -1,144 +0,0 @@ - 'Aro', 'controlled' => 'Aco', 'both' => array('Aro', 'Aco')); - -/** - * Sets up the configuration for the model, and loads ACL models if they haven't been already - * - * @param Model $model - * @param array $config - * @return void - */ - public function setup(Model $model, $config = array()) { - if (isset($config[0])) { - $config['type'] = $config[0]; - unset($config[0]); - } - $this->settings[$model->name] = array_merge(array('type' => 'controlled'), $config); - $this->settings[$model->name]['type'] = strtolower($this->settings[$model->name]['type']); - - $types = $this->_typeMaps[$this->settings[$model->name]['type']]; - - if (!is_array($types)) { - $types = array($types); - } - foreach ($types as $type) { - $model->{$type} = ClassRegistry::init($type); - } - if (!method_exists($model, 'parentNode')) { - trigger_error(__d('cake_dev', 'Callback %s not defined in %s', 'parentNode()', $model->alias), E_USER_WARNING); - } - } - -/** - * Retrieves the Aro/Aco node for this model - * - * @param Model $model - * @param string|array|Model $ref Array with 'model' and 'foreign_key', model object, or string value - * @param string $type Only needed when Acl is set up as 'both', specify 'Aro' or 'Aco' to get the correct node - * @return array - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/acl.html#node - */ - public function node(Model $model, $ref = null, $type = null) { - if (empty($type)) { - $type = $this->_typeMaps[$this->settings[$model->name]['type']]; - if (is_array($type)) { - trigger_error(__d('cake_dev', 'AclBehavior is setup with more then one type, please specify type parameter for node()'), E_USER_WARNING); - return null; - } - } - if (empty($ref)) { - $ref = array('model' => $model->name, 'foreign_key' => $model->id); - } - return $model->{$type}->node($ref); - } - -/** - * Creates a new ARO/ACO node bound to this record - * - * @param Model $model - * @param boolean $created True if this is a new record - * @param array $options Options passed from Model::save(). - * @return void - */ - public function afterSave(Model $model, $created, $options = array()) { - $types = $this->_typeMaps[$this->settings[$model->name]['type']]; - if (!is_array($types)) { - $types = array($types); - } - foreach ($types as $type) { - $parent = $model->parentNode(); - if (!empty($parent)) { - $parent = $this->node($model, $parent, $type); - } - $data = array( - 'parent_id' => isset($parent[0][$type]['id']) ? $parent[0][$type]['id'] : null, - 'model' => $model->name, - 'foreign_key' => $model->id - ); - if (!$created) { - $node = $this->node($model, null, $type); - $data['id'] = isset($node[0][$type]['id']) ? $node[0][$type]['id'] : null; - } - $model->{$type}->create(); - $model->{$type}->save($data); - } - } - -/** - * Destroys the ARO/ACO node bound to the deleted record - * - * @param Model $model - * @return void - */ - public function afterDelete(Model $model) { - $types = $this->_typeMaps[$this->settings[$model->name]['type']]; - if (!is_array($types)) { - $types = array($types); - } - foreach ($types as $type) { - $node = Hash::extract($this->node($model, null, $type), "0.{$type}.id"); - if (!empty($node)) { - $model->{$type}->delete($node); - } - } - } - -} diff --git a/Cake/Model/Behavior/TranslateBehavior.php b/Cake/Model/Behavior/TranslateBehavior.php deleted file mode 100644 index 32cc1139b6d..00000000000 --- a/Cake/Model/Behavior/TranslateBehavior.php +++ /dev/null @@ -1,699 +0,0 @@ - array('field_one', - * 'field_two' => 'FieldAssoc', 'field_three')) - * - * With above example only one permanent hasMany will be joined (for field_two - * as FieldAssoc) - * - * $config could be empty - and translations configured dynamically by - * bindTranslation() method - * - * @param Model $Model Model the behavior is being attached to. - * @param array $config Array of configuration information. - * @return mixed - */ - public function setup(Model $Model, $config = array()) { - $db = ConnectionManager::getDataSource($Model->useDbConfig); - if (!$db->connected) { - trigger_error( - __d('cake_dev', 'Datasource %s for TranslateBehavior of model %s is not connected', $Model->useDbConfig, $Model->alias), - E_USER_ERROR - ); - return false; - } - - $this->settings[$Model->alias] = array(); - $this->runtime[$Model->alias] = array('fields' => array()); - $this->translateModel($Model); - return $this->bindTranslation($Model, $config, false); - } - -/** - * Cleanup Callback unbinds bound translations and deletes setting information. - * - * @param Model $Model Model being detached. - * @return void - */ - public function cleanup(Model $Model) { - $this->unbindTranslation($Model); - unset($this->settings[$Model->alias]); - unset($this->runtime[$Model->alias]); - } - -/** - * beforeFind Callback - * - * @param Model $Model Model find is being run on. - * @param array $query Array of Query parameters. - * @return array Modified query - */ - public function beforeFind(Model $Model, $query) { - $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields; - $locale = $this->_getLocale($Model); - if (empty($locale)) { - return $query; - } - $db = $Model->getDataSource(); - $RuntimeModel = $this->translateModel($Model); - - if (!empty($RuntimeModel->tablePrefix)) { - $tablePrefix = $RuntimeModel->tablePrefix; - } else { - $tablePrefix = $db->config['prefix']; - } - $joinTable = new \StdClass(); - $joinTable->tablePrefix = $tablePrefix; - $joinTable->table = $RuntimeModel->table; - $joinTable->schemaName = $RuntimeModel->getDataSource()->getSchemaName(); - - $this->_joinTable = $joinTable; - $this->_runtimeModel = $RuntimeModel; - - if (is_string($query['fields']) && "COUNT(*) AS {$db->name('count')}" == $query['fields']) { - $query['fields'] = "COUNT(DISTINCT({$db->name($Model->escapeField())})) {$db->alias}count"; - $query['joins'][] = array( - 'type' => 'INNER', - 'alias' => $RuntimeModel->alias, - 'table' => $joinTable, - 'conditions' => array( - $Model->escapeField() => $db->identifier($RuntimeModel->escapeField('foreign_key')), - $RuntimeModel->escapeField('model') => $Model->name, - $RuntimeModel->escapeField('locale') => $locale - ) - ); - $conditionFields = $this->_checkConditions($Model, $query); - foreach ($conditionFields as $field) { - $query = $this->_addJoin($Model, $query, $field, $field, $locale); - } - unset($this->_joinTable, $this->_runtimeModel); - return $query; - } - - $fields = array_merge( - $this->settings[$Model->alias], - $this->runtime[$Model->alias]['fields'] - ); - $addFields = array(); - if (empty($query['fields'])) { - $addFields = $fields; - } elseif (is_array($query['fields'])) { - $isAllFields = ( - in_array($Model->alias . '.' . '*', $query['fields']) || - in_array($Model->escapeField('*'), $query['fields']) - ); - foreach ($fields as $key => $value) { - $field = (is_numeric($key)) ? $value : $key; - if ( - $isAllFields || - in_array($Model->alias . '.' . $field, $query['fields']) || - in_array($field, $query['fields']) - ) { - $addFields[] = $field; - } - } - } - - $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields; - if ($addFields) { - foreach ($addFields as $_f => $field) { - $aliasField = is_numeric($_f) ? $field : $_f; - - foreach (array($aliasField, $Model->alias . '.' . $aliasField) as $_field) { - $key = array_search($_field, (array)$query['fields']); - - if ($key !== false) { - unset($query['fields'][$key]); - } - } - $query = $this->_addJoin($Model, $query, $field, $aliasField, $locale); - } - } - $this->runtime[$Model->alias]['beforeFind'] = $addFields; - unset($this->_joinTable, $this->_runtimeModel); - return $query; - } - -/** - * Check a query's conditions for translated fields. - * Return an array of translated fields found in the conditions. - * - * @param Model $Model The model being read. - * @param array $query The query array. - * @return array The list of translated fields that are in the conditions. - */ - protected function _checkConditions(Model $Model, $query) { - $conditionFields = array(); - if (empty($query['conditions']) || (!empty($query['conditions']) && !is_array($query['conditions']))) { - return $conditionFields; - } - foreach ($query['conditions'] as $col => $val) { - foreach ($this->settings[$Model->alias] as $field => $assoc) { - if (is_numeric($field)) { - $field = $assoc; - } - if (strpos($col, $field) !== false) { - $conditionFields[] = $field; - } - } - } - return $conditionFields; - } - -/** - * Appends a join for translated fields. - * - * @param Model $Model The model being worked on. - * @param array $query The query array to append a join to. - * @param string $field The field name being joined. - * @param string $aliasField The aliased field name being joined. - * @param string|array $locale The locale(s) having joins added. - * @return array The modified query - */ - protected function _addJoin(Model $Model, $query, $field, $aliasField, $locale) { - $db = ConnectionManager::getDataSource($Model->useDbConfig); - $RuntimeModel = $this->_runtimeModel; - $joinTable = $this->_joinTable; - $aliasVirtual = "i18n_{$field}"; - $alias = "I18n__{$field}"; - if (is_array($locale)) { - foreach ($locale as $_locale) { - $aliasVirtualLocale = "{$aliasVirtual}_{$_locale}"; - $aliasLocale = "{$alias}__{$_locale}"; - $Model->virtualFields[$aliasVirtualLocale] = "{$aliasLocale}.content"; - if (!empty($query['fields']) && is_array($query['fields'])) { - $query['fields'][] = $aliasVirtualLocale; - } - $query['joins'][] = array( - 'type' => 'LEFT', - 'alias' => $aliasLocale, - 'table' => $joinTable, - 'conditions' => array( - $Model->escapeField() => $db->identifier("{$aliasLocale}.foreign_key"), - "{$aliasLocale}.model" => $Model->name, - "{$aliasLocale}.{$RuntimeModel->displayField}" => $aliasField, - "{$aliasLocale}.locale" => $_locale - ) - ); - } - } else { - $Model->virtualFields[$aliasVirtual] = "{$alias}.content"; - if (!empty($query['fields']) && is_array($query['fields'])) { - $query['fields'][] = $aliasVirtual; - } - $query['joins'][] = array( - 'type' => 'INNER', - 'alias' => $alias, - 'table' => $joinTable, - 'conditions' => array( - "{$Model->alias}.{$Model->primaryKey}" => $db->identifier("{$alias}.foreign_key"), - "{$alias}.model" => $Model->name, - "{$alias}.{$RuntimeModel->displayField}" => $aliasField, - "{$alias}.locale" => $locale - ) - ); - } - return $query; - } - -/** - * afterFind Callback - * - * @param Model $Model Model find was run on - * @param array $results Array of model results. - * @param boolean $primary Did the find originate on $model. - * @return array Modified results - */ - public function afterFind(Model $Model, $results, $primary = false) { - $Model->virtualFields = $this->runtime[$Model->alias]['virtualFields']; - $this->runtime[$Model->alias]['virtualFields'] = $this->runtime[$Model->alias]['fields'] = array(); - $locale = $this->_getLocale($Model); - - if (empty($locale) || empty($results) || empty($this->runtime[$Model->alias]['beforeFind'])) { - return $results; - } - $beforeFind = $this->runtime[$Model->alias]['beforeFind']; - - foreach ($results as $key => &$row) { - $results[$key][$Model->alias]['locale'] = (is_array($locale)) ? current($locale) : $locale; - foreach ($beforeFind as $_f => $field) { - $aliasField = is_numeric($_f) ? $field : $_f; - $aliasVirtual = "i18n_{$field}"; - if (is_array($locale)) { - foreach ($locale as $_locale) { - $aliasVirtualLocale = "{$aliasVirtual}_{$_locale}"; - if (!isset($row[$Model->alias][$aliasField]) && !empty($row[$Model->alias][$aliasVirtualLocale])) { - $row[$Model->alias][$aliasField] = $row[$Model->alias][$aliasVirtualLocale]; - $row[$Model->alias]['locale'] = $_locale; - } - unset($row[$Model->alias][$aliasVirtualLocale]); - } - - if (!isset($row[$Model->alias][$aliasField])) { - $row[$Model->alias][$aliasField] = ''; - } - } else { - $value = ''; - if (!empty($row[$Model->alias][$aliasVirtual])) { - $value = $row[$Model->alias][$aliasVirtual]; - } - $row[$Model->alias][$aliasField] = $value; - unset($row[$Model->alias][$aliasVirtual]); - } - } - } - return $results; - } - -/** - * beforeValidate Callback - * - * @param Model $Model Model invalidFields was called on. - * @param array $options Options passed from Model::save(). - * @return boolean - * @see Model::save() - */ - public function beforeValidate(Model $Model, $options = array()) { - unset($this->runtime[$Model->alias]['beforeSave']); - $this->_setRuntimeData($Model); - return true; - } - -/** - * beforeSave callback. - * - * Copies data into the runtime property when `$options['validate']` is - * disabled. Or the runtime data hasn't been set yet. - * - * @param Model $Model Model save was called on. - * @param array $options Options passed from Model::save(). - * @return boolean true. - * @see Model::save() - */ - public function beforeSave(Model $Model, $options = array()) { - if (isset($options['validate']) && !$options['validate']) { - unset($this->runtime[$Model->alias]['beforeSave']); - } - if (isset($this->runtime[$Model->alias]['beforeSave'])) { - return true; - } - $this->_setRuntimeData($Model); - return true; - } - -/** - * Sets the runtime data. - * - * Used from beforeValidate() and beforeSave() for compatibility issues, - * and to allow translations to be persisted even when validation - * is disabled. - * - * @param Model $Model - * @return void - */ - protected function _setRuntimeData(Model $Model) { - $locale = $this->_getLocale($Model); - if (empty($locale)) { - return true; - } - $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']); - $tempData = array(); - - foreach ($fields as $key => $value) { - $field = (is_numeric($key)) ? $value : $key; - - if (isset($Model->data[$Model->alias][$field])) { - $tempData[$field] = $Model->data[$Model->alias][$field]; - if (is_array($Model->data[$Model->alias][$field])) { - if (is_string($locale) && !empty($Model->data[$Model->alias][$field][$locale])) { - $Model->data[$Model->alias][$field] = $Model->data[$Model->alias][$field][$locale]; - } else { - $values = array_values($Model->data[$Model->alias][$field]); - $Model->data[$Model->alias][$field] = $values[0]; - } - } - } - } - $this->runtime[$Model->alias]['beforeSave'] = $tempData; - } - -/** - * Restores model data to the original data. - * This solves issues with saveAssociated and validate = first. - * - * @param Model $model - * @return void - */ - public function afterValidate(Model $Model) { - $Model->data[$Model->alias] = array_merge( - $Model->data[$Model->alias], - $this->runtime[$Model->alias]['beforeSave'] - ); - return true; - } - -/** - * afterSave Callback - * - * @param Model $Model Model the callback is called on - * @param boolean $created Whether or not the save created a record. - * @param array $options Options passed from Model::save(). - * @return void - */ - public function afterSave(Model $Model, $created, $options = array()) { - if (!isset($this->runtime[$Model->alias]['beforeValidate']) && !isset($this->runtime[$Model->alias]['beforeSave'])) { - return true; - } - if (isset($this->runtime[$Model->alias]['beforeValidate'])) { - $tempData = $this->runtime[$Model->alias]['beforeValidate']; - } else { - $tempData = $this->runtime[$Model->alias]['beforeSave']; - } - - unset($this->runtime[$Model->alias]['beforeValidate'], $this->runtime[$Model->alias]['beforeSave']); - $conditions = array('model' => $Model->name, 'foreign_key' => $Model->id); - $RuntimeModel = $this->translateModel($Model); - - if ($created) { - $tempData = $this->_prepareTranslations($Model, $tempData); - } - $locale = $this->_getLocale($Model); - - foreach ($tempData as $field => $value) { - unset($conditions['content']); - $conditions['field'] = $field; - if (is_array($value)) { - $conditions['locale'] = array_keys($value); - } else { - $conditions['locale'] = $locale; - if (is_array($locale)) { - $value = array($locale[0] => $value); - } else { - $value = array($locale => $value); - } - } - $translations = $RuntimeModel->find('list', array( - 'conditions' => $conditions, - 'fields' => array( - $RuntimeModel->alias . '.locale', - $RuntimeModel->alias . '.id' - ) - )); - foreach ($value as $_locale => $_value) { - $RuntimeModel->create(); - $conditions['locale'] = $_locale; - $conditions['content'] = $_value; - if (array_key_exists($_locale, $translations)) { - $RuntimeModel->save(array( - $RuntimeModel->alias => array_merge( - $conditions, array('id' => $translations[$_locale]) - ) - )); - } else { - $RuntimeModel->save(array($RuntimeModel->alias => $conditions)); - } - } - } - } - -/** - * Prepares the data to be saved for translated records. - * Add blank fields, and populates data for multi-locale saves. - * - * @param Model $Model Model instance - * @param array $data The sparse data that was provided. - * @return array The fully populated data to save. - */ - protected function _prepareTranslations(Model $Model, $data) { - $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']); - $locales = array(); - foreach ($data as $key => $value) { - if (is_array($value)) { - $locales = array_merge($locales, array_keys($value)); - } - } - $locales = array_unique($locales); - $hasLocales = count($locales) > 0; - - foreach ($fields as $key => $field) { - if (!is_numeric($key)) { - $field = $key; - } - if ($hasLocales && !isset($data[$field])) { - $data[$field] = array_fill_keys($locales, ''); - } elseif (!isset($data[$field])) { - $data[$field] = ''; - } - } - return $data; - } - -/** - * afterDelete Callback - * - * @param Model $Model Model the callback was run on. - * @return void - */ - public function afterDelete(Model $Model) { - $RuntimeModel = $this->translateModel($Model); - $conditions = array('model' => $Model->name, 'foreign_key' => $Model->id); - $RuntimeModel->deleteAll($conditions); - } - -/** - * Get selected locale for model - * - * @param Model $Model Model the locale needs to be set/get on. - * @return mixed string or false - */ - protected function _getLocale(Model $Model) { - if (!isset($Model->locale) || $Model->locale === null) { - $I18n = I18n::getInstance(); - $I18n->l10n->get(Configure::read('Config.language')); - $Model->locale = $I18n->l10n->locale; - } - - return $Model->locale; - } - -/** - * Get instance of model for translations. - * - * If the model has a translateModel property set, this will be used as the class - * name to find/use. If no translateModel property is found 'I18nModel' will be used. - * - * @param Model $Model Model to get a translatemodel for. - * @return Model - */ - public function translateModel(Model $Model) { - if (!isset($this->runtime[$Model->alias]['model'])) { - if (!isset($Model->translateModel) || empty($Model->translateModel)) { - $className = 'I18nModel'; - } else { - $className = $Model->translateModel; - } - - $this->runtime[$Model->alias]['model'] = ClassRegistry::init($className); - } - if (!empty($Model->translateTable) && $Model->translateTable !== $this->runtime[$Model->alias]['model']->useTable) { - $this->runtime[$Model->alias]['model']->setSource($Model->translateTable); - } elseif (empty($Model->translateTable) && empty($Model->translateModel)) { - $this->runtime[$Model->alias]['model']->setSource('i18n'); - } - return $this->runtime[$Model->alias]['model']; - } - -/** - * Bind translation for fields, optionally with hasMany association for - * fake field. - * - * *Note* You should avoid binding translations that overlap existing model properties. - * This can cause un-expected and un-desirable behavior. - * - * @param Model $Model instance of model - * @param string|array $fields string with field or array(field1, field2=>AssocName, field3) - * @param boolean $reset Leave true to have the fields only modified for the next operation. - * if false the field will be added for all future queries. - * @return boolean - * @throws Cake\Error\Exception when attempting to bind a translating called name. This is not allowed - * as it shadows Model::$name. - */ - public function bindTranslation(Model $Model, $fields, $reset = true) { - if (is_string($fields)) { - $fields = array($fields); - } - $associations = array(); - $RuntimeModel = $this->translateModel($Model); - $default = array('className' => $RuntimeModel->alias, 'foreignKey' => 'foreign_key'); - - foreach ($fields as $key => $value) { - if (is_numeric($key)) { - $field = $value; - $association = null; - } else { - $field = $key; - $association = $value; - } - if ($association === 'name') { - throw new Error\Exception( - __d('cake_dev', 'You cannot bind a translation named "name".') - ); - } - - $this->_removeField($Model, $field); - - if ($association === null) { - if ($reset) { - $this->runtime[$Model->alias]['fields'][] = $field; - } else { - $this->settings[$Model->alias][] = $field; - } - } else { - if ($reset) { - $this->runtime[$Model->alias]['fields'][$field] = $association; - } else { - $this->settings[$Model->alias][$field] = $association; - } - - foreach (array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany') as $type) { - if (isset($Model->{$type}[$association]) || isset($Model->__backAssociation[$type][$association])) { - trigger_error( - __d('cake_dev', 'Association %s is already bound to model %s', $association, $Model->alias), - E_USER_ERROR - ); - return false; - } - } - $associations[$association] = array_merge($default, array('conditions' => array( - 'model' => $Model->name, - $RuntimeModel->displayField => $field - ))); - } - } - - if (!empty($associations)) { - $Model->bindModel(array('hasMany' => $associations), $reset); - } - return true; - } - -/** - * Update runtime setting for a given field. - * - * @param Model $Model Model instance - * @param string $field The field to update. - * @return void - */ - protected function _removeField(Model $Model, $field) { - if (array_key_exists($field, $this->settings[$Model->alias])) { - unset($this->settings[$Model->alias][$field]); - } elseif (in_array($field, $this->settings[$Model->alias])) { - $this->settings[$Model->alias] = array_merge(array_diff($this->settings[$Model->alias], array($field))); - } - - if (array_key_exists($field, $this->runtime[$Model->alias]['fields'])) { - unset($this->runtime[$Model->alias]['fields'][$field]); - } elseif (in_array($field, $this->runtime[$Model->alias]['fields'])) { - $this->runtime[$Model->alias]['fields'] = array_merge(array_diff($this->runtime[$Model->alias]['fields'], array($field))); - } - } - -/** - * Unbind translation for fields, optionally unbinds hasMany association for - * fake field - * - * @param Model $Model instance of model - * @param string|array $fields string with field, or array(field1, field2=>AssocName, field3), or null for - * unbind all original translations - * @return boolean - */ - public function unbindTranslation(Model $Model, $fields = null) { - if (empty($fields) && empty($this->settings[$Model->alias])) { - return false; - } - if (empty($fields)) { - return $this->unbindTranslation($Model, $this->settings[$Model->alias]); - } - - if (is_string($fields)) { - $fields = array($fields); - } - $associations = array(); - - foreach ($fields as $key => $value) { - if (is_numeric($key)) { - $field = $value; - $association = null; - } else { - $field = $key; - $association = $value; - } - - $this->_removeField($Model, $field); - - if ($association !== null && (isset($Model->hasMany[$association]) || isset($Model->__backAssociation['hasMany'][$association]))) { - $associations[] = $association; - } - } - - if (!empty($associations)) { - $Model->unbindModel(array('hasMany' => $associations), false); - } - return true; - } - -} diff --git a/Cake/Model/Behavior/TreeBehavior.php b/Cake/Model/Behavior/TreeBehavior.php deleted file mode 100644 index 68ad9e774d9..00000000000 --- a/Cake/Model/Behavior/TreeBehavior.php +++ /dev/null @@ -1,1075 +0,0 @@ - 'parent_id', 'left' => 'lft', 'right' => 'rght', - 'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1 - ); - -/** - * Used to preserve state between delete callbacks. - * - * @var array - */ - protected $_deletedRow = array(); - -/** - * Initiate Tree behavior - * - * @param Model $Model instance of model - * @param array $config array of configuration settings. - * @return void - */ - public function setup(Model $Model, $config = array()) { - if (isset($config[0])) { - $config['type'] = $config[0]; - unset($config[0]); - } - $settings = array_merge($this->_defaults, $config); - - if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) { - $data = $Model->getAssociated($settings['scope']); - $Parent = $Model->{$settings['scope']}; - $settings['scope'] = $Model->escapeField($data['foreignKey']) . ' = ' . $Parent->escapeField(); - $settings['recursive'] = 0; - } - $this->settings[$Model->alias] = $settings; - } - -/** - * After save method. Called after all saves - * - * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the - * parameters to be saved. - * - * @param Model $Model Model instance. - * @param boolean $created indicates whether the node just saved was created or updated - * @param array $options Options passed from Model::save(). - * @return boolean true on success, false on failure - */ - public function afterSave(Model $Model, $created, $options = array()) { - extract($this->settings[$Model->alias]); - if ($created) { - if ((isset($Model->data[$Model->alias][$parent])) && $Model->data[$Model->alias][$parent]) { - return $this->_setParent($Model, $Model->data[$Model->alias][$parent], $created); - } - } elseif ($this->settings[$Model->alias]['__parentChange']) { - $this->settings[$Model->alias]['__parentChange'] = false; - return $this->_setParent($Model, $Model->data[$Model->alias][$parent]); - } - } - -/** - * Runs before a find() operation - * - * @param Model $Model Model using the behavior - * @param array $query Query parameters as set by cake - * @return array - */ - public function beforeFind(Model $Model, $query) { - if ($Model->findQueryType === 'threaded' && !isset($query['parent'])) { - $query['parent'] = $this->settings[$Model->alias]['parent']; - } - return $query; - } - -/** - * Stores the record about to be deleted. - * - * This is used to delete child nodes in the afterDelete. - * - * @param Model $Model Model instance - * @param boolean $cascade - * @return boolean - */ - public function beforeDelete(Model $Model, $cascade = true) { - extract($this->settings[$Model->alias]); - $data = $Model->find('first', array( - 'conditions' => array($Model->escapeField($Model->primaryKey) => $Model->id), - 'fields' => array($Model->escapeField($left), $Model->escapeField($right)), - 'recursive' => -1)); - if ($data) { - $this->_deletedRow[$Model->alias] = current($data); - } - return true; - } - -/** - * After delete method. - * - * Will delete the current node and all children using the deleteAll method and sync the table - * - * @param Model $Model Model instance - * @return boolean true to continue, false to abort the delete - */ - public function afterDelete(Model $Model) { - extract($this->settings[$Model->alias]); - $data = $this->_deletedRow[$Model->alias]; - $this->_deletedRow[$Model->alias] = null; - - if (!$data[$right] || !$data[$left]) { - return true; - } - $diff = $data[$right] - $data[$left] + 1; - - if ($diff > 2) { - if (is_string($scope)) { - $scope = array($scope); - } - $scope[][$Model->escapeField($left) . " BETWEEN ? AND ?"] = array($data[$left] + 1, $data[$right] - 1); - $Model->deleteAll($scope); - } - $this->_sync($Model, $diff, '-', '> ' . $data[$right]); - return true; - } - -/** - * Before save method. Called before all saves - * - * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the - * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by - * this method bypassing the setParent logic. - * - * @since 1.2 - * @param Model $Model Model instance - * @param array $options Options passed from Model::save(). - * @return boolean true to continue, false to abort the save - * @see Model::save() - */ - public function beforeSave(Model $Model, $options = array()) { - extract($this->settings[$Model->alias]); - - $this->_addToWhitelist($Model, array($left, $right)); - if (!$Model->id || !$Model->exists()) { - if (array_key_exists($parent, $Model->data[$Model->alias]) && $Model->data[$Model->alias][$parent]) { - $parentNode = $Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]), - 'fields' => array($Model->primaryKey, $right), 'recursive' => $recursive - )); - if (!$parentNode) { - return false; - } - list($parentNode) = array_values($parentNode); - $Model->data[$Model->alias][$left] = 0; - $Model->data[$Model->alias][$right] = 0; - } else { - $edge = $this->_getMax($Model, $scope, $right, $recursive); - $Model->data[$Model->alias][$left] = $edge + 1; - $Model->data[$Model->alias][$right] = $edge + 2; - } - } elseif (array_key_exists($parent, $Model->data[$Model->alias])) { - if ($Model->data[$Model->alias][$parent] != $Model->field($parent)) { - $this->settings[$Model->alias]['__parentChange'] = true; - } - if (!$Model->data[$Model->alias][$parent]) { - $Model->data[$Model->alias][$parent] = null; - $this->_addToWhitelist($Model, $parent); - } else { - $values = $Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $Model->id), - 'fields' => array($Model->primaryKey, $parent, $left, $right), 'recursive' => $recursive) - ); - - if ($values === false) { - return false; - } - list($node) = array_values($values); - - $parentNode = $Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]), - 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive - )); - if (!$parentNode) { - return false; - } - list($parentNode) = array_values($parentNode); - - if (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) { - return false; - } elseif ($node[$Model->primaryKey] == $parentNode[$Model->primaryKey]) { - return false; - } - } - } - return true; - } - -/** - * Get the number of child nodes - * - * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field) - * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted. - * - * @param Model $Model Model instance - * @param integer|string|boolean $id The ID of the record to read or false to read all top level nodes - * @param boolean $direct whether to count direct, or all, children - * @return integer number of child nodes - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::childCount - */ - public function childCount(Model $Model, $id = null, $direct = false) { - if (is_array($id)) { - extract(array_merge(array('id' => null), $id)); - } - if ($id === null && $Model->id) { - $id = $Model->id; - } elseif (!$id) { - $id = null; - } - extract($this->settings[$Model->alias]); - - if ($direct) { - return $Model->find('count', array('conditions' => array($scope, $Model->escapeField($parent) => $id))); - } - - if ($id === null) { - return $Model->find('count', array('conditions' => $scope)); - } elseif ($Model->id === $id && isset($Model->data[$Model->alias][$left]) && isset($Model->data[$Model->alias][$right])) { - $data = $Model->data[$Model->alias]; - } else { - $data = $Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $id), 'recursive' => $recursive)); - if (!$data) { - return 0; - } - $data = $data[$Model->alias]; - } - return ($data[$right] - $data[$left] - 1) / 2; - } - -/** - * Get the child nodes of the current model - * - * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field) - * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted. - * - * @param Model $Model Model instance - * @param integer|string $id The ID of the record to read - * @param boolean $direct whether to return only the direct, or all, children - * @param string|array $fields Either a single string of a field name, or an array of field names - * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order - * @param integer $limit SQL LIMIT clause, for calculating items per page. - * @param integer $page Page number, for accessing paged data - * @param integer $recursive The number of levels deep to fetch associated records - * @return array Array of child nodes - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::children - */ - public function children(Model $Model, $id = null, $direct = false, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) { - if (is_array($id)) { - extract(array_merge(array('id' => null), $id)); - } - $overrideRecursive = $recursive; - - if ($id === null && $Model->id) { - $id = $Model->id; - } elseif (!$id) { - $id = null; - } - - extract($this->settings[$Model->alias]); - - if ($overrideRecursive !== null) { - $recursive = $overrideRecursive; - } - if (!$order) { - $order = $Model->escapeField($left) . " asc"; - } - if ($direct) { - $conditions = array($scope, $Model->escapeField($parent) => $id); - return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive')); - } - - if (!$id) { - $conditions = $scope; - } else { - $result = array_values((array)$Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $id), - 'fields' => array($left, $right), - 'recursive' => $recursive - ))); - - if (empty($result) || !isset($result[0])) { - return array(); - } - $conditions = array($scope, - $Model->escapeField($right) . ' <' => $result[0][$right], - $Model->escapeField($left) . ' >' => $result[0][$left] - ); - } - return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive')); - } - -/** - * A convenience method for returning a hierarchical array used for HTML select boxes - * - * @param Model $Model Model instance - * @param string|array $conditions SQL conditions as a string or as an array('field' =>'value',...) - * @param string $keyPath A string path to the key, i.e. "{n}.Post.id" - * @param string $valuePath A string path to the value, i.e. "{n}.Post.title" - * @param string $spacer The character or characters which will be repeated - * @param integer $recursive The number of levels deep to fetch associated records - * @return array An associative array of records, where the id is the key, and the display field is the value - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::generateTreeList - */ - public function generateTreeList(Model $Model, $conditions = null, $keyPath = null, $valuePath = null, $spacer = '_', $recursive = null) { - $overrideRecursive = $recursive; - extract($this->settings[$Model->alias]); - if ($overrideRecursive !== null) { - $recursive = $overrideRecursive; - } - - $fields = null; - if (!$keyPath && !$valuePath && $Model->hasField($Model->displayField)) { - $fields = array($Model->primaryKey, $Model->displayField, $left, $right); - } - - if (!$keyPath) { - $keyPath = '{n}.' . $Model->alias . '.' . $Model->primaryKey; - } - - if (!$valuePath) { - $valuePath = array('%s%s', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField); - - } elseif (is_string($valuePath)) { - $valuePath = array('%s%s', '{n}.tree_prefix', $valuePath); - - } else { - array_unshift($valuePath, '%s' . $valuePath[0], '{n}.tree_prefix'); - } - - $conditions = (array)$conditions; - if ($scope) { - $conditions[] = $scope; - } - - $order = $Model->escapeField($left) . " asc"; - $results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive')); - $stack = array(); - - foreach ($results as $i => $result) { - $count = count($stack); - while ($stack && ($stack[$count - 1] < $result[$Model->alias][$right])) { - array_pop($stack); - $count--; - } - $results[$i]['tree_prefix'] = str_repeat($spacer, $count); - $stack[] = $result[$Model->alias][$right]; - } - if (empty($results)) { - return array(); - } - return Hash::combine($results, $keyPath, $valuePath); - } - -/** - * Get the parent node - * - * reads the parent id and returns this node - * - * @param Model $Model Model instance - * @param integer|string $id The ID of the record to read - * @param string|array $fields - * @param integer $recursive The number of levels deep to fetch associated records - * @return array|boolean Array of data for the parent node - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getParentNode - */ - public function getParentNode(Model $Model, $id = null, $fields = null, $recursive = null) { - if (is_array($id)) { - extract(array_merge(array('id' => null), $id)); - } - $overrideRecursive = $recursive; - if (empty($id)) { - $id = $Model->id; - } - extract($this->settings[$Model->alias]); - if ($overrideRecursive !== null) { - $recursive = $overrideRecursive; - } - $parentId = $Model->find('first', array('conditions' => array($Model->primaryKey => $id), 'fields' => array($parent), 'recursive' => -1)); - - if ($parentId) { - $parentId = $parentId[$Model->alias][$parent]; - $parent = $Model->find('first', array('conditions' => array($Model->escapeField() => $parentId), 'fields' => $fields, 'recursive' => $recursive)); - - return $parent; - } - return false; - } - -/** - * Get the path to the given node - * - * @param Model $Model Model instance - * @param integer|string $id The ID of the record to read - * @param string|array $fields Either a single string of a field name, or an array of field names - * @param integer $recursive The number of levels deep to fetch associated records - * @return array Array of nodes from top most parent to current node - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getPath - */ - public function getPath(Model $Model, $id = null, $fields = null, $recursive = null) { - if (is_array($id)) { - extract(array_merge(array('id' => null), $id)); - } - $overrideRecursive = $recursive; - if (empty($id)) { - $id = $Model->id; - } - extract($this->settings[$Model->alias]); - if ($overrideRecursive !== null) { - $recursive = $overrideRecursive; - } - $result = $Model->find('first', array('conditions' => array($Model->escapeField() => $id), 'fields' => array($left, $right), 'recursive' => $recursive)); - if ($result) { - $result = array_values($result); - } else { - return null; - } - $item = $result[0]; - $results = $Model->find('all', array( - 'conditions' => array($scope, $Model->escapeField($left) . ' <=' => $item[$left], $Model->escapeField($right) . ' >=' => $item[$right]), - 'fields' => $fields, 'order' => array($Model->escapeField($left) => 'asc'), 'recursive' => $recursive - )); - return $results; - } - -/** - * Reorder the node without changing the parent. - * - * If the node is the last child, or is a top level node with no subsequent node this method will return false - * - * @param Model $Model Model instance - * @param integer|string $id The ID of the record to move - * @param integer|boolean $number how many places to move the node or true to move to last position - * @return boolean true on success, false on failure - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveDown - */ - public function moveDown(Model $Model, $id = null, $number = 1) { - if (is_array($id)) { - extract(array_merge(array('id' => null), $id)); - } - if (!$number) { - return false; - } - if (empty($id)) { - $id = $Model->id; - } - extract($this->settings[$Model->alias]); - list($node) = array_values($Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $id), - 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive - ))); - if ($node[$parent]) { - list($parentNode) = array_values($Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $node[$parent]), - 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive - ))); - if (($node[$right] + 1) == $parentNode[$right]) { - return false; - } - } - $nextNode = $Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField($left) => ($node[$right] + 1)), - 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive) - ); - if ($nextNode) { - list($nextNode) = array_values($nextNode); - } else { - return false; - } - $edge = $this->_getMax($Model, $scope, $right, $recursive); - $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]); - $this->_sync($Model, $nextNode[$left] - $node[$left], '-', 'BETWEEN ' . $nextNode[$left] . ' AND ' . $nextNode[$right]); - $this->_sync($Model, $edge - $node[$left] - ($nextNode[$right] - $nextNode[$left]), '-', '> ' . $edge); - - if (is_int($number)) { - $number--; - } - if ($number) { - $this->moveDown($Model, $id, $number); - } - return true; - } - -/** - * Reorder the node without changing the parent. - * - * If the node is the first child, or is a top level node with no previous node this method will return false - * - * @param Model $Model Model instance - * @param integer|string $id The ID of the record to move - * @param integer|boolean $number how many places to move the node, or true to move to first position - * @return boolean true on success, false on failure - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveUp - */ - public function moveUp(Model $Model, $id = null, $number = 1) { - if (is_array($id)) { - extract(array_merge(array('id' => null), $id)); - } - if (!$number) { - return false; - } - if (empty($id)) { - $id = $Model->id; - } - extract($this->settings[$Model->alias]); - list($node) = array_values($Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $id), - 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive - ))); - if ($node[$parent]) { - list($parentNode) = array_values($Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $node[$parent]), - 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive - ))); - if (($node[$left] - 1) == $parentNode[$left]) { - return false; - } - } - $previousNode = $Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField($right) => ($node[$left] - 1)), - 'fields' => array($Model->primaryKey, $left, $right), - 'recursive' => $recursive - )); - - if ($previousNode) { - list($previousNode) = array_values($previousNode); - } else { - return false; - } - $edge = $this->_getMax($Model, $scope, $right, $recursive); - $this->_sync($Model, $edge - $previousNode[$left] + 1, '+', 'BETWEEN ' . $previousNode[$left] . ' AND ' . $previousNode[$right]); - $this->_sync($Model, $node[$left] - $previousNode[$left], '-', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]); - $this->_sync($Model, $edge - $previousNode[$left] - ($node[$right] - $node[$left]), '-', '> ' . $edge); - if (is_int($number)) { - $number--; - } - if ($number) { - $this->moveUp($Model, $id, $number); - } - return true; - } - -/** - * Recover a corrupted tree - * - * The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data - * will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode - * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction - * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present. - * - * @param Model $Model Model instance - * @param string $mode parent or tree - * @param string|integer $missingParentAction 'return' to do nothing and return, 'delete' to - * delete, or the id of the parent to set as the parent_id - * @return boolean true on success, false on failure - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::recover - */ - public function recover(Model $Model, $mode = 'parent', $missingParentAction = null) { - if (is_array($mode)) { - extract(array_merge(array('mode' => 'parent'), $mode)); - } - extract($this->settings[$Model->alias]); - $Model->recursive = $recursive; - if ($mode === 'parent') { - $Model->bindModel(array('belongsTo' => array('VerifyParent' => array( - 'className' => $Model->name, - 'foreignKey' => $parent, - 'fields' => array($Model->primaryKey, $left, $right, $parent), - )))); - $missingParents = $Model->find('list', array( - 'recursive' => 0, - 'conditions' => array($scope, array( - 'NOT' => array($Model->escapeField($parent) => null), $Model->VerifyParent->escapeField() => null - )) - )); - $Model->unbindModel(array('belongsTo' => array('VerifyParent'))); - if ($missingParents) { - if ($missingParentAction === 'return') { - foreach ($missingParents as $id => $display) { - $this->errors[] = 'cannot find the parent for ' . $Model->alias . ' with id ' . $id . '(' . $display . ')'; - } - return false; - } elseif ($missingParentAction === 'delete') { - $Model->deleteAll(array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)), false); - } else { - $Model->updateAll(array($Model->escapeField($parent) => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents))); - } - } - - $this->_recoverByParentId($Model); - } else { - $db = ConnectionManager::getDataSource($Model->useDbConfig); - foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) { - $path = $this->getPath($Model, $array[$Model->alias][$Model->primaryKey]); - $parentId = null; - if (count($path) > 1) { - $parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey]; - } - $Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey])); - } - } - return true; - } - -/** - * _recoverByParentId - * - * Recursive helper function used by recover - * - * @param Model $Model - * @param integer $counter - * @param mixed $parentId - * @return integer $counter - */ - protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = null) { - $params = array( - 'conditions' => array( - $this->settings[$Model->alias]['parent'] => $parentId - ), - 'fields' => array($Model->primaryKey), - 'page' => 1, - 'limit' => 100, - 'order' => array($Model->primaryKey) - ); - - $scope = $this->settings[$Model->alias]['scope']; - if ($scope && ($scope !== '1 = 1' && $scope !== true)) { - $params['conditions'][] = $scope; - } - - $children = $Model->find('all', $params); - $hasChildren = (bool)$children; - - if ($parentId !== null) { - if ($hasChildren) { - $Model->updateAll( - array($this->settings[$Model->alias]['left'] => $counter), - array($Model->escapeField() => $parentId) - ); - $counter++; - } else { - $Model->updateAll( - array( - $this->settings[$Model->alias]['left'] => $counter, - $this->settings[$Model->alias]['right'] => $counter + 1 - ), - array($Model->escapeField() => $parentId) - ); - $counter += 2; - } - } - - while ($children) { - foreach ($children as $row) { - $counter = $this->_recoverByParentId($Model, $counter, $row[$Model->alias][$Model->primaryKey]); - } - - if (count($children) !== $params['limit']) { - break; - } - $params['page']++; - $children = $Model->find('all', $params); - } - - if ($parentId !== null && $hasChildren) { - $Model->updateAll( - array($this->settings[$Model->alias]['right'] => $counter), - array($Model->escapeField() => $parentId) - ); - $counter++; - } - - return $counter; - } - -/** - * Reorder method. - * - * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters. - * This method does not change the parent of any node. - * - * Requires a valid tree, by default it verifies the tree before beginning. - * - * Options: - * - * - 'id' id of record to use as top node for reordering - * - 'field' Which field to use in reordering defaults to displayField - * - 'order' Direction to order either DESC or ASC (defaults to ASC) - * - 'verify' Whether or not to verify the tree before reorder. defaults to true. - * - * @param Model $Model Model instance - * @param array $options array of options to use in reordering. - * @return boolean true on success, false on failure - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::reorder - */ - public function reorder(Model $Model, $options = array()) { - $options = array_merge(array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true), $options); - extract($options); - if ($verify && !$this->verify($Model)) { - return false; - } - $verify = false; - extract($this->settings[$Model->alias]); - $fields = array($Model->primaryKey, $field, $left, $right); - $sort = $field . ' ' . $order; - $nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive); - - $cacheQueries = $Model->cacheQueries; - $Model->cacheQueries = false; - if ($nodes) { - foreach ($nodes as $node) { - $id = $node[$Model->alias][$Model->primaryKey]; - $this->moveDown($Model, $id, true); - if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) { - $this->reorder($Model, compact('id', 'field', 'order', 'verify')); - } - } - } - $Model->cacheQueries = $cacheQueries; - return true; - } - -/** - * Remove the current node from the tree, and reparent all children up one level. - * - * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted - * after the children are reparented. - * - * @param Model $Model Model instance - * @param integer|string $id The ID of the record to remove - * @param boolean $delete whether to delete the node after reparenting children (if any) - * @return boolean true on success, false on failure - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::removeFromTree - */ - public function removeFromTree(Model $Model, $id = null, $delete = false) { - if (is_array($id)) { - extract(array_merge(array('id' => null), $id)); - } - extract($this->settings[$Model->alias]); - - list($node) = array_values($Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $id), - 'fields' => array($Model->primaryKey, $left, $right, $parent), - 'recursive' => $recursive - ))); - - if ($node[$right] == $node[$left] + 1) { - if ($delete) { - return $Model->delete($id); - } - $Model->id = $id; - return $Model->saveField($parent, null); - } elseif ($node[$parent]) { - list($parentNode) = array_values($Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $node[$parent]), - 'fields' => array($Model->primaryKey, $left, $right), - 'recursive' => $recursive - ))); - } else { - $parentNode[$right] = $node[$right] + 1; - } - - $db = ConnectionManager::getDataSource($Model->useDbConfig); - $Model->updateAll( - array($parent => $db->value($node[$parent], $parent)), - array($Model->escapeField($parent) => $node[$Model->primaryKey]) - ); - $this->_sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1)); - $this->_sync($Model, 2, '-', '> ' . ($node[$right])); - $Model->id = $id; - - if ($delete) { - $Model->updateAll( - array( - $Model->escapeField($left) => 0, - $Model->escapeField($right) => 0, - $Model->escapeField($parent) => null - ), - array($Model->escapeField() => $id) - ); - return $Model->delete($id); - } - $edge = $this->_getMax($Model, $scope, $right, $recursive); - if ($node[$right] == $edge) { - $edge = $edge - 2; - } - $Model->id = $id; - return $Model->save( - array($left => $edge + 1, $right => $edge + 2, $parent => null), - array('callbacks' => false, 'validate' => false) - ); - } - -/** - * Check if the current tree is valid. - * - * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message) - * - * @param Model $Model Model instance - * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node], - * [incorrect left/right index,node id], message) - * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::verify - */ - public function verify(Model $Model) { - extract($this->settings[$Model->alias]); - if (!$Model->find('count', array('conditions' => $scope))) { - return true; - } - $min = $this->_getMin($Model, $scope, $left, $recursive); - $edge = $this->_getMax($Model, $scope, $right, $recursive); - $errors = array(); - - for ($i = $min; $i <= $edge; $i++) { - $count = $Model->find('count', array('conditions' => array( - $scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i) - ))); - if ($count != 1) { - if (!$count) { - $errors[] = array('index', $i, 'missing'); - } else { - $errors[] = array('index', $i, 'duplicate'); - } - } - } - $node = $Model->find('first', array('conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)), 'recursive' => 0)); - if ($node) { - $errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.'); - } - - $Model->bindModel(array('belongsTo' => array('VerifyParent' => array( - 'className' => $Model->name, - 'foreignKey' => $parent, - 'fields' => array($Model->primaryKey, $left, $right, $parent) - )))); - - foreach ($Model->find('all', array('conditions' => $scope, 'recursive' => 0)) as $instance) { - if ($instance[$Model->alias][$left] === null || $instance[$Model->alias][$right] === null) { - $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], - 'has invalid left or right values'); - } elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) { - $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], - 'left and right values identical'); - } elseif ($instance[$Model->alias][$parent]) { - if (!$instance['VerifyParent'][$Model->primaryKey]) { - $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], - 'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist'); - } elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) { - $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], - 'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').'); - } elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) { - $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], - 'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').'); - } - } elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) { - $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent'); - } - } - if ($errors) { - return $errors; - } - return true; - } - -/** - * Sets the parent of the given node - * - * The force parameter is used to override the "don't change the parent to the current parent" logic in the event - * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this - * method could be private, since calling save with parent_id set also calls setParent - * - * @param Model $Model Model instance - * @param integer|string $parentId - * @param boolean $created - * @return boolean true on success, false on failure - */ - protected function _setParent(Model $Model, $parentId = null, $created = false) { - extract($this->settings[$Model->alias]); - list($node) = array_values($Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $Model->id), - 'fields' => array($Model->primaryKey, $parent, $left, $right), - 'recursive' => $recursive - ))); - $edge = $this->_getMax($Model, $scope, $right, $recursive, $created); - - if (empty($parentId)) { - $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created); - $this->_sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created); - } else { - $values = $Model->find('first', array( - 'conditions' => array($scope, $Model->escapeField() => $parentId), - 'fields' => array($Model->primaryKey, $left, $right), - 'recursive' => $recursive - )); - - if ($values === false) { - return false; - } - $parentNode = array_values($values); - - if (empty($parentNode) || empty($parentNode[0])) { - return false; - } - $parentNode = $parentNode[0]; - - if (($Model->id == $parentId)) { - return false; - } elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) { - return false; - } - if (empty($node[$left]) && empty($node[$right])) { - $this->_sync($Model, 2, '+', '>= ' . $parentNode[$right], $created); - $result = $Model->save( - array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId), - array('validate' => false, 'callbacks' => false) - ); - $Model->data = $result; - } else { - $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created); - $diff = $node[$right] - $node[$left] + 1; - - if ($node[$left] > $parentNode[$left]) { - if ($node[$right] < $parentNode[$right]) { - $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created); - $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created); - } else { - $this->_sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created); - $this->_sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created); - } - } else { - $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created); - $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created); - } - } - } - return true; - } - -/** - * get the maximum index value in the table. - * - * @param Model $Model - * @param string $scope - * @param string $right - * @param integer $recursive - * @param boolean $created - * @return integer - */ - protected function _getMax(Model $Model, $scope, $right, $recursive = -1, $created = false) { - $db = ConnectionManager::getDataSource($Model->useDbConfig); - if ($created) { - if (is_string($scope)) { - $scope .= " AND " . $Model->escapeField() . " <> "; - $scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey)); - } else { - $scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id; - } - } - $name = $Model->escapeField($right); - list($edge) = array_values($Model->find('first', array( - 'conditions' => $scope, - 'fields' => $db->calculate($Model, 'max', array($name, $right)), - 'recursive' => $recursive, - 'callbacks' => false - ))); - return (empty($edge[$right])) ? 0 : $edge[$right]; - } - -/** - * get the minimum index value in the table. - * - * @param Model $Model - * @param string $scope - * @param string $left - * @param integer $recursive - * @return integer - */ - protected function _getMin(Model $Model, $scope, $left, $recursive = -1) { - $db = ConnectionManager::getDataSource($Model->useDbConfig); - $name = $Model->escapeField($left); - list($edge) = array_values($Model->find('first', array( - 'conditions' => $scope, - 'fields' => $db->calculate($Model, 'min', array($name, $left)), - 'recursive' => $recursive, - 'callbacks' => false - ))); - return (empty($edge[$left])) ? 0 : $edge[$left]; - } - -/** - * Table sync method. - * - * Handles table sync operations, Taking account of the behavior scope. - * - * @param Model $Model - * @param integer $shift - * @param string $dir - * @param array $conditions - * @param boolean $created - * @param string $field - * @return void - */ - protected function _sync(Model $Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') { - $ModelRecursive = $Model->recursive; - extract($this->settings[$Model->alias]); - $Model->recursive = $recursive; - - if ($field === 'both') { - $this->_sync($Model, $shift, $dir, $conditions, $created, $left); - $field = $right; - } - if (is_string($conditions)) { - $conditions = array($Model->escapeField($field) . " {$conditions}"); - } - if (($scope !== '1 = 1' && $scope !== true) && $scope) { - $conditions[] = $scope; - } - if ($created) { - $conditions['NOT'][$Model->escapeField()] = $Model->id; - } - $Model->updateAll(array($Model->escapeField($field) => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions); - $Model->recursive = $ModelRecursive; - } - -} diff --git a/Cake/Model/BehaviorCollection.php b/Cake/Model/BehaviorCollection.php deleted file mode 100644 index 98789695fcc..00000000000 --- a/Cake/Model/BehaviorCollection.php +++ /dev/null @@ -1,273 +0,0 @@ -modelName = $modelName; - - if (!empty($behaviors)) { - foreach (BehaviorCollection::normalizeObjectArray($behaviors) as $config) { - $this->load($config['class'], $config['settings']); - } - } - } - -/** - * Loads a behavior into the collection. You can use use `$config['enabled'] = false` - * to load a behavior with callbacks disabled. By default callbacks are enabled. Disable behaviors - * can still be used as normal. - * - * You can alias your behavior as an existing behavior by setting the 'className' key, i.e., - * {{{ - * public $actsAs = array( - * 'Tree' => array( - * 'className' => 'AliasedTree' - * ); - * ); - * }}} - * All calls to the `Tree` behavior would use `AliasedTree` instead. - * - * @param string $behavior CamelCased name of the behavior to load - * @param array $config Behavior configuration parameters - * @return boolean True on success, false on failure - * @throws Cake\Error\MissingBehaviorException when a behavior could not be found. - */ - public function load($behavior, $config = array()) { - if (isset($config['className'])) { - $alias = $behavior; - $behavior = $config['className']; - } - $configDisabled = isset($config['enabled']) && $config['enabled'] === false; - $priority = isset($config['priority']) ? $config['priority'] : $this->defaultPriority; - unset($config['enabled'], $config['className'], $config['priority']); - - list($plugin, $name) = pluginSplit($behavior, true); - if (!isset($alias)) { - $alias = $name; - } - $class = App::classname($behavior, 'Model/Behavior', 'Behavior'); - if (!$class) { - throw new Error\MissingBehaviorException(array( - 'class' => $name . 'Behavior', - 'plugin' => substr($plugin, 0, -1) - )); - } - - if (!isset($this->{$alias})) { - if (ClassRegistry::isKeySet($class)) { - $this->_loaded[$alias] = ClassRegistry::getObject($class); - } else { - $this->_loaded[$alias] = new $class(); - ClassRegistry::addObject($class, $this->_loaded[$alias]); - } - } elseif (isset($this->_loaded[$alias]->settings) && isset($this->_loaded[$alias]->settings[$this->modelName])) { - if ($config !== null && $config !== false) { - $config = array_merge($this->_loaded[$alias]->settings[$this->modelName], $config); - } else { - $config = array(); - } - } - if (empty($config)) { - $config = array(); - } - $this->_loaded[$alias]->settings['priority'] = $priority; - $this->_loaded[$alias]->setup(ClassRegistry::getObject($this->modelName), $config); - - foreach ($this->_loaded[$alias]->mapMethods as $method => $methodAlias) { - $this->_mappedMethods[$method] = array($alias, $methodAlias); - } - $methods = get_class_methods($this->_loaded[$alias]); - $x = new \Cake\Model\ModelBehavior(); - $parentMethods = array_flip(get_class_methods('Cake\Model\ModelBehavior')); - $callbacks = array( - 'setup', 'cleanup', 'beforeFind', 'afterFind', 'beforeSave', 'afterSave', - 'beforeDelete', 'afterDelete', 'onError' - ); - - foreach ($methods as $m) { - if (!isset($parentMethods[$m])) { - $methodAllowed = ( - $m[0] !== '_' && !array_key_exists($m, $this->_methods) && - !in_array($m, $callbacks) - ); - if ($methodAllowed) { - $this->_methods[$m] = array($alias, $m); - } - } - } - - if ($configDisabled) { - $this->disable($alias); - } elseif (!$this->enabled($alias)) { - $this->enable($alias); - } else { - $this->setPriority($alias, $priority); - } - - return true; - } - -/** - * Detaches a behavior from a model - * - * @param string $name CamelCased name of the behavior to unload - * @return void - */ - public function unload($name) { - list(, $name) = pluginSplit($name); - if (isset($this->_loaded[$name])) { - $this->_loaded[$name]->cleanup(ClassRegistry::getObject($this->modelName)); - parent::unload($name); - } - foreach ($this->_methods as $m => $callback) { - if (is_array($callback) && $callback[0] == $name) { - unset($this->_methods[$m]); - } - } - } - -/** - * Dispatches a behavior method. Will call either normal methods or mapped methods. - * - * If a method is not handled by the BehaviorCollection, and $strict is false, a - * special return of `array('unhandled')` will be returned to signal the method was not found. - * - * @param Model $model The model the method was originally called on. - * @param string $method The method called. - * @param array $params Parameters for the called method. - * @param boolean $strict If methods are not found, trigger an error. - * @return array All methods for all behaviors attached to this object - */ - public function dispatchMethod($model, $method, $params = array(), $strict = false) { - $method = $this->hasMethod($method, true); - - if ($strict && empty($method)) { - trigger_error(__d('cake_dev', '%s - Method %s not found in any attached behavior', 'BehaviorCollection::dispatchMethod()', $method), E_USER_WARNING); - return null; - } - if (empty($method)) { - return array('unhandled'); - } - if (count($method) === 3) { - array_unshift($params, $method[2]); - unset($method[2]); - } - return call_user_func_array( - array($this->_loaded[$method[0]], $method[1]), - array_merge(array(&$model), $params) - ); - } - -/** - * Gets the method list for attached behaviors, i.e. all public, non-callback methods. - * This does not include mappedMethods. - * - * @return array All public methods for all behaviors attached to this collection - */ - public function methods() { - return $this->_methods; - } - -/** - * Check to see if a behavior in this collection implements the provided method. Will - * also check mappedMethods. - * - * @param string $method The method to find. - * @param boolean $callback Return the callback for the method. - * @return mixed If $callback is false, a boolean will be returned, if its true, an array - * containing callback information will be returned. For mapped methods the array will have 3 elements. - */ - public function hasMethod($method, $callback = false) { - if (isset($this->_methods[$method])) { - return $callback ? $this->_methods[$method] : true; - } - foreach ($this->_mappedMethods as $pattern => $target) { - if (preg_match($pattern . 'i', $method)) { - if ($callback) { - $target[] = $method; - return $target; - } - return true; - } - } - return false; - } - -/** - * Returns the implemented events that will get routed to the trigger function - * in order to dispatch them separately on each behavior - * - * @return array - */ - public function implementedEvents() { - return array( - 'Model.beforeFind' => 'trigger', - 'Model.afterFind' => 'trigger', - 'Model.beforeValidate' => 'trigger', - 'Model.afterValidate' => 'trigger', - 'Model.beforeSave' => 'trigger', - 'Model.afterSave' => 'trigger', - 'Model.beforeDelete' => 'trigger', - 'Model.afterDelete' => 'trigger' - ); - } - -} diff --git a/Cake/Model/Datasource/DataSource.php b/Cake/Model/Datasource/DataSource.php deleted file mode 100644 index cc6971eadfc..00000000000 --- a/Cake/Model/Datasource/DataSource.php +++ /dev/null @@ -1,441 +0,0 @@ -setConfig($config); - } - -/** - * Caches/returns cached results for child instances - * - * @param mixed $data - * @return array Array of sources available in this datasource. - */ - public function listSources($data = null) { - if ($this->cacheSources === false) { - return null; - } - - if ($this->_sources !== null) { - return $this->_sources; - } - - $key = ConnectionManager::getSourceName($this) . '_' . $this->config['database'] . '_list'; - $key = preg_replace('/[^A-Za-z0-9_\-.+]/', '_', $key); - $sources = Cache::read($key, '_cake_model_'); - - if (empty($sources)) { - $sources = $data; - Cache::write($key, $data, '_cake_model_'); - } - - return $this->_sources = $sources; - } - -/** - * Returns a Model description (metadata) or null if none found. - * - * @param Model|string $model - * @return array Array of Metadata for the $model - */ - public function describe($model) { - if ($this->cacheSources === false) { - return null; - } - if (is_string($model)) { - $table = $model; - } else { - $table = $model->tablePrefix . $model->table; - } - - if (isset($this->_descriptions[$table])) { - return $this->_descriptions[$table]; - } - $cache = $this->_cacheDescription($table); - - if ($cache !== null) { - $this->_descriptions[$table] =& $cache; - return $cache; - } - return null; - } - -/** - * Begin a transaction - * - * @return boolean Returns true if a transaction is not in progress - */ - public function begin() { - return !$this->_transactionStarted; - } - -/** - * Commit a transaction - * - * @return boolean Returns true if a transaction is in progress - */ - public function commit() { - return $this->_transactionStarted; - } - -/** - * Rollback a transaction - * - * @return boolean Returns true if a transaction is in progress - */ - public function rollback() { - return $this->_transactionStarted; - } - -/** - * Converts column types to basic types - * - * @param string $real Real column type (i.e. "varchar(255)") - * @return string Abstract column type (i.e. "string") - */ - public function column($real) { - return false; - } - -/** - * Used to create new records. The "C" CRUD. - * - * To-be-overridden in subclasses. - * - * @param Model $Model The Model to be created. - * @param array $fields An Array of fields to be saved. - * @param array $values An Array of values to save. - * @return boolean success - */ - public function create(Model $Model, $fields = null, $values = null) { - return false; - } - -/** - * Used to read records from the Datasource. The "R" in CRUD - * - * To-be-overridden in subclasses. - * - * @param Model $Model The model being read. - * @param array $queryData An array of query data used to find the data you want - * @param integer $recursive Number of levels of association - * @return mixed - */ - public function read(Model $Model, $queryData = array(), $recursive = null) { - return false; - } - -/** - * Update a record(s) in the datasource. - * - * To-be-overridden in subclasses. - * - * @param Model $Model Instance of the model class being updated - * @param array $fields Array of fields to be updated - * @param array $values Array of values to be update $fields to. - * @param mixed $conditions - * @return boolean Success - */ - public function update(Model $Model, $fields = null, $values = null, $conditions = null) { - return false; - } - -/** - * Delete a record(s) in the datasource. - * - * To-be-overridden in subclasses. - * - * @param Model $Model The model class having record(s) deleted - * @param mixed $conditions The conditions to use for deleting. - * @return boolean Success - */ - public function delete(Model $Model, $conditions = null) { - return false; - } - -/** - * Returns the ID generated from the previous INSERT operation. - * - * @param mixed $source - * @return mixed Last ID key generated in previous INSERT - */ - public function lastInsertId($source = null) { - return false; - } - -/** - * Returns the number of rows returned by last operation. - * - * @param mixed $source - * @return integer Number of rows returned by last operation - */ - public function lastNumRows($source = null) { - return false; - } - -/** - * Returns the number of rows affected by last query. - * - * @param mixed $source - * @return integer Number of rows affected by last query. - */ - public function lastAffected($source = null) { - return false; - } - -/** - * Check whether the conditions for the Datasource being available - * are satisfied. Often used from connect() to check for support - * before establishing a connection. - * - * @return boolean Whether or not the Datasources conditions for use are met. - */ - public function enabled() { - return true; - } - -/** - * Sets the configuration for the DataSource. - * Merges the $config information with the _baseConfig and the existing $config property. - * - * @param array $config The configuration array - * @return void - */ - public function setConfig($config = array()) { - $this->config = array_merge($this->_baseConfig, $this->config, $config); - } - -/** - * Cache the DataSource description - * - * @param string $object The name of the object (model) to cache - * @param mixed $data The description of the model, usually a string or array - * @return mixed - */ - protected function _cacheDescription($object, $data = null) { - if ($this->cacheSources === false) { - return null; - } - - if ($data !== null) { - $this->_descriptions[$object] =& $data; - } - - $key = ConnectionManager::getSourceName($this) . '_' . $object; - $cache = Cache::read($key, '_cake_model_'); - - if (empty($cache)) { - $cache = $data; - Cache::write($key, $cache, '_cake_model_'); - } - - return $cache; - } - -/** - * Replaces `{$__cakeID__$}` and `{$__cakeForeignKey__$}` placeholders in query data. - * - * @param string $query Query string needing replacements done. - * @param array $data Array of data with values that will be inserted in placeholders. - * @param string $association Name of association model being replaced - * @param Model $Model Model instance - * @param array $stack - * @return string String of query data with placeholders replaced. - */ - public function insertQueryData($query, $data, $association, Model $Model, $stack) { - $keys = array('{$__cakeID__$}', '{$__cakeForeignKey__$}'); - - $modelAlias = $Model->alias; - - foreach ($keys as $key) { - if (strpos($query, $key) === false) { - continue; - } - - $insertKey = $InsertModel = null; - switch ($key) { - case '{$__cakeID__$}': - $InsertModel = $Model; - $insertKey = $Model->primaryKey; - - break; - case '{$__cakeForeignKey__$}': - foreach ($Model->associations() as $type) { - foreach ($Model->{$type} as $assoc => $assocData) { - if ($assoc !== $association) { - continue; - } - - if (isset($assocData['foreignKey'])) { - $InsertModel = $Model->{$assoc}; - $insertKey = $assocData['foreignKey']; - } - - break 3; - } - } - - break; - } - - $val = $dataType = null; - if (!empty($insertKey) && !empty($InsertModel)) { - if (isset($data[$modelAlias][$insertKey])) { - $val = $data[$modelAlias][$insertKey]; - } elseif (isset($data[$association][$insertKey])) { - $val = $data[$association][$insertKey]; - } else { - $found = false; - foreach (array_reverse($stack) as $assocData) { - if (isset($data[$assocData]) && isset($data[$assocData][$insertKey])) { - $val = $data[$assocData][$insertKey]; - $found = true; - break; - } - } - - if (!$found) { - $val = ''; - } - } - - $dataType = $InsertModel->getColumnType($InsertModel->primaryKey); - } - - if (empty($val) && $val !== '0') { - return false; - } - - $query = str_replace($key, $this->value($val, $dataType), $query); - } - - return $query; - } - -/** - * To-be-overridden in subclasses. - * - * @param Model $Model Model instance - * @param string $key Key name to make - * @return string Key name for model. - */ - public function resolveKey(Model $Model, $key) { - return $Model->alias . $key; - } - -/** - * Returns the schema name. Override this in subclasses. - * - * @return string schema name - */ - public function getSchemaName() { - return null; - } - -/** - * Closes a connection. Override in subclasses - * - * @return boolean - */ - public function close() { - return $this->connected = false; - } - -/** - * Closes the current datasource. - */ - public function __destruct() { - if ($this->_transactionStarted) { - $this->rollback(); - } - if ($this->connected) { - $this->close(); - } - } - -} diff --git a/Cake/Model/I18nModel.php b/Cake/Model/I18nModel.php deleted file mode 100644 index 61a5a805cf9..00000000000 --- a/Cake/Model/I18nModel.php +++ /dev/null @@ -1,44 +0,0 @@ - table 'users'; class 'Man' => table 'men') - * The table is required to have at least 'id auto_increment' primary key. - * - * @link http://book.cakephp.org/2.0/en/models.html - */ -class Model extends Object implements EventListener { - - use MergeVariablesTrait; - -/** - * The name of the DataSource connection that this Model uses - * - * The value must be an attribute name that you defined in `App/Config/datasources.php` - * or created using `ConnectionManager::create()`. - * - * @var string - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig - */ - public $useDbConfig = 'default'; - -/** - * Custom database table name, or null/false if no table association is desired. - * - * @var string - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usetable - */ - public $useTable = null; - -/** - * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements. - * - * This field is also used in `find('list')` when called with no extra parameters in the fields list - * - * @var string - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayfield - */ - public $displayField = null; - -/** - * Value of the primary key ID of the record that this model is currently pointing to. - * Automatically set after database insertions. - * - * @var mixed - */ - public $id = false; - -/** - * Container for the data that this model gets from persistent storage (usually, a database). - * - * @var array - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data - */ - public $data = array(); - -/** - * Holds physical schema/database name for this model. Automatically set during Model creation. - * - * @var string - */ - public $schemaName = null; - -/** - * Table name for this Model. - * - * @var string - */ - public $table = false; - -/** - * The name of the primary key field for this model. - * - * @var string - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primaryKey - */ - public $primaryKey = null; - -/** - * Field-by-field table metadata. - * - * @var array - */ - protected $_schema = null; - -/** - * List of validation rules. It must be an array with the field name as key and using - * as value one of the following possibilities - * - * ### Validating using regular expressions - * - * {{{ - * public $validate = array( - * 'name' => '/^[a-z].+$/i' - * ); - * }}} - * - * ### Validating using methods (no parameters) - * - * {{{ - * public $validate = array( - * 'name' => 'notEmpty' - * ); - * }}} - * - * ### Validating using methods (with parameters) - * - * {{{ - * public $validate = array( - * 'age' => array( - * 'rule' => array('between', 5, 25) - * ) - * ); - * }}} - * - * ### Validating using custom method - * - * {{{ - * public $validate = array( - * 'password' => array( - * 'rule' => array('customValidation') - * ) - * ); - * public function customValidation($data) { - * // $data will contain array('password' => 'value') - * if (isset($this->data[$this->alias]['password2'])) { - * return $this->data[$this->alias]['password2'] === current($data); - * } - * return true; - * } - * }}} - * - * ### Validations with messages - * - * The messages will be used in Model::$validationErrors and can be used in the FormHelper - * - * {{{ - * public $validate = array( - * 'age' => array( - * 'rule' => array('between', 5, 25), - * 'message' => array('The age must be between %d and %d.') - * ) - * ); - * }}} - * - * ### Multiple validations to the same field - * - * {{{ - * public $validate = array( - * 'login' => array( - * array( - * 'rule' => 'alphaNumeric', - * 'message' => 'Only alphabets and numbers allowed', - * 'last' => true - * ), - * array( - * 'rule' => array('minLength', 8), - * 'message' => array('Minimum length of %d characters') - * ) - * ) - * ); - * }}} - * - * ### Valid keys in validations - * - * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters - * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf - * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true] - * - `required`: Boolean value to indicate if the field must be present on save - * - `allowEmpty`: Boolean value to indicate if the field can be empty - * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create - * - * @var array - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate - * @link http://book.cakephp.org/2.0/en/models/data-validation.html - */ - public $validate = array(); - -/** - * List of validation errors. - * - * @var array - */ - public $validationErrors = array(); - -/** - * Name of the validation string domain to use when translating validation errors. - * - * @var string - */ - public $validationDomain = null; - -/** - * Database table prefix for tables in model. - * - * @var string - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix - */ - public $tablePrefix = null; - -/** - * Plugin model belongs to. - * - * @var string - */ - public $plugin = null; - -/** - * Name of the model. - * - * @var string - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name - */ - public $name = null; - -/** - * Alias name for model. - * - * @var string - */ - public $alias = null; - -/** - * List of table names included in the model description. Used for associations. - * - * @var array - */ - public $tableToModel = array(); - -/** - * Whether or not to cache queries for this model. This enables in-memory - * caching only, the results are not stored beyond the current request. - * - * @var boolean - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cachequeries - */ - public $cacheQueries = false; - -/** - * Detailed list of belongsTo associations. - * - * ### Basic usage - * - * `public $belongsTo = array('Group', 'Department');` - * - * ### Detailed configuration - * - * {{{ - * public $belongsTo = array( - * 'Group', - * 'Department' => array( - * 'className' => 'Department', - * 'foreignKey' => 'department_id' - * ) - * ); - * }}} - * - * ### Possible keys in association - * - * - `className`: the class name of the model being associated to the current model. - * If you're defining a 'Profile belongsTo User' relationship, the className key should equal 'User.' - * - `foreignKey`: the name of the foreign key found in the current model. This is - * especially handy if you need to define multiple belongsTo relationships. The default - * value for this key is the underscored, singular name of the other model, suffixed with '_id'. - * - `conditions`: An SQL fragment used to filter related model records. It's good - * practice to use model names in SQL fragments: 'User.active = 1' is always - * better than just 'active = 1.' - * - `type`: the type of the join to use in the SQL query, default is LEFT which - * may not fit your needs in all situations, INNER may be helpful when you want - * everything from your main and associated models or nothing at all!(effective - * when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner) - * - `fields`: A list of fields to be retrieved when the associated model data is - * fetched. Returns all fields by default. - * - `order`: An SQL fragment that defines the sorting order for the returned associated rows. - * - `counterCache`: If set to true the associated Model will automatically increase or - * decrease the "[singular_model_name]_count" field in the foreign table whenever you do - * a save() or delete(). If its a string then its the field name to use. The value in the - * counter field represents the number of related rows. - * - `counterScope`: Optional conditions array to use for updating counter cache field. - * - * @var array - * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto - */ - public $belongsTo = array(); - -/** - * Detailed list of hasOne associations. - * - * ### Basic usage - * - * `public $hasOne = array('Profile', 'Address');` - * - * ### Detailed configuration - * - * {{{ - * public $hasOne = array( - * 'Profile', - * 'Address' => array( - * 'className' => 'Address', - * 'foreignKey' => 'user_id' - * ) - * ); - * }}} - * - * ### Possible keys in association - * - * - `className`: the class name of the model being associated to the current model. - * If you're defining a 'User hasOne Profile' relationship, the className key should equal 'Profile.' - * - `foreignKey`: the name of the foreign key found in the other model. This is - * especially handy if you need to define multiple hasOne relationships. - * The default value for this key is the underscored, singular name of the - * current model, suffixed with '_id'. In the example above it would default to 'user_id'. - * - `conditions`: An SQL fragment used to filter related model records. It's good - * practice to use model names in SQL fragments: "Profile.approved = 1" is - * always better than just "approved = 1." - * - `fields`: A list of fields to be retrieved when the associated model data is - * fetched. Returns all fields by default. - * - `order`: An SQL fragment that defines the sorting order for the returned associated rows. - * - `dependent`: When the dependent key is set to true, and the model's delete() - * method is called with the cascade parameter set to true, associated model - * records are also deleted. In this case we set it true so that deleting a - * User will also delete her associated Profile. - * - * @var array - * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone - */ - public $hasOne = array(); - -/** - * Detailed list of hasMany associations. - * - * ### Basic usage - * - * `public $hasMany = array('Comment', 'Task');` - * - * ### Detailed configuration - * - * {{{ - * public $hasMany = array( - * 'Comment', - * 'Task' => array( - * 'className' => 'Task', - * 'foreignKey' => 'user_id' - * ) - * ); - * }}} - * - * ### Possible keys in association - * - * - `className`: the class name of the model being associated to the current model. - * If you're defining a 'User hasMany Comment' relationship, the className key should equal 'Comment.' - * - `foreignKey`: the name of the foreign key found in the other model. This is - * especially handy if you need to define multiple hasMany relationships. The default - * value for this key is the underscored, singular name of the actual model, suffixed with '_id'. - * - `conditions`: An SQL fragment used to filter related model records. It's good - * practice to use model names in SQL fragments: "Comment.status = 1" is always - * better than just "status = 1." - * - `fields`: A list of fields to be retrieved when the associated model data is - * fetched. Returns all fields by default. - * - `order`: An SQL fragment that defines the sorting order for the returned associated rows. - * - `limit`: The maximum number of associated rows you want returned. - * - `offset`: The number of associated rows to skip over (given the current - * conditions and order) before fetching and associating. - * - `dependent`: When dependent is set to true, recursive model deletion is - * possible. In this example, Comment records will be deleted when their - * associated User record has been deleted. - * - `exclusive`: When exclusive is set to true, recursive model deletion does - * the delete with a deleteAll() call, instead of deleting each entity separately. - * This greatly improves performance, but may not be ideal for all circumstances. - * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model - * records. This should be used in situations that require very custom results. - * - * @var array - * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany - */ - public $hasMany = array(); - -/** - * Detailed list of hasAndBelongsToMany associations. - * - * ### Basic usage - * - * `public $hasAndBelongsToMany = array('Role', 'Address');` - * - * ### Detailed configuration - * - * {{{ - * public $hasAndBelongsToMany = array( - * 'Role', - * 'Address' => array( - * 'className' => 'Address', - * 'foreignKey' => 'user_id', - * 'associationForeignKey' => 'address_id', - * 'joinTable' => 'addresses_users' - * ) - * ); - * }}} - * - * ### Possible keys in association - * - * - `className`: the class name of the model being associated to the current model. - * If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.' - * - `joinTable`: The name of the join table used in this association (if the - * current table doesn't adhere to the naming convention for HABTM join tables). - * - `with`: Defines the name of the model for the join table. By default CakePHP - * will auto-create a model for you. Using the example above it would be called - * RecipesTag. By using this key you can override this default name. The join - * table model can be used just like any "regular" model to access the join table directly. - * - `foreignKey`: the name of the foreign key found in the current model. - * This is especially handy if you need to define multiple HABTM relationships. - * The default value for this key is the underscored, singular name of the - * current model, suffixed with '_id'. - * - `associationForeignKey`: the name of the foreign key found in the other model. - * This is especially handy if you need to define multiple HABTM relationships. - * The default value for this key is the underscored, singular name of the other - * model, suffixed with '_id'. - * - `unique`: If true (default value) cake will first delete existing relationship - * records in the foreign keys table before inserting new ones, when updating a - * record. So existing associations need to be passed again when updating. - * To prevent deletion of existing relationship records, set this key to a string 'keepExisting'. - * - `conditions`: An SQL fragment used to filter related model records. It's good - * practice to use model names in SQL fragments: "Comment.status = 1" is always - * better than just "status = 1." - * - `fields`: A list of fields to be retrieved when the associated model data is - * fetched. Returns all fields by default. - * - `order`: An SQL fragment that defines the sorting order for the returned associated rows. - * - `limit`: The maximum number of associated rows you want returned. - * - `offset`: The number of associated rows to skip over (given the current - * conditions and order) before fetching and associating. - * - `finderQuery`, A complete SQL query CakePHP - * can use to fetch associated model records. This should - * be used in situations that require very custom results. - * - * @var array - * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm - */ - public $hasAndBelongsToMany = array(); - -/** - * List of behaviors to load when the model object is initialized. Settings can be - * passed to behaviors by using the behavior name as index. Eg: - * - * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1')) - * - * @var array - * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors - */ - public $actsAs = null; - -/** - * Holds the Behavior objects currently bound to this model. - * - * @var BehaviorCollection - */ - public $Behaviors = null; - -/** - * Whitelist of fields allowed to be saved. - * - * @var array - */ - public $whitelist = array(); - -/** - * Whether or not to cache sources for this model. - * - * @var boolean - */ - public $cacheSources = true; - -/** - * Type of find query currently executing. - * - * @var string - */ - public $findQueryType = null; - -/** - * Number of associations to recurse through during find calls. Fetches only - * the first level by default. - * - * @var integer - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive - */ - public $recursive = 1; - -/** - * The column name(s) and direction(s) to order find results by default. - * - * public $order = "Post.created DESC"; - * public $order = array("Post.view_count DESC", "Post.rating DESC"); - * - * @var string - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order - */ - public $order = null; - -/** - * Array of virtual fields this model has. Virtual fields are aliased - * SQL expressions. Fields added to this property will be read as other fields in a model - * but will not be saveable. - * - * `public $virtualFields = array('two' => '1 + 1');` - * - * Is a simplistic example of how to set virtualFields - * - * @var array - * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields - */ - public $virtualFields = array(); - -/** - * Default list of association keys. - * - * @var array - */ - protected $_associationKeys = array( - 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'), - 'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'), - 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'), - 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery') - ); - -/** - * Holds provided/generated association key names and other data for all associations. - * - * @var array - */ - protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); - -// @codingStandardsIgnoreStart - -/** - * Holds model associations temporarily to allow for dynamic (un)binding. - * - * @var array - */ - public $__backAssociation = array(); - -/** - * Back inner association - * - * @var array - */ - public $__backInnerAssociation = array(); - -/** - * Back original association - * - * @var array - */ - public $__backOriginalAssociation = array(); - -// @codingStandardsIgnoreEnd - -/** - * The ID of the model record that was last inserted. - * - * @var integer - */ - protected $_insertID = null; - -/** - * Has the datasource been configured. - * - * @var boolean - * @see Model::getDataSource - */ - protected $_sourceConfigured = false; - -/** - * List of valid finder method options, supplied as the first parameter to find(). - * - * @var array - */ - public $findMethods = array( - 'all' => true, 'first' => true, 'count' => true, - 'neighbors' => true, 'list' => true, 'threaded' => true - ); - -/** - * Instance of the Cake\Event\EventManager this model is using - * to dispatch inner events. - * - * @var Cake\Event\EventManager - */ - protected $_eventManager = null; - -/** - * Instance of the ModelValidator - * - * @var ModelValidator - */ - protected $_validator = null; - -/** - * Constructor. Binds the model's database table to the object. - * - * If `$id` is an array it can be used to pass several options into the model. - * - * - `id`: The id to start the model on. - * - `table`: The table to use for this model. - * - `ds`: The connection name this model is connected to. - * - `name`: The name of the model eg. Post. - * - `alias`: The alias of the model, this is used for registering the instance in the `ClassRegistry`. - * eg. `ParentThread` - * - * ### Overriding Model's __construct method. - * - * When overriding Model::__construct() be careful to include and pass in all 3 of the - * arguments to `parent::__construct($id, $table, $ds);` - * - * ### Dynamically creating models - * - * You can dynamically create model instances using the $id array syntax. - * - * {{{ - * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2')); - * }}} - * - * Would create a model attached to the posts table on connection2. Dynamic model creation is useful - * when you want a model object that contains no associations or attached behaviors. - * - * @param boolean|integer|string|array $id Set this ID for this model on startup, - * can also be an array of options, see above. - * @param string $table Name of database table to use. - * @param string $ds DataSource connection name. - */ - public function __construct($id = false, $table = null, $ds = null) { - parent::__construct(); - - if (is_array($id)) { - extract(array_merge( - array( - 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig, - 'name' => $this->name, 'alias' => $this->alias, 'plugin' => $this->plugin - ), - $id - )); - } - - if ($this->plugin === null) { - $this->plugin = (isset($plugin) ? $plugin : $this->plugin); - } - - if ($this->name === null) { - if (isset($name)) { - $this->name = $name; - } else { - list(, $this->name) = namespaceSplit(get_class($this)); - } - } - - if ($this->alias === null) { - $this->alias = (isset($alias) ? $alias : $this->name); - } - - if ($this->primaryKey === null) { - $this->primaryKey = 'id'; - } - - ClassRegistry::addObject($this->alias, $this); - - $this->id = $id; - unset($id); - - if ($table === false) { - $this->useTable = false; - } elseif ($table) { - $this->useTable = $table; - } - - if ($ds !== null) { - $this->useDbConfig = $ds; - } - - $this->_mergeVars( - ['actsAs', 'findMethods'], - ['associative' => ['actsAs', 'findMethods']] - ); - - $this->Behaviors = new BehaviorCollection(); - - if ($this->useTable !== false) { - - if ($this->useTable === null) { - $this->useTable = Inflector::tableize($this->name); - } - - if (!$this->displayField) { - unset($this->displayField); - } - $this->table = $this->useTable; - $this->tableToModel[$this->table] = $this->alias; - } elseif ($this->table === false) { - $this->table = Inflector::tableize($this->name); - } - - if ($this->tablePrefix === null) { - unset($this->tablePrefix); - } - - $this->_createLinks(); - $this->Behaviors->init($this->alias, $this->actsAs); - } - -/** - * Returns a list of all events that will fire in the model during it's lifecycle. - * You can override this function to add you own listener callbacks - * - * @return array - */ - public function implementedEvents() { - return array( - 'Model.beforeFind' => array('callable' => 'beforeFind', 'passParams' => true), - 'Model.afterFind' => array('callable' => 'afterFind', 'passParams' => true), - 'Model.beforeValidate' => array('callable' => 'beforeValidate', 'passParams' => true), - 'Model.afterValidate' => array('callable' => 'afterValidate'), - 'Model.beforeSave' => array('callable' => 'beforeSave', 'passParams' => true), - 'Model.afterSave' => array('callable' => 'afterSave', 'passParams' => true), - 'Model.beforeDelete' => array('callable' => 'beforeDelete', 'passParams' => true), - 'Model.afterDelete' => array('callable' => 'afterDelete'), - ); - } - -/** - * Returns the Cake\Event\EventManager manager instance that is handling any callbacks. - * You can use this instance to register any new listeners or callbacks to the - * model events, or create your own events and trigger them at will. - * - * @return Cake\Event\EventManager - */ - public function getEventManager() { - if (empty($this->_eventManager)) { - $this->_eventManager = new EventManager(); - $this->_eventManager->attach($this->Behaviors); - $this->_eventManager->attach($this); - } - - return $this->_eventManager; - } - -/** - * Handles custom method calls, like findBy for DB models, - * and custom RPC calls for remote data sources. - * - * @param string $method Name of method to call. - * @param array $params Parameters for the method. - * @return mixed Whatever is returned by called method - */ - public function __call($method, $params) { - $result = $this->Behaviors->dispatchMethod($this, $method, $params); - if ($result !== array('unhandled')) { - return $result; - } - - return $this->getDataSource()->query($method, $params, $this); - } - -/** - * Handles the lazy loading of model associations by looking in the association arrays for the requested variable - * - * @param string $name variable tested for existence in class - * @return boolean true if the variable exists (if is a not loaded model association it will be created), false otherwise - */ - public function __isset($name) { - $className = false; - - foreach ($this->_associations as $type) { - if (isset($name, $this->{$type}[$name])) { - $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className']; - break; - } elseif (isset($name, $this->__backAssociation[$type][$name])) { - $className = empty($this->__backAssociation[$type][$name]['className']) ? - $name : $this->__backAssociation[$type][$name]['className']; - break; - } elseif ($type === 'hasAndBelongsToMany') { - foreach ($this->{$type} as $k => $relation) { - if (empty($relation['with'])) { - continue; - } - - if (is_array($relation['with'])) { - if (key($relation['with']) === $name) { - $className = $name; - } - } else { - list($plugin, $class) = pluginSplit($relation['with']); - if ($class === $name) { - $className = $relation['with']; - } - } - - if ($className) { - $assocKey = $k; - $dynamic = !empty($relation['dynamicWith']); - break(2); - } - } - } - } - - if (!$className) { - return false; - } - - list($plugin, $className) = pluginSplit($className); - - if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) { - $appModelClass = App::classname('Model', 'Model'); - $this->{$className} = new $appModelClass(array( - 'name' => $className, - 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'], - 'ds' => $this->useDbConfig - )); - } else { - $this->_constructLinkedModel($name, $className, $plugin); - } - - if (!empty($assocKey)) { - $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table; - if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) { - $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey']; - } - } - - return true; - } - -/** - * Returns the value of the requested variable if it can be set by __isset() - * - * @param string $name variable requested for it's value or reference - * @return mixed value of requested variable if it is set - */ - public function __get($name) { - if ($name === 'displayField') { - return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey)); - } - - if ($name === 'tablePrefix') { - $this->setDataSource(); - if (property_exists($this, 'tablePrefix') && !empty($this->tablePrefix)) { - return $this->tablePrefix; - } - - return $this->tablePrefix = null; - } - - if (isset($this->{$name})) { - return $this->{$name}; - } - } - -/** - * Bind model associations on the fly. - * - * If `$reset` is false, association will not be reset - * to the originals defined in the model - * - * Example: Add a new hasOne binding to the Profile model not - * defined in the model source code: - * - * `$this->User->bindModel(array('hasOne' => array('Profile')));` - * - * Bindings that are not made permanent will be reset by the next Model::find() call on this - * model. - * - * @param array $params Set of bindings (indexed by binding type) - * @param boolean $reset Set to false to make the binding permanent - * @return boolean Success - * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly - */ - public function bindModel($params, $reset = true) { - foreach ($params as $assoc => $model) { - if ($reset === true && !isset($this->__backAssociation[$assoc])) { - $this->__backAssociation[$assoc] = $this->{$assoc}; - } - - foreach ($model as $key => $value) { - $assocName = $key; - - if (is_numeric($key)) { - $assocName = $value; - $value = array(); - } - - $this->{$assoc}[$assocName] = $value; - - if (property_exists($this, $assocName)) { - unset($this->{$assocName}); - } - - if ($reset === false && isset($this->__backAssociation[$assoc])) { - $this->__backAssociation[$assoc][$assocName] = $value; - } - } - } - - $this->_createLinks(); - return true; - } - -/** - * Turn off associations on the fly. - * - * If $reset is false, association will not be reset - * to the originals defined in the model - * - * Example: Turn off the associated Model Support request, - * to temporarily lighten the User model: - * - * `$this->User->unbindModel(array('hasMany' => array('SupportRequest')));` - * Or alternatively: - * `$this->User->unbindModel(array('hasMany' => 'SupportRequest'));` - * - * Unbound models that are not made permanent will reset with the next call to Model::find() - * - * @param array $params Set of bindings to unbind (indexed by binding type) - * @param boolean $reset Set to false to make the unbinding permanent - * @return boolean Success - * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly - */ - public function unbindModel($params, $reset = true) { - foreach ($params as $assoc => $models) { - if ($reset === true && !isset($this->__backAssociation[$assoc])) { - $this->__backAssociation[$assoc] = $this->{$assoc}; - } - $models = Hash::normalize((array)$models, false); - foreach ($models as $model) { - if ($reset === false && isset($this->__backAssociation[$assoc][$model])) { - unset($this->__backAssociation[$assoc][$model]); - } - - unset($this->{$assoc}[$model]); - } - } - - return true; - } - -/** - * Create a set of associations. - * - * @return void - */ - protected function _createLinks() { - foreach ($this->_associations as $type) { - $association =& $this->{$type}; - - if (!is_array($association)) { - $association = explode(',', $association); - - foreach ($association as $i => $className) { - $className = trim($className); - unset ($association[$i]); - $association[$className] = array(); - } - } - - if (!empty($association)) { - foreach ($association as $assoc => $value) { - $plugin = null; - - if (is_numeric($assoc)) { - unset($association[$assoc]); - $assoc = $value; - $value = array(); - - if (strpos($assoc, '.') !== false) { - list($plugin, $assoc) = pluginSplit($assoc, true); - $association[$assoc] = array('className' => $plugin . $assoc); - } else { - $association[$assoc] = $value; - } - } - - $this->_generateAssociation($type, $assoc); - } - } - } - } - -/** - * Protected helper method to create associated models of a given class. - * - * @param string $assoc Association name - * @param string $className Class name - * @param string $plugin name of the plugin where $className is located - * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName')); - * usage: $this->Assoc->modelMethods(); - * - * public $hasMany = array('ModelName'); - * usage: $this->ModelName->modelMethods(); - * @return void - */ - protected function _constructLinkedModel($assoc, $className = null, $plugin = null) { - if (empty($className)) { - $className = $assoc; - } - - if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) { - if ($plugin) { - $plugin .= '.'; - } - - $model = array('class' => $plugin . $className, 'alias' => $assoc); - $this->{$assoc} = ClassRegistry::init($model); - - if ($plugin) { - ClassRegistry::addObject($plugin . $className, $this->{$assoc}); - } - - if ($assoc) { - $this->tableToModel[$this->{$assoc}->table] = $assoc; - } - } - } - -/** - * Build an array-based association from string. - * - * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany' - * @param string $assocKey - * @return void - */ - protected function _generateAssociation($type, $assocKey) { - $class = $assocKey; - $dynamicWith = false; - $assoc =& $this->{$type}[$assocKey]; - - foreach ($this->_associationKeys[$type] as $key) { - if (!isset($assoc[$key]) || $assoc[$key] === null) { - $data = ''; - - switch ($key) { - case 'fields': - $data = ''; - break; - - case 'foreignKey': - $data = (($type === 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id'; - break; - - case 'associationForeignKey': - $data = Inflector::singularize($this->{$class}->table) . '_id'; - break; - - case 'with': - $data = Inflector::camelize(Inflector::singularize($assoc['joinTable'])); - $dynamicWith = true; - break; - - case 'joinTable': - $tables = array($this->table, $this->{$class}->table); - sort($tables); - $data = $tables[0] . '_' . $tables[1]; - break; - - case 'className': - $data = $class; - break; - - case 'unique': - $data = true; - break; - } - - $assoc[$key] = $data; - } - - if ($dynamicWith) { - $assoc['dynamicWith'] = true; - } - } - } - -/** - * Sets a custom table for your model class. Used by your controller to select a database table. - * - * @param string $tableName Name of the custom table - * @throws Cake\Error\MissingTableException when database table $tableName is not found on data source - * @return void - */ - public function setSource($tableName) { - $this->setDataSource($this->useDbConfig); - $db = ConnectionManager::getDataSource($this->useDbConfig); - - if (method_exists($db, 'listSources')) { - $restore = $db->cacheSources; - $db->cacheSources = ($restore && $this->cacheSources); - $sources = $db->listSources(); - $db->cacheSources = $restore; - - if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) { - throw new Error\MissingTableException(array( - 'table' => $this->tablePrefix . $tableName, - 'class' => $this->alias, - 'ds' => $this->useDbConfig, - )); - } - - $this->_schema = null; - } - - $this->table = $this->useTable = $tableName; - $this->tableToModel[$this->table] = $this->alias; - } - -/** - * This function does two things: - * - * 1. it scans the array $one for the primary key, - * and if that's found, it sets the current id to the value of $one[id]. - * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object. - * 2. Returns an array with all of $one's keys and values. - * (Alternative indata: two strings, which are mangled to - * a one-item, two-dimensional array using $one for a key and $two as its value.) - * - * @param string|array|SimpleXmlElement|DomNode $one Array or string of data - * @param string $two Value string for the alternative indata method - * @return array Data with all of $one's keys and values - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html - */ - public function set($one, $two = null) { - if (!$one) { - return; - } - - if (is_object($one)) { - if ($one instanceof \SimpleXMLElement || $one instanceof \DOMNode) { - $one = $this->_normalizeXmlData(Xml::toArray($one)); - } else { - $one = Set::reverse($one); - } - } - - if (is_array($one)) { - $data = $one; - if (empty($one[$this->alias])) { - $data = $this->_setAliasData($one); - } - } else { - $data = array($this->alias => array($one => $two)); - } - - foreach ($data as $modelName => $fieldSet) { - if (!is_array($fieldSet)) { - continue; - } - - foreach ($fieldSet as $fieldName => $fieldValue) { - unset($this->validationErrors[$fieldName]); - - if ($modelName === $this->alias && $fieldName === $this->primaryKey) { - $this->id = $fieldValue; - } - - if (is_array($fieldValue) || is_object($fieldValue)) { - $fieldValue = $this->deconstruct($fieldName, $fieldValue); - } - - $this->data[$modelName][$fieldName] = $fieldValue; - } - } - - return $data; - } - -/** - * Move values to alias - * - * @param array $data - * @return array - */ - protected function _setAliasData($data) { - $models = array_keys($this->getAssociated()); - $schema = array_keys((array)$this->schema()); - - foreach ($data as $field => $value) { - if (in_array($field, $schema) || !in_array($field, $models)) { - $data[$this->alias][$field] = $value; - unset($data[$field]); - } - } - - return $data; - } - -/** - * Normalize `Xml::toArray()` to use in `Model::save()` - * - * @param array $xml XML as array - * @return array - */ - protected function _normalizeXmlData(array $xml) { - $return = array(); - foreach ($xml as $key => $value) { - if (is_array($value)) { - $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value); - } elseif ($key[0] === '@') { - $return[substr($key, 1)] = $value; - } else { - $return[$key] = $value; - } - } - - return $return; - } - -/** - * Deconstructs a complex data type (array or object) into a single field value. - * - * @param string $field The name of the field to be deconstructed - * @param array|object $data An array or object to be deconstructed into a field - * @return mixed The resulting data that should be assigned to a field - */ - public function deconstruct($field, $data) { - if (!is_array($data)) { - return $data; - } - - $type = $this->getColumnType($field); - - if (!in_array($type, array('datetime', 'timestamp', 'date', 'time'))) { - return $data; - } - - $useNewDate = (isset($data['year']) || isset($data['month']) || - isset($data['day']) || isset($data['hour']) || isset($data['minute'])); - - $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec'); - $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec'); - $date = array(); - - if (isset($data['meridian']) && empty($data['meridian'])) { - return null; - } - - if ( - isset($data['hour']) && - isset($data['meridian']) && - !empty($data['hour']) && - $data['hour'] != 12 && - $data['meridian'] === 'pm' - ) { - $data['hour'] = $data['hour'] + 12; - } - - if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && $data['meridian'] === 'am') { - $data['hour'] = '00'; - } - - if ($type === 'time') { - foreach ($timeFields as $key => $val) { - if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { - $data[$val] = '00'; - } elseif ($data[$val] !== '') { - $data[$val] = sprintf('%02d', $data[$val]); - } - - if (!empty($data[$val])) { - $date[$key] = $data[$val]; - } else { - return null; - } - } - } - - if ($type === 'datetime' || $type === 'timestamp' || $type === 'date') { - foreach ($dateFields as $key => $val) { - if ($val === 'hour' || $val === 'min' || $val === 'sec') { - if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { - $data[$val] = '00'; - } else { - $data[$val] = sprintf('%02d', $data[$val]); - } - } - - if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) { - return null; - } - - if (isset($data[$val]) && !empty($data[$val])) { - $date[$key] = $data[$val]; - } - } - } - - if ($useNewDate && !empty($date)) { - $format = $this->getDataSource()->columns[$type]['format']; - foreach (array('m', 'd', 'H', 'i', 's') as $index) { - if (isset($date[$index])) { - $date[$index] = sprintf('%02d', $date[$index]); - } - } - - return str_replace(array_keys($date), array_values($date), $format); - } - - return $data; - } - -/** - * Returns an array of table metadata (column names and types) from the database. - * $field => keys(type, null, default, key, length, extra) - * - * @param boolean|string $field Set to true to reload schema, or a string to return a specific field - * @return array Array of table metadata - */ - public function schema($field = false) { - if ($this->useTable !== false && (!is_array($this->_schema) || $field === true)) { - $db = $this->getDataSource(); - $db->cacheSources = ($this->cacheSources && $db->cacheSources); - if (method_exists($db, 'describe')) { - $this->_schema = $db->describe($this); - } - } - - if (!is_string($field)) { - return $this->_schema; - } - - if (isset($this->_schema[$field])) { - return $this->_schema[$field]; - } - - return null; - } - -/** - * Returns an associative array of field names and column types. - * - * @return array Field types indexed by field name - */ - public function getColumnTypes() { - $columns = $this->schema(); - if (empty($columns)) { - trigger_error(__d('cake_dev', '(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()'), E_USER_WARNING); - } - - $cols = array(); - foreach ($columns as $field => $values) { - $cols[$field] = $values['type']; - } - - return $cols; - } - -/** - * Returns the column type of a column in the model. - * - * @param string $column The name of the model column - * @return string Column type - */ - public function getColumnType($column) { - $db = $this->getDataSource(); - $cols = $this->schema(); - $model = null; - - $startQuote = isset($db->startQuote) ? $db->startQuote : null; - $endQuote = isset($db->endQuote) ? $db->endQuote : null; - $column = str_replace(array($startQuote, $endQuote), '', $column); - - if (strpos($column, '.')) { - list($model, $column) = explode('.', $column); - } - - if ($model != $this->alias && isset($this->{$model})) { - return $this->{$model}->getColumnType($column); - } - - if (isset($cols[$column]) && isset($cols[$column]['type'])) { - return $cols[$column]['type']; - } - - return null; - } - -/** - * Returns true if the supplied field exists in the model's database table. - * - * @param string|array $name Name of field to look for, or an array of names - * @param boolean $checkVirtual checks if the field is declared as virtual - * @return mixed If $name is a string, returns a boolean indicating whether the field exists. - * If $name is an array of field names, returns the first field that exists, - * or false if none exist. - */ - public function hasField($name, $checkVirtual = false) { - if (is_array($name)) { - foreach ($name as $n) { - if ($this->hasField($n, $checkVirtual)) { - return $n; - } - } - - return false; - } - - if ($checkVirtual && !empty($this->virtualFields) && $this->isVirtualField($name)) { - return true; - } - - if (empty($this->_schema)) { - $this->schema(); - } - - if ($this->_schema) { - return isset($this->_schema[$name]); - } - - return false; - } - -/** - * Check that a method is callable on a model. This will check both the model's own methods, its - * inherited methods and methods that could be callable through behaviors. - * - * @param string $method The method to be called. - * @return boolean True on method being callable. - */ - public function hasMethod($method) { - if (method_exists($this, $method)) { - return true; - } - - return $this->Behaviors->hasMethod($method); - } - -/** - * Returns true if the supplied field is a model Virtual Field - * - * @param string $field Name of field to look for - * @return boolean indicating whether the field exists as a model virtual field. - */ - public function isVirtualField($field) { - if (empty($this->virtualFields) || !is_string($field)) { - return false; - } - - if (isset($this->virtualFields[$field])) { - return true; - } - - if (strpos($field, '.') !== false) { - list($model, $field) = explode('.', $field); - if ($model == $this->alias && isset($this->virtualFields[$field])) { - return true; - } - } - - return false; - } - -/** - * Returns the expression for a model virtual field - * - * @param string $field Name of field to look for - * @return mixed If $field is string expression bound to virtual field $field - * If $field is null, returns an array of all model virtual fields - * or false if none $field exist. - */ - public function getVirtualField($field = null) { - if (!$field) { - return empty($this->virtualFields) ? false : $this->virtualFields; - } - - if ($this->isVirtualField($field)) { - if (strpos($field, '.') !== false) { - list(, $field) = pluginSplit($field); - } - - return $this->virtualFields[$field]; - } - - return false; - } - -/** - * Initializes the model for writing a new record, loading the default values - * for those fields that are not defined in $data, and clearing previous validation errors. - * Especially helpful for saving data in loops. - * - * @param boolean|array $data Optional data array to assign to the model after it is created. If null or false, - * schema data defaults are not merged. - * @param boolean $filterKey If true, overwrites any primary key input with an empty value - * @return array The current Model::data; after merging $data and/or defaults from database - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array - */ - public function create($data = array(), $filterKey = false) { - $defaults = array(); - $this->id = false; - $this->data = array(); - $this->validationErrors = array(); - - if ($data !== null && $data !== false) { - $schema = (array)$this->schema(); - foreach ($schema as $field => $properties) { - if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') { - $defaults[$field] = $properties['default']; - } - } - - $this->set($defaults); - $this->set($data); - } - - if ($filterKey) { - $this->set($this->primaryKey, false); - } - - return $this->data; - } - -/** - * This function is a convenient wrapper class to create(false) and, as the name suggests, clears the id, data, and validation errors. - * - * @return boolean Always true upon success - * @see Model::create() - */ - public function clear() { - $this->create(false); - return true; - } - -/** - * Returns a list of fields from the database, and sets the current model - * data (Model::$data) with the record found. - * - * @param string|array $fields String of single field name, or an array of field names. - * @param integer|string $id The ID of the record to read - * @return array Array of database fields, or false if not found - * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read - */ - public function read($fields = null, $id = null) { - $this->validationErrors = array(); - - if ($id) { - $this->id = $id; - } - - $id = $this->id; - - if (is_array($this->id)) { - $id = $this->id[0]; - } - - if ($id !== null && $id !== false) { - $this->data = $this->find('first', array( - 'conditions' => array($this->alias . '.' . $this->primaryKey => $id), - 'fields' => $fields - )); - - return $this->data; - } - - return false; - } - -/** - * Returns the contents of a single field given the supplied conditions, in the - * supplied order. - * - * @param string $name Name of field to get - * @param array $conditions SQL conditions (defaults to NULL) - * @param string $order SQL ORDER BY fragment - * @return string field contents, or false if not found - * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field - */ - public function field($name, $conditions = null, $order = null) { - if ($conditions === null && $this->id !== false) { - $conditions = array($this->alias . '.' . $this->primaryKey => $this->id); - } - - $recursive = $this->recursive; - if ($this->recursive >= 1) { - $recursive = -1; - } - - $fields = $name; - $data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive')); - if (!$data) { - return false; - } - - if (strpos($name, '.') === false) { - if (isset($data[$this->alias][$name])) { - return $data[$this->alias][$name]; - } - } else { - $name = explode('.', $name); - if (isset($data[$name[0]][$name[1]])) { - return $data[$name[0]][$name[1]]; - } - } - - if (isset($data[0]) && count($data[0]) > 0) { - return array_shift($data[0]); - } - } - -/** - * Saves the value of a single field to the database, based on the current - * model ID. - * - * @param string $name Name of the table field - * @param mixed $value Value of the field - * @param boolean|array $validate Either a boolean, or an array. - * If a boolean, indicates whether or not to validate before saving. - * If an array, allows control of 'validate', 'callbacks' and 'counterCache' options. - * See Model::save() for details of each options. - * @return boolean See Model::save() - * @see Model::save() - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false - */ - public function saveField($name, $value, $validate = false) { - $id = $this->id; - $this->create(false); - - $options = array('validate' => $validate, 'fieldList' => array($name)); - if (is_array($validate)) { - $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate); - } - - return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options); - } - -/** - * Saves model data (based on white-list, if supplied) to the database. By - * default, validation occurs before save. - * - * @param array $data Data to save. - * @param boolean|array $validate Either a boolean, or an array. - * If a boolean, indicates whether or not to validate before saving. - * If an array, can have following keys: - * - * - validate: Set to true/false to enable or disable validation. - * - fieldList: An array of fields you want to allow for saving. - * - callbacks: Set to false to disable callbacks. Using 'before' or 'after' - * will enable only those callbacks. - * - `counterCache`: Boolean to control updating of counter caches (if any) - * - * @param array $fieldList List of fields to allow to be saved - * @return mixed On success Model::$data if its not empty or true, false on failure - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html - */ - public function save($data = null, $validate = true, $fieldList = array()) { - $defaults = array( - 'validate' => true, 'fieldList' => array(), - 'callbacks' => true, 'counterCache' => true - ); - $_whitelist = $this->whitelist; - $fields = array(); - - if (!is_array($validate)) { - $options = array_merge($defaults, compact('validate', 'fieldList')); - } else { - $options = array_merge($defaults, $validate); - } - - if (!empty($options['fieldList'])) { - if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) { - $this->whitelist = $options['fieldList'][$this->alias]; - } elseif (Hash::dimensions($options['fieldList']) < 2) { - $this->whitelist = $options['fieldList']; - } - } elseif ($options['fieldList'] === null) { - $this->whitelist = array(); - } - - $this->set($data); - - if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) { - $this->whitelist = $_whitelist; - return false; - } - - foreach (array('created', 'updated', 'modified') as $field) { - $keyPresentAndEmpty = ( - isset($this->data[$this->alias]) && - array_key_exists($field, $this->data[$this->alias]) && - $this->data[$this->alias][$field] === null - ); - - if ($keyPresentAndEmpty) { - unset($this->data[$this->alias][$field]); - } - } - - $exists = $this->exists(); - $dateFields = array('modified', 'updated'); - - if (!$exists) { - $dateFields[] = 'created'; - } - - if (isset($this->data[$this->alias])) { - $fields = array_keys($this->data[$this->alias]); - } - - if ($options['validate'] && !$this->validates($options)) { - $this->whitelist = $_whitelist; - return false; - } - - $db = $this->getDataSource(); - $now = time(); - - foreach ($dateFields as $updateCol) { - if (in_array($updateCol, $fields) || !$this->hasField($updateCol)) { - continue; - } - - $default = array('formatter' => 'date'); - $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]); - - $time = $now; - if (array_key_exists('format', $colType)) { - $time = call_user_func($colType['formatter'], $colType['format']); - } - - if (!empty($this->whitelist)) { - $this->whitelist[] = $updateCol; - } - $this->set($updateCol, $time); - } - - if ($options['callbacks'] === true || $options['callbacks'] === 'before') { - $event = new Event('Model.beforeSave', $this, array($options)); - list($event->break, $event->breakOn) = array(true, array(false, null)); - $this->getEventManager()->dispatch($event); - if (!$event->result) { - $this->whitelist = $_whitelist; - return false; - } - } - - $db = $this->getDataSource(); - - if (empty($this->data[$this->alias][$this->primaryKey])) { - unset($this->data[$this->alias][$this->primaryKey]); - } - $fields = $values = array(); - - foreach ($this->data as $n => $v) { - if (isset($this->hasAndBelongsToMany[$n])) { - if (isset($v[$n])) { - $v = $v[$n]; - } - $joined[$n] = $v; - } elseif ($n === $this->alias) { - foreach (array('created', 'updated', 'modified') as $field) { - if (array_key_exists($field, $v) && empty($v[$field])) { - unset($v[$field]); - } - } - - foreach ($v as $x => $y) { - if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) { - list($fields[], $values[]) = array($x, $y); - } - } - } - } - - $count = count($fields); - - if (!$exists && $count > 0) { - $this->id = false; - } - - $success = true; - $created = false; - - if ($count > 0) { - $cache = $this->_prepareUpdateFields(array_combine($fields, $values)); - - if (!empty($this->id)) { - $success = (bool)$db->update($this, $fields, $values); - } else { - if (empty($this->data[$this->alias][$this->primaryKey]) && $this->_isUUIDField($this->primaryKey)) { - if (array_key_exists($this->primaryKey, $this->data[$this->alias])) { - $j = array_search($this->primaryKey, $fields); - $values[$j] = String::uuid(); - } else { - list($fields[], $values[]) = array($this->primaryKey, String::uuid()); - } - } - - if (!$db->create($this, $fields, $values)) { - $success = false; - } else { - $created = true; - } - } - - if ($success && $options['counterCache'] && !empty($this->belongsTo)) { - $this->updateCounterCache($cache, $created); - } - } - - if (!empty($joined) && $success === true) { - $this->_saveMulti($joined, $this->id, $db); - } - - if ($success && $count === 0) { - $success = false; - } - - if ($success && $count > 0) { - if (!empty($this->data)) { - if ($created) { - $this->data[$this->alias][$this->primaryKey] = $this->id; - } - } - - if ($options['callbacks'] === true || $options['callbacks'] === 'after') { - $event = new Event('Model.afterSave', $this, array($created, $options)); - $this->getEventManager()->dispatch($event); - } - - if (!empty($this->data)) { - $success = $this->data; - } - - $this->data = false; - $this->_clearCache(); - $this->validationErrors = array(); - } - - $this->whitelist = $_whitelist; - return $success; - } - -/** - * Check if the passed in field is a UUID field - * - * @param string $field the field to check - * @return boolean - */ - protected function _isUUIDField($field) { - $field = $this->schema($field); - return $field['length'] == 36 && in_array($field['type'], array('string', 'binary')); - } - -/** - * Saves model hasAndBelongsToMany data to the database. - * - * @param array $joined Data to save - * @param integer|string $id ID of record in this model - * @param DataSource $db - * @return void - */ - protected function _saveMulti($joined, $id, $db) { - foreach ($joined as $assoc => $data) { - if (!isset($this->hasAndBelongsToMany[$assoc])) { - continue; - } - - $habtm = $this->hasAndBelongsToMany[$assoc]; - - list($join) = $this->joinModel($habtm['with']); - - $Model = $this->{$join}; - - if (!empty($habtm['with'])) { - $withModel = is_array($habtm['with']) ? key($habtm['with']) : $habtm['with']; - list(, $withModel) = pluginSplit($withModel); - $dbMulti = $this->{$withModel}->getDataSource(); - } else { - $dbMulti = $db; - } - - $isUUID = !empty($Model->primaryKey) && $Model->_isUUIDField($Model->primaryKey); - - $newData = $newValues = $newJoins = array(); - $primaryAdded = false; - - $fields = array( - $dbMulti->name($habtm['foreignKey']), - $dbMulti->name($habtm['associationForeignKey']) - ); - - $idField = $db->name($Model->primaryKey); - if ($isUUID && !in_array($idField, $fields)) { - $fields[] = $idField; - $primaryAdded = true; - } - - foreach ((array)$data as $row) { - if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) { - $newJoins[] = $row; - $values = array($id, $row); - - if ($isUUID && $primaryAdded) { - $values[] = String::uuid(); - } - - $newValues[$row] = $values; - unset($values); - } elseif (isset($row[$habtm['associationForeignKey']])) { - if (!empty($row[$Model->primaryKey])) { - $newJoins[] = $row[$habtm['associationForeignKey']]; - } - - $newData[] = $row; - } elseif (isset($row[$join]) && isset($row[$join][$habtm['associationForeignKey']])) { - if (!empty($row[$join][$Model->primaryKey])) { - $newJoins[] = $row[$join][$habtm['associationForeignKey']]; - } - - $newData[] = $row[$join]; - } - } - - $keepExisting = $habtm['unique'] === 'keepExisting'; - if ($habtm['unique']) { - $conditions = array( - $join . '.' . $habtm['foreignKey'] => $id - ); - - if (!empty($habtm['conditions'])) { - $conditions = array_merge($conditions, (array)$habtm['conditions']); - } - - $associationForeignKey = $Model->alias . '.' . $habtm['associationForeignKey']; - $links = $Model->find('all', array( - 'conditions' => $conditions, - 'recursive' => empty($habtm['conditions']) ? -1 : 0, - 'fields' => $associationForeignKey, - )); - - $oldLinks = Hash::extract($links, "{n}.{$associationForeignKey}"); - if (!empty($oldLinks)) { - if ($keepExisting && !empty($newJoins)) { - $conditions[$associationForeignKey] = array_diff($oldLinks, $newJoins); - } else { - $conditions[$associationForeignKey] = $oldLinks; - } - - $dbMulti->delete($Model, $conditions); - } - } - - if (!empty($newData)) { - foreach ($newData as $data) { - $data[$habtm['foreignKey']] = $id; - if (empty($data[$Model->primaryKey])) { - $Model->create(); - } - - $Model->save($data); - } - } - - if (!empty($newValues)) { - if ($keepExisting && !empty($links)) { - foreach ($links as $link) { - $oldJoin = $link[$join][$habtm['associationForeignKey']]; - if (!in_array($oldJoin, $newJoins)) { - $conditions[$associationForeignKey] = $oldJoin; - $db->delete($Model, $conditions); - } else { - unset($newValues[$oldJoin]); - } - } - - $newValues = array_values($newValues); - } - - if (!empty($newValues)) { - $dbMulti->insertMulti($Model, $fields, $newValues); - } - } - } - } - -/** - * Updates the counter cache of belongsTo associations after a save or delete operation - * - * @param array $keys Optional foreign key data, defaults to the information $this->data - * @param boolean $created True if a new record was created, otherwise only associations with - * 'counterScope' defined get updated - * @return void - */ - public function updateCounterCache($keys = array(), $created = false) { - $keys = empty($keys) ? $this->data[$this->alias] : $keys; - $keys['old'] = isset($keys['old']) ? $keys['old'] : array(); - - foreach ($this->belongsTo as $parent => $assoc) { - if (empty($assoc['counterCache'])) { - continue; - } - - $Model = $this->{$parent}; - - if (!is_array($assoc['counterCache'])) { - if (isset($assoc['counterScope'])) { - $assoc['counterCache'] = array($assoc['counterCache'] => $assoc['counterScope']); - } else { - $assoc['counterCache'] = array($assoc['counterCache'] => array()); - } - } - - $foreignKey = $assoc['foreignKey']; - $fkQuoted = $this->escapeField($assoc['foreignKey']); - - foreach ($assoc['counterCache'] as $field => $conditions) { - if (!is_string($field)) { - $field = Inflector::underscore($this->alias) . '_count'; - } - - if (!$Model->hasField($field)) { - continue; - } - - if ($conditions === true) { - $conditions = array(); - } else { - $conditions = (array)$conditions; - } - - if (!array_key_exists($foreignKey, $keys)) { - $keys[$foreignKey] = $this->field($foreignKey); - } - - $recursive = (empty($conditions) ? -1 : 0); - - if (isset($keys['old'][$foreignKey]) && $keys['old'][$foreignKey] != $keys[$foreignKey]) { - $conditions[$fkQuoted] = $keys['old'][$foreignKey]; - $count = intval($this->find('count', compact('conditions', 'recursive'))); - - $Model->updateAll( - array($field => $count), - array($Model->escapeField() => $keys['old'][$foreignKey]) - ); - } - - $conditions[$fkQuoted] = $keys[$foreignKey]; - - if ($recursive === 0) { - $conditions = array_merge($conditions, (array)$conditions); - } - - $count = intval($this->find('count', compact('conditions', 'recursive'))); - - $Model->updateAll( - array($field => $count), - array($Model->escapeField() => $keys[$foreignKey]) - ); - } - } - } - -/** - * Helper method for `Model::updateCounterCache()`. Checks the fields to be updated for - * - * @param array $data The fields of the record that will be updated - * @return array Returns updated foreign key values, along with an 'old' key containing the old - * values, or empty if no foreign keys are updated. - */ - protected function _prepareUpdateFields($data) { - $foreignKeys = array(); - foreach ($this->belongsTo as $assoc => $info) { - if ($info['counterCache']) { - $foreignKeys[$assoc] = $info['foreignKey']; - } - } - - $included = array_intersect($foreignKeys, array_keys($data)); - - if (empty($included) || empty($this->id)) { - return array(); - } - - $old = $this->find('first', array( - 'conditions' => array($this->alias . '.' . $this->primaryKey => $this->id), - 'fields' => array_values($included), - 'recursive' => -1 - )); - - return array_merge($data, array('old' => $old[$this->alias])); - } - -/** - * Backwards compatible passthrough method for: - * saveMany(), validateMany(), saveAssociated() and validateAssociated() - * - * Saves multiple individual records for a single model; Also works with a single record, as well as - * all its associated records. - * - * #### Options - * - * - `validate`: Set to false to disable validation, true to validate each record before saving, - * 'first' to validate *all* records before any are saved (default), - * or 'only' to only validate the records, but not save them. - * - `atomic`: If true (default), will attempt to save all records in a single transaction. - * Should be set to false if database/table does not support transactions. - * - `fieldList`: Equivalent to the $fieldList parameter in Model::save(). - * It should be an associate array with model name as key and array of fields as value. Eg. - * {{{ - * array( - * 'SomeModel' => array('field'), - * 'AssociatedModel' => array('field', 'otherfield') - * ) - * }}} - * - `deep`: See saveMany/saveAssociated - * - `callbacks`: See Model::save() - * - `counterCache`: See Model::save() - * - * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple - * records of the same type), or an array indexed by association name. - * @param array $options Options to use when saving record data, See $options above. - * @return mixed If atomic: True on success, or false on failure. - * Otherwise: array similar to the $data array passed, but values are set to true/false - * depending on whether each record saved successfully. - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array - */ - public function saveAll($data = array(), $options = array()) { - $options = array_merge(array('validate' => 'first'), $options); - if (Hash::numeric(array_keys($data))) { - if ($options['validate'] === 'only') { - return $this->validateMany($data, $options); - } - - return $this->saveMany($data, $options); - } - - if ($options['validate'] === 'only') { - return $this->validateAssociated($data, $options); - } - - return $this->saveAssociated($data, $options); - } - -/** - * Saves multiple individual records for a single model - * - * #### Options - * - * - `validate`: Set to false to disable validation, true to validate each record before saving, - * 'first' to validate *all* records before any are saved (default), - * - `atomic`: If true (default), will attempt to save all records in a single transaction. - * Should be set to false if database/table does not support transactions. - * - `fieldList`: Equivalent to the $fieldList parameter in Model::save() - * - `deep`: If set to true, all associated data will be saved as well. - * - `callbacks`: See Model::save() - * - `counterCache`: See Model::save() - * - * @param array $data Record data to save. This should be a numerically-indexed array - * @param array $options Options to use when saving record data, See $options above. - * @return mixed If atomic: True on success, or false on failure. - * Otherwise: array similar to the $data array passed, but values are set to true/false - * depending on whether each record saved successfully. - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array - */ - public function saveMany($data = null, $options = array()) { - if (empty($data)) { - $data = $this->data; - } - - $options = array_merge(array('validate' => 'first', 'atomic' => true, 'deep' => false), $options); - $this->validationErrors = $validationErrors = array(); - - if (empty($data) && $options['validate'] !== false) { - $result = $this->save($data, $options); - if (!$options['atomic']) { - return array(!empty($result)); - } - - return !empty($result); - } - - if ($options['validate'] === 'first') { - $validates = $this->validateMany($data, $options); - if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) { - return $validates; - } - $options['validate'] = false; - } - - if ($options['atomic']) { - $db = $this->getDataSource(); - $transactionBegun = $db->begin(); - } - - $return = array(); - foreach ($data as $key => $record) { - $validates = $this->create(null) !== null; - $saved = false; - if ($validates) { - if ($options['deep']) { - $saved = $this->saveAssociated($record, array_merge($options, array('atomic' => false))); - } else { - $saved = $this->save($record, $options); - } - } - - $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, $saved, true)))); - if (!$validates) { - $validationErrors[$key] = $this->validationErrors; - } - - if (!$options['atomic']) { - $return[$key] = $validates; - } elseif (!$validates) { - break; - } - } - - $this->validationErrors = $validationErrors; - - if (!$options['atomic']) { - return $return; - } - - if ($validates) { - if ($transactionBegun) { - return $db->commit() !== false; - } - return true; - } - - $db->rollback(); - return false; - } - -/** - * Validates multiple individual records for a single model - * - * #### Options - * - * - `atomic`: If true (default), returns boolean. If false returns array. - * - `fieldList`: Equivalent to the $fieldList parameter in Model::save() - * - `deep`: If set to true, all associated data will be validated as well. - * - * Warning: This method could potentially change the passed argument `$data`, - * If you do not want this to happen, make a copy of `$data` before passing it - * to this method - * - * @param array $data Record data to validate. This should be a numerically-indexed array - * @param array $options Options to use when validating record data (see above), See also $options of validates(). - * @return boolean|array If atomic: True on success, or false on failure. - * Otherwise: array similar to the $data array passed, but values are set to true/false - * depending on whether each record validated successfully. - */ - public function validateMany(&$data, $options = array()) { - return $this->validator()->validateMany($data, $options); - } - -/** - * Saves a single record, as well as all its directly associated records. - * - * #### Options - * - * - `validate`: Set to `false` to disable validation, `true` to validate each record before saving, - * 'first' to validate *all* records before any are saved(default), - * - `atomic`: If true (default), will attempt to save all records in a single transaction. - * Should be set to false if database/table does not support transactions. - * - `fieldList`: Equivalent to the $fieldList parameter in Model::save(). - * It should be an associate array with model name as key and array of fields as value. Eg. - * {{{ - * array( - * 'SomeModel' => array('field'), - * 'AssociatedModel' => array('field', 'otherfield') - * ) - * }}} - * - `deep`: If set to true, not only directly associated data is saved, but deeper nested associated data as well. - * - `callbacks`: See Model::save() - * - `counterCache`: See Model::save() - * - * @param array $data Record data to save. This should be an array indexed by association name. - * @param array $options Options to use when saving record data, See $options above. - * @return mixed If atomic: True on success, or false on failure. - * Otherwise: array similar to the $data array passed, but values are set to true/false - * depending on whether each record saved successfully. - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array - */ - public function saveAssociated($data = null, $options = array()) { - if (empty($data)) { - $data = $this->data; - } - - $options = array_merge(array('validate' => 'first', 'atomic' => true, 'deep' => false), $options); - $this->validationErrors = $validationErrors = array(); - - if (empty($data) && $options['validate'] !== false) { - $result = $this->save($data, $options); - if (!$options['atomic']) { - return array(!empty($result)); - } - - return !empty($result); - } - - if ($options['validate'] === 'first') { - $validates = $this->validateAssociated($data, $options); - if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, Hash::flatten($validates), true))) { - return $validates; - } - - $options['validate'] = false; - } - - if ($options['atomic']) { - $db = $this->getDataSource(); - $transactionBegun = $db->begin(); - } - - $associations = $this->getAssociated(); - $return = array(); - $validates = true; - foreach ($data as $association => $values) { - $isEmpty = empty($values) || (isset($values[$association]) && empty($values[$association])); - if ($isEmpty || !isset($associations[$association]) || $associations[$association] !== 'belongsTo') { - continue; - } - - $Model = $this->{$association}; - - $validates = $Model->create(null) !== null; - $saved = false; - if ($validates) { - if ($options['deep']) { - $saved = $Model->saveAssociated($values, array_merge($options, array('atomic' => false))); - } else { - $saved = $Model->save($values, array_merge($options, array('atomic' => false))); - } - $validates = ($saved === true || (is_array($saved) && !in_array(false, $saved, true))); - } - - if ($validates) { - $key = $this->belongsTo[$association]['foreignKey']; - if (isset($data[$this->alias])) { - $data[$this->alias][$key] = $Model->id; - } else { - $data = array_merge(array($key => $Model->id), $data, array($key => $Model->id)); - } - $options = $this->_addToWhiteList($key, $options); - } else { - $validationErrors[$association] = $Model->validationErrors; - } - - $return[$association] = $validates; - } - - if ($validates && !($this->create(null) !== null && $this->save($data, $options))) { - $validationErrors[$this->alias] = $this->validationErrors; - $validates = false; - } - $return[$this->alias] = $validates; - - foreach ($data as $association => $values) { - if (!$validates) { - break; - } - - $isEmpty = empty($values) || (isset($values[$association]) && empty($values[$association])); - if ($isEmpty || !isset($associations[$association])) { - continue; - } - - $Model = $this->{$association}; - - $type = $associations[$association]; - $key = $this->{$type}[$association]['foreignKey']; - switch ($type) { - case 'hasOne': - if (isset($values[$association])) { - $values[$association][$key] = $this->id; - } else { - $values = array_merge(array($key => $this->id), $values, array($key => $this->id)); - } - - $validates = $Model->create(null) !== null; - $saved = false; - - if ($validates) { - $options = $Model->_addToWhiteList($key, $options); - if ($options['deep']) { - $saved = $Model->saveAssociated($values, array_merge($options, array('atomic' => false))); - } else { - $saved = $Model->save($values, $options); - } - } - - $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, $saved, true)))); - if (!$validates) { - $validationErrors[$association] = $Model->validationErrors; - } - - $return[$association] = $validates; - break; - case 'hasMany': - foreach ($values as $i => $value) { - if (isset($values[$i][$association])) { - $values[$i][$association][$key] = $this->id; - } else { - $values[$i] = array_merge(array($key => $this->id), $value, array($key => $this->id)); - } - } - - $options = $Model->_addToWhiteList($key, $options); - $_return = $Model->saveMany($values, array_merge($options, array('atomic' => false))); - if (in_array(false, $_return, true)) { - $validationErrors[$association] = $Model->validationErrors; - $validates = false; - } - - $return[$association] = $_return; - break; - } - } - $this->validationErrors = $validationErrors; - - if (isset($validationErrors[$this->alias])) { - $this->validationErrors = $validationErrors[$this->alias]; - unset($validationErrors[$this->alias]); - $this->validationErrors = array_merge($this->validationErrors, $validationErrors); - } - - if (!$options['atomic']) { - return $return; - } - if ($validates) { - if ($transactionBegun) { - return $db->commit() !== false; - } - - return true; - } - - $db->rollback(); - return false; - } - -/** - * Helper method for saveAll() and friends, to add foreign key to fieldlist - * - * @param string $key fieldname to be added to list - * @param array $options - * @return array $options - */ - protected function _addToWhiteList($key, $options) { - if (empty($options['fieldList']) && $this->whitelist && !in_array($key, $this->whitelist)) { - $options['fieldList'][$this->alias] = $this->whitelist; - $options['fieldList'][$this->alias][] = $key; - return $options; - } - - if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) { - $options['fieldList'][$this->alias][] = $key; - return $options; - } - - if (!empty($options['fieldList']) && is_array($options['fieldList']) && Hash::dimensions($options['fieldList']) < 2) { - $options['fieldList'][] = $key; - } - - return $options; - } - -/** - * Validates a single record, as well as all its directly associated records. - * - * #### Options - * - * - `atomic`: If true (default), returns boolean. If false returns array. - * - `fieldList`: Equivalent to the $fieldList parameter in Model::save() - * - `deep`: If set to true, not only directly associated data , but deeper nested associated data is validated as well. - * - * Warning: This method could potentially change the passed argument `$data`, - * If you do not want this to happen, make a copy of `$data` before passing it - * to this method - * - * @param array $data Record data to validate. This should be an array indexed by association name. - * @param array $options Options to use when validating record data (see above), See also $options of validates(). - * @return array|boolean If atomic: True on success, or false on failure. - * Otherwise: array similar to the $data array passed, but values are set to true/false - * depending on whether each record validated successfully. - */ - public function validateAssociated(&$data, $options = array()) { - return $this->validator()->validateAssociated($data, $options); - } - -/** - * Updates multiple model records based on a set of conditions. - * - * @param array $fields Set of fields and values, indexed by fields. - * Fields are treated as SQL snippets, to insert literal values manually escape your data. - * @param mixed $conditions Conditions to match, true for all records - * @return boolean True on success, false on failure - * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions - */ - public function updateAll($fields, $conditions = true) { - return $this->getDataSource()->update($this, $fields, null, $conditions); - } - -/** - * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success. - * - * @param integer|string $id ID of record to delete - * @param boolean $cascade Set to true to delete records that depend on this record - * @return boolean True on success - * @link http://book.cakephp.org/2.0/en/models/deleting-data.html - */ - public function delete($id = null, $cascade = true) { - if (!empty($id)) { - $this->id = $id; - } - - $id = $this->id; - - $event = new Event('Model.beforeDelete', $this, array($cascade)); - list($event->break, $event->breakOn) = array(true, array(false, null)); - $this->getEventManager()->dispatch($event); - if ($event->isStopped()) { - return false; - } - - if (!$this->exists()) { - return false; - } - - $this->_deleteDependent($id, $cascade); - $this->_deleteLinks($id); - $this->id = $id; - - if (!empty($this->belongsTo)) { - foreach ($this->belongsTo as $assoc) { - if (empty($assoc['counterCache'])) { - continue; - } - $keys = $this->find('first', array( - 'fields' => $this->_collectForeignKeys(), - 'conditions' => array($this->alias . '.' . $this->primaryKey => $id), - 'recursive' => -1, - 'callbacks' => false - )); - break; - } - } - - if (!$this->getDataSource()->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) { - return false; - } - - if (!empty($keys[$this->alias])) { - $this->updateCounterCache($keys[$this->alias]); - } - - $this->getEventManager()->dispatch(new Event('Model.afterDelete', $this)); - $this->_clearCache(); - $this->id = false; - - return true; - } - -/** - * Cascades model deletes through associated hasMany and hasOne child records. - * - * @param string $id ID of record that was deleted - * @param boolean $cascade Set to true to delete records that depend on this record - * @return void - */ - protected function _deleteDependent($id, $cascade) { - if ($cascade !== true) { - return; - } - - if (!empty($this->__backAssociation)) { - $savedAssociations = $this->__backAssociation; - $this->__backAssociation = array(); - } - - foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) { - if ($data['dependent'] !== true) { - continue; - } - - $Model = $this->{$assoc}; - - if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $Model->getAssociated('belongsTo'))) { - $Model->recursive = 0; - $conditions = array($this->escapeField(null, $this->name) => $id); - } else { - $Model->recursive = -1; - $conditions = array($Model->escapeField($data['foreignKey']) => $id); - if ($data['conditions']) { - $conditions = array_merge((array)$data['conditions'], $conditions); - } - } - - if (isset($data['exclusive']) && $data['exclusive']) { - $Model->deleteAll($conditions); - } else { - $records = $Model->find('all', array( - 'conditions' => $conditions, 'fields' => $Model->primaryKey - )); - - if (!empty($records)) { - foreach ($records as $record) { - $Model->delete($record[$Model->alias][$Model->primaryKey]); - } - } - } - } - - if (isset($savedAssociations)) { - $this->__backAssociation = $savedAssociations; - } - } - -/** - * Cascades model deletes through HABTM join keys. - * - * @param string $id ID of record that was deleted - * @return void - */ - protected function _deleteLinks($id) { - foreach ($this->hasAndBelongsToMany as $data) { - list(, $joinModel) = pluginSplit($data['with']); - $Model = $this->{$joinModel}; - $records = $Model->find('all', array( - 'conditions' => array($Model->escapeField($data['foreignKey']) => $id), - 'fields' => $Model->primaryKey, - 'recursive' => -1, - 'callbacks' => false - )); - - if (!empty($records)) { - foreach ($records as $record) { - $Model->delete($record[$Model->alias][$Model->primaryKey]); - } - } - } - } - -/** - * Deletes multiple model records based on a set of conditions. - * - * @param mixed $conditions Conditions to match - * @param boolean $cascade Set to true to delete records that depend on this record - * @param boolean $callbacks Run callbacks - * @return boolean True on success, false on failure - * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall - */ - public function deleteAll($conditions, $cascade = true, $callbacks = false) { - if (empty($conditions)) { - return false; - } - - $db = $this->getDataSource(); - - if (!$cascade && !$callbacks) { - return $db->delete($this, $conditions); - } - - $ids = $this->find('all', array_merge(array( - 'fields' => "DISTINCT {$this->alias}.{$this->primaryKey}", - 'order' => false, - 'recursive' => 0), compact('conditions')) - ); - - if ($ids === false || $ids === null) { - return false; - } - - $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}"); - if (empty($ids)) { - return true; - } - - if ($callbacks) { - $_id = $this->id; - $result = true; - foreach ($ids as $id) { - $result = $result && $this->delete($id, $cascade); - } - - $this->id = $_id; - return $result; - } - - foreach ($ids as $id) { - $this->_deleteLinks($id); - if ($cascade) { - $this->_deleteDependent($id, $cascade); - } - } - - return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids)); - } - -/** - * Collects foreign keys from associations. - * - * @param string $type - * @return array - */ - protected function _collectForeignKeys($type = 'belongsTo') { - $result = array(); - - foreach ($this->{$type} as $assoc => $data) { - if (isset($data['foreignKey']) && is_string($data['foreignKey'])) { - $result[$assoc] = $data['foreignKey']; - } - } - - return $result; - } - -/** - * Returns true if a record with particular ID exists. - * - * If $id is not passed it calls `Model::getID()` to obtain the current record ID, - * and then performs a `Model::find('count')` on the currently configured datasource - * to ascertain the existence of the record in persistent storage. - * - * @param integer|string $id ID of record to check for existence - * @return boolean True if such a record exists - */ - public function exists($id = null) { - if ($id === null) { - $id = $this->getID(); - } - - if ($id === false) { - return false; - } - - return (bool)$this->find('count', array( - 'conditions' => array( - $this->alias . '.' . $this->primaryKey => $id - ), - 'recursive' => -1, - 'callbacks' => false - )); - } - -/** - * Returns true if a record that meets given conditions exists. - * - * @param array $conditions SQL conditions array - * @return boolean True if such a record exists - */ - public function hasAny($conditions = null) { - return (bool)$this->find('count', array('conditions' => $conditions, 'recursive' => -1)); - } - -/** - * Queries the datasource and returns a result set array. - * - * Used to perform find operations, where the first argument is type of find operation to perform - * (all / first / count / neighbors / list / threaded), - * second parameter options for finding (indexed array, including: 'conditions', 'limit', - * 'recursive', 'page', 'fields', 'offset', 'order', 'callbacks') - * - * Eg: - * {{{ - * $model->find('all', array( - * 'conditions' => array('name' => 'Thomas Anderson'), - * 'fields' => array('name', 'email'), - * 'order' => 'field3 DESC', - * 'recursive' => 2, - * 'group' => 'type', - * 'callbacks' => false, - * )); - * }}} - * - * In addition to the standard query keys above, you can provide Datasource, and behavior specific - * keys. For example, when using a SQL based datasource you can use the joins key to specify additional - * joins that should be part of the query. - * - * {{{ - * $model->find('all', array( - * 'conditions' => array('name' => 'Thomas Anderson'), - * 'joins' => array( - * array( - * 'alias' => 'Thought', - * 'table' => 'thoughts', - * 'type' => 'LEFT', - * 'conditions' => '`Thought`.`person_id` = `Person`.`id`' - * ) - * ) - * )); - * }}} - * - * ### Disabling callbacks - * - * The `callbacks` key allows you to disable or specify the callbacks that should be run. To - * disable beforeFind & afterFind callbacks set `'callbacks' => false` in your options. You can - * also set the callbacks option to 'before' or 'after' to enable only the specified callback. - * - * ### Adding new find types - * - * Behaviors and find types can also define custom finder keys which are passed into find(). - * See the documentation for custom find types - * (http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#creating-custom-find-types) - * for how to implement custom find types. - * - * Specifying 'fields' for notation 'list': - * - * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value. - * - If a single field is specified, 'id' is used for key and specified field is used for value. - * - If three fields are specified, they are used (in order) for key, value and group. - * - Otherwise, first and second fields are used for key and value. - * - * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you - * have issues with database views. - * - * Note: find(count) has its own return values. - * - * @param string $type Type of find operation (all / first / count / neighbors / list / threaded) - * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks) - * @return array Array of records, or Null on failure. - * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html - */ - public function find($type = 'first', $query = array()) { - $this->findQueryType = $type; - $this->id = $this->getID(); - - $query = $this->buildQuery($type, $query); - if ($query === null) { - return null; - } - - return $this->_readDataSource($type, $query); - } - -/** - * Read from the datasource - * - * Model::_readDataSource() is used by all find() calls to read from the data source and can be overloaded to allow - * caching of datasource calls. - * - * {{{ - * protected function _readDataSource($type, $query) { - * $cacheName = md5(json_encode($query)); - * $cache = Cache::read($cacheName, 'cache-config-name'); - * if ($cache !== false) { - * return $cache; - * } - * - * $results = parent::_readDataSource($type, $query); - * Cache::write($cacheName, $results, 'cache-config-name'); - * return $results; - * } - * }}} - * - * @param string $type Type of find operation (all / first / count / neighbors / list / threaded) - * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks) - * @return array - */ - protected function _readDataSource($type, $query) { - $results = $this->getDataSource()->read($this, $query); - $this->resetAssociations(); - - if ($query['callbacks'] === true || $query['callbacks'] === 'after') { - $results = $this->_filterResults($results); - } - - $this->findQueryType = null; - - if ($this->findMethods[$type] === true) { - return $this->{'_find' . ucfirst($type)}('after', $query, $results); - } - } - -/** - * Builds the query array that is used by the data source to generate the query to fetch the data. - * - * @param string $type Type of find operation (all / first / count / neighbors / list / threaded) - * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks) - * @return array Query array or null if it could not be build for some reasons - * @see Model::find() - */ - public function buildQuery($type = 'first', $query = array()) { - $query = array_merge( - array( - 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null, - 'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true, - ), - (array)$query - ); - - if ($this->findMethods[$type] === true) { - $query = $this->{'_find' . ucfirst($type)}('before', $query); - } - - if (!is_numeric($query['page']) || intval($query['page']) < 1) { - $query['page'] = 1; - } - - if ($query['page'] > 1 && !empty($query['limit'])) { - $query['offset'] = ($query['page'] - 1) * $query['limit']; - } - - if ($query['order'] === null && $this->order !== null) { - $query['order'] = $this->order; - } - - $query['order'] = array($query['order']); - - if ($query['callbacks'] === true || $query['callbacks'] === 'before') { - $event = new Event('Model.beforeFind', $this, array($query)); - list($event->break, $event->breakOn, $event->modParams) = array(true, array(false, null), 0); - $this->getEventManager()->dispatch($event); - - if ($event->isStopped()) { - return null; - } - - $query = $event->result === true ? $event->data[0] : $event->result; - } - - return $query; - } - -/** - * Handles the before/after filter logic for find('all') operations. Only called by Model::find(). - * - * @param string $state Either "before" or "after" - * @param array $query - * @param array $results - * @return array - * @see Model::find() - */ - protected function _findAll($state, $query, $results = array()) { - if ($state === 'before') { - return $query; - } - - return $results; - } - -/** - * Handles the before/after filter logic for find('first') operations. Only called by Model::find(). - * - * @param string $state Either "before" or "after" - * @param array $query - * @param array $results - * @return array - * @see Model::find() - */ - protected function _findFirst($state, $query, $results = array()) { - if ($state === 'before') { - $query['limit'] = 1; - return $query; - } - - if (empty($results[0])) { - return array(); - } - - return $results[0]; - } - -/** - * Handles the before/after filter logic for find('count') operations. Only called by Model::find(). - * - * @param string $state Either "before" or "after" - * @param array $query - * @param array $results - * @return integer The number of records found, or false - * @see Model::find() - */ - protected function _findCount($state, $query, $results = array()) { - if ($state === 'before') { - if (!empty($query['type']) && isset($this->findMethods[$query['type']]) && $query['type'] !== 'count') { - $query['operation'] = 'count'; - $query = $this->{'_find' . ucfirst($query['type'])}('before', $query); - } - - $db = $this->getDataSource(); - $query['order'] = false; - if (!method_exists($db, 'calculate')) { - return $query; - } - - if (!empty($query['fields']) && is_array($query['fields'])) { - if (!preg_match('/^count/i', current($query['fields']))) { - unset($query['fields']); - } - } - - if (empty($query['fields'])) { - $query['fields'] = $db->calculate($this, 'count'); - } elseif (method_exists($db, 'expression') && is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) { - $query['fields'] = $db->calculate($this, 'count', array( - $db->expression($query['fields']), 'count' - )); - } - - return $query; - } - - foreach (array(0, $this->alias) as $key) { - if (isset($results[0][$key]['count'])) { - if ($query['group']) { - return count($results); - } - - return intval($results[0][$key]['count']); - } - } - - return false; - } - -/** - * Handles the before/after filter logic for find('list') operations. Only called by Model::find(). - * - * @param string $state Either "before" or "after" - * @param array $query - * @param array $results - * @return array Key/value pairs of primary keys/display field values of all records found - * @see Model::find() - */ - protected function _findList($state, $query, $results = array()) { - if ($state === 'before') { - if (empty($query['fields'])) { - $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}"); - $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null); - } else { - if (!is_array($query['fields'])) { - $query['fields'] = String::tokenize($query['fields']); - } - - if (count($query['fields']) === 1) { - if (strpos($query['fields'][0], '.') === false) { - $query['fields'][0] = $this->alias . '.' . $query['fields'][0]; - } - - $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null); - $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]); - } elseif (count($query['fields']) === 3) { - for ($i = 0; $i < 3; $i++) { - if (strpos($query['fields'][$i], '.') === false) { - $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i]; - } - } - - $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]); - } else { - for ($i = 0; $i < 2; $i++) { - if (strpos($query['fields'][$i], '.') === false) { - $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i]; - } - } - - $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null); - } - } - - if (!isset($query['recursive']) || $query['recursive'] === null) { - $query['recursive'] = -1; - } - list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list; - - return $query; - } - - if (empty($results)) { - return array(); - } - - return Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']); - } - -/** - * Detects the previous field's value, then uses logic to find the 'wrapping' - * rows and return them. - * - * @param string $state Either "before" or "after" - * @param array $query - * @param array $results - * @return array - */ - protected function _findNeighbors($state, $query, $results = array()) { - extract($query); - - if ($state === 'before') { - $conditions = (array)$conditions; - if (isset($field) && isset($value)) { - if (strpos($field, '.') === false) { - $field = $this->alias . '.' . $field; - } - } else { - $field = $this->alias . '.' . $this->primaryKey; - $value = $this->id; - } - - $query['conditions'] = array_merge($conditions, array($field . ' <' => $value)); - $query['order'] = $field . ' DESC'; - $query['limit'] = 1; - $query['field'] = $field; - $query['value'] = $value; - - return $query; - } - - unset($query['conditions'][$field . ' <']); - $return = array(); - if (isset($results[0])) { - $prevVal = Hash::get($results[0], $field); - $query['conditions'][$field . ' >='] = $prevVal; - $query['conditions'][$field . ' !='] = $value; - $query['limit'] = 2; - } else { - $return['prev'] = null; - $query['conditions'][$field . ' >'] = $value; - $query['limit'] = 1; - } - - $query['order'] = $field . ' ASC'; - $neighbors = $this->find('all', $query); - if (!array_key_exists('prev', $return)) { - $return['prev'] = isset($neighbors[0]) ? $neighbors[0] : null; - } - - if (count($neighbors) === 2) { - $return['next'] = $neighbors[1]; - } elseif (count($neighbors) === 1 && !$return['prev']) { - $return['next'] = $neighbors[0]; - } else { - $return['next'] = null; - } - - return $return; - } - -/** - * In the event of ambiguous results returned (multiple top level results, with different parent_ids) - * top level results with different parent_ids to the first result will be dropped - * - * @param string $state - * @param mixed $query - * @param array $results - * @return array Threaded results - */ - protected function _findThreaded($state, $query, $results = array()) { - if ($state === 'before') { - return $query; - } - - $parent = 'parent_id'; - if (isset($query['parent'])) { - $parent = $query['parent']; - } - - return Hash::nest($results, array( - 'idPath' => '{n}.' . $this->alias . '.' . $this->primaryKey, - 'parentPath' => '{n}.' . $this->alias . '.' . $parent - )); - } - -/** - * Passes query results through model and behavior afterFind() methods. - * - * @param array $results Results to filter - * @param boolean $primary If this is the primary model results (results from model where the find operation was performed) - * @return array Set of filtered results - */ - protected function _filterResults($results, $primary = true) { - $event = new Event('Model.afterFind', $this, array($results, $primary)); - $event->modParams = 0; - $this->getEventManager()->dispatch($event); - return $event->result; - } - -/** - * This resets the association arrays for the model back - * to those originally defined in the model. Normally called at the end - * of each call to Model::find() - * - * @return boolean Success - */ - public function resetAssociations() { - if (!empty($this->__backAssociation)) { - foreach ($this->_associations as $type) { - if (isset($this->__backAssociation[$type])) { - $this->{$type} = $this->__backAssociation[$type]; - } - } - - $this->__backAssociation = array(); - } - - foreach ($this->_associations as $type) { - foreach ($this->{$type} as $key => $name) { - if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) { - $this->{$key}->resetAssociations(); - } - } - } - - $this->__backAssociation = array(); - return true; - } - -/** - * Returns false if any fields passed match any (by default, all if $or = false) of their matching values. - * - * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data) - * @param boolean $or If false, all fields specified must match in order for a false return value - * @return boolean False if any records matching any fields are found - */ - public function isUnique($fields, $or = true) { - if (!is_array($fields)) { - $fields = func_get_args(); - if (is_bool($fields[count($fields) - 1])) { - $or = $fields[count($fields) - 1]; - unset($fields[count($fields) - 1]); - } - } - - foreach ($fields as $field => $value) { - if (is_numeric($field)) { - unset($fields[$field]); - - $field = $value; - $value = null; - if (isset($this->data[$this->alias][$field])) { - $value = $this->data[$this->alias][$field]; - } - } - - if (strpos($field, '.') === false) { - unset($fields[$field]); - $fields[$this->alias . '.' . $field] = $value; - } - } - - if ($or) { - $fields = array('or' => $fields); - } - - if (!empty($this->id)) { - $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id; - } - - return !$this->find('count', array('conditions' => $fields, 'recursive' => -1)); - } - -/** - * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method. - * - * @param string $sql SQL statement - * @param boolean|array $params Either a boolean to control query caching or an array of parameters - * for use with prepared statement placeholders. - * @param boolean $cache If $params is provided, a boolean flag for enabling/disabled - * query caching. - * @return mixed Resultset array or boolean indicating success / failure depending on the query executed - * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query - */ - public function query($sql) { - $params = func_get_args(); - $db = $this->getDataSource(); - return call_user_func_array(array(&$db, 'query'), $params); - } - -/** - * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations - * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation. - * - * Will validate the currently set data. Use Model::set() or Model::create() to set the active data. - * - * @param array $options An optional array of custom options to be made available in the beforeValidate callback - * @return boolean True if there are no errors - */ - public function validates($options = array()) { - return $this->validator()->validates($options); - } - -/** - * Returns an array of fields that have failed the validation of the current model. - * - * Additionally it populates the validationErrors property of the model with the same array. - * - * @param array|string $options An optional array of custom options to be made available in the beforeValidate callback - * @return array Array of invalid fields and their error messages - * @see Model::validates() - */ - public function invalidFields($options = array()) { - return $this->validator()->errors($options); - } - -/** - * Marks a field as invalid, optionally setting the name of validation - * rule (in case of multiple validation for field) that was broken. - * - * @param string $field The name of the field to invalidate - * @param mixed $value Name of validation rule that was not failed, or validation message to - * be returned. If no validation key is provided, defaults to true. - * @return void - */ - public function invalidate($field, $value = true) { - $this->validator()->invalidate($field, $value); - } - -/** - * Returns true if given field name is a foreign key in this model. - * - * @param string $field Returns true if the input string ends in "_id" - * @return boolean True if the field is a foreign key listed in the belongsTo array. - */ - public function isForeignKey($field) { - $foreignKeys = array(); - if (!empty($this->belongsTo)) { - foreach ($this->belongsTo as $data) { - $foreignKeys[] = $data['foreignKey']; - } - } - - return in_array($field, $foreignKeys); - } - -/** - * Escapes the field name and prepends the model name. Escaping is done according to the - * current database driver's rules. - * - * @param string $field Field to escape (e.g: id) - * @param string $alias Alias for the model (e.g: Post) - * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`). - */ - public function escapeField($field = null, $alias = null) { - if (empty($alias)) { - $alias = $this->alias; - } - - if (empty($field)) { - $field = $this->primaryKey; - } - - $db = $this->getDataSource(); - if (strpos($field, $db->name($alias) . '.') === 0) { - return $field; - } - - return $db->name($alias . '.' . $field); - } - -/** - * Returns the current record's ID - * - * @param integer $list Index on which the composed ID is located - * @return mixed The ID of the current record, false if no ID - */ - public function getID($list = 0) { - if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) { - return false; - } - - if (!is_array($this->id)) { - return $this->id; - } - - if (isset($this->id[$list]) && !empty($this->id[$list])) { - return $this->id[$list]; - } - - if (isset($this->id[$list])) { - return false; - } - - return current($this->id); - } - -/** - * Returns the ID of the last record this model inserted. - * - * @return mixed Last inserted ID - */ - public function getLastInsertID() { - return $this->getInsertID(); - } - -/** - * Returns the ID of the last record this model inserted. - * - * @return mixed Last inserted ID - */ - public function getInsertID() { - return $this->_insertID; - } - -/** - * Sets the ID of the last record this model inserted - * - * @param integer|string $id Last inserted ID - * @return void - */ - public function setInsertID($id) { - $this->_insertID = $id; - } - -/** - * Returns the number of rows returned from the last query. - * - * @return integer Number of rows - */ - public function getNumRows() { - return $this->getDataSource()->lastNumRows(); - } - -/** - * Returns the number of rows affected by the last query. - * - * @return integer Number of rows - */ - public function getAffectedRows() { - return $this->getDataSource()->lastAffected(); - } - -/** - * Sets the DataSource to which this model is bound. - * - * @param string $dataSource The name of the DataSource, as defined in App/Config/datasources.php - * @return void - * @throws MissingConnectionException - */ - public function setDataSource($dataSource = null) { - $oldConfig = $this->useDbConfig; - - if ($dataSource) { - $this->useDbConfig = $dataSource; - } - - $db = ConnectionManager::getDataSource($this->useDbConfig); - if (!empty($oldConfig) && isset($db->config['prefix'])) { - $oldDb = ConnectionManager::getDataSource($oldConfig); - - if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) { - $this->tablePrefix = $db->config['prefix']; - } - } elseif (isset($db->config['prefix'])) { - $this->tablePrefix = $db->config['prefix']; - } - - $this->schemaName = $db->getSchemaName(); - } - -/** - * Gets the DataSource to which this model is bound. - * - * @return DataSource A DataSource object - */ - public function getDataSource() { - if (!$this->_sourceConfigured && $this->useTable !== false) { - $this->_sourceConfigured = true; - $this->setSource($this->useTable); - } - - return ConnectionManager::getDataSource($this->useDbConfig); - } - -/** - * Get associations - * - * @return array - */ - public function associations() { - return $this->_associations; - } - -/** - * Gets all the models with which this model is associated. - * - * @param string $type Only result associations of this type - * @return array Associations - */ - public function getAssociated($type = null) { - if (!$type) { - $associated = array(); - foreach ($this->_associations as $assoc) { - if (!empty($this->{$assoc})) { - $models = array_keys($this->{$assoc}); - foreach ($models as $m) { - $associated[$m] = $assoc; - } - } - } - - return $associated; - } - - if (in_array($type, $this->_associations)) { - if (empty($this->{$type})) { - return array(); - } - - return array_keys($this->{$type}); - } - - $assoc = array_merge( - $this->hasOne, - $this->hasMany, - $this->belongsTo, - $this->hasAndBelongsToMany - ); - - if (array_key_exists($type, $assoc)) { - foreach ($this->_associations as $a) { - if (isset($this->{$a}[$type])) { - $assoc[$type]['association'] = $a; - break; - } - } - - return $assoc[$type]; - } - - return null; - } - -/** - * Gets the name and fields to be used by a join model. This allows specifying join fields - * in the association definition. - * - * @param string|array $assoc The model to be joined - * @param array $keys Any join keys which must be merged with the keys queried - * @return array - */ - public function joinModel($assoc, $keys = array()) { - if (is_string($assoc)) { - list(, $assoc) = pluginSplit($assoc); - return array($assoc, array_keys($this->{$assoc}->schema())); - } - - if (is_array($assoc)) { - $with = key($assoc); - return array($with, array_unique(array_merge($assoc[$with], $keys))); - } - - trigger_error( - __d('cake_dev', 'Invalid join model settings in %s. The association parameter has the wrong type, expecting a string or array, but was passed type: %s', $this->alias, gettype($assoc)), - E_USER_WARNING - ); - } - -/** - * Called before each find operation. Return false if you want to halt the find - * call, otherwise return the (modified) query data. - * - * @param array $query Data used to execute this query, i.e. conditions, order, etc. - * @return mixed true if the operation should continue, false if it should abort; or, modified - * $query to continue with new $query - * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforefind - */ - public function beforeFind($query) { - return true; - } - -/** - * Called after each find operation. Can be used to modify any results returned by find(). - * Return value should be the (modified) results. - * - * @param mixed $results The results of the find operation - * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association) - * @return mixed Result of the find operation - * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterfind - */ - public function afterFind($results, $primary = false) { - return $results; - } - -/** - * Called before each save operation, after validation. Return a non-true result - * to halt the save. - * - * @param array $options Options passed from Model::save(). - * @return boolean True if the operation should continue, false if it should abort - * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave - * @see Model::save() - */ - public function beforeSave($options = array()) { - return true; - } - -/** - * Called after each successful save operation. - * - * @param boolean $created True if this save created a new record - * @param array $options Options passed from Model::save(). - * @return void - * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#aftersave - * @see Model::save() - */ - public function afterSave($created, $options = array()) { - } - -/** - * Called before every deletion operation. - * - * @param boolean $cascade If true records that depend on this record will also be deleted - * @return boolean True if the operation should continue, false if it should abort - * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforedelete - */ - public function beforeDelete($cascade = true) { - return true; - } - -/** - * Called after every deletion operation. - * - * @return void - * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterdelete - */ - public function afterDelete() { - } - -/** - * Called during validation operations, before validation. Please note that custom - * validation rules can be defined in $validate. - * - * @param array $options Options passed from Model::save(). - * @return boolean True if validate operation should continue, false to abort - * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate - * @see Model::save() - */ - public function beforeValidate($options = array()) { - return true; - } - -/** - * Called after data has been checked for errors - * - * @return void - */ - public function afterValidate() { - } - -/** - * Called when a DataSource-level error occurs. - * - * @return void - * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#onerror - */ - public function onError() { - } - -/** - * Clears cache for this model. - * - * @param string $type If null this deletes cached views if Cache.check is true - * Will be used to allow deleting query cache also - * @return mixed True on delete, null otherwise - */ - protected function _clearCache($type = null) { - if ($type !== null || Configure::read('Cache.check') !== true) { - return; - } - $pluralized = Inflector::pluralize($this->alias); - $assoc = array( - strtolower($pluralized), - Inflector::underscore($pluralized) - ); - foreach ($this->_associations as $association) { - foreach ($this->{$association} as $className) { - $pluralizedAssociation = Inflector::pluralize($className['className']); - if (!in_array(strtolower($pluralizedAssociation), $assoc)) { - $assoc = array_merge($assoc, array( - strtolower($pluralizedAssociation), - Inflector::underscore($pluralizedAssociation) - )); - } - } - } - clearCache(array_unique($assoc)); - return true; - } - -/** - * Returns an instance of a model validator for this class - * - * @param ModelValidator Model validator instance. - * If null a new ModelValidator instance will be made using current model object - * @return ModelValidator - */ - public function validator(ModelValidator $instance = null) { - if ($instance) { - $this->_validator = $instance; - } elseif (!$this->_validator) { - $this->_validator = new ModelValidator($this); - } - - return $this->_validator; - } - -} diff --git a/Cake/Model/ModelBehavior.php b/Cake/Model/ModelBehavior.php deleted file mode 100644 index b654f592d2f..00000000000 --- a/Cake/Model/ModelBehavior.php +++ /dev/null @@ -1,241 +0,0 @@ -Model->doSomething($arg1, $arg2);`. - * - * ### Mapped methods - * - * Behaviors can also define mapped methods. Mapped methods use pattern matching for method invocation. This - * allows you to create methods similar to Model::findAllByXXX methods on your behaviors. Mapped methods need to - * be declared in your behaviors `$mapMethods` array. The method signature for a mapped method is slightly different - * than a normal behavior mixin method. - * - * {{{ - * public $mapMethods = array('/do(\w+)/' => 'doSomething'); - * - * function doSomething(Model $model, $method, $arg1, $arg2) { - * //do something - * } - * }}} - * - * The above will map every doXXX() method call to the behavior. As you can see, the model is - * still the first parameter, but the called method name will be the 2nd parameter. This allows - * you to munge the method name for additional information, much like Model::findAllByXX. - * - * @see Model::$actsAs - * @see BehaviorCollection::load() - */ -class ModelBehavior extends Object { - -/** - * Contains configuration settings for use with individual model objects. This - * is used because if multiple models use this Behavior, each will use the same - * object instance. Individual model settings should be stored as an - * associative array, keyed off of the model name. - * - * @var array - * @see Model::$alias - */ - public $settings = array(); - -/** - * Allows the mapping of preg-compatible regular expressions to public or - * private methods in this class, where the array key is a /-delimited regular - * expression, and the value is a class method. Similar to the functionality of - * the findBy* / findAllBy* magic methods. - * - * @var array - */ - public $mapMethods = array(); - -/** - * Setup this behavior with the specified configuration settings. - * - * @param Model $model Model using this behavior - * @param array $config Configuration settings for $model - * @return void - */ - public function setup(Model $model, $config = array()) { - } - -/** - * Clean up any initialization this behavior has done on a model. Called when a behavior is dynamically - * detached from a model using Model::detach(). - * - * @param Model $model Model using this behavior - * @return void - * @see BehaviorCollection::detach() - */ - public function cleanup(Model $model) { - if (isset($this->settings[$model->alias])) { - unset($this->settings[$model->alias]); - } - } - -/** - * beforeFind can be used to cancel find operations, or modify the query that will be executed. - * By returning null/false you can abort a find. By returning an array you can modify/replace the query - * that is going to be run. - * - * @param Model $model Model using this behavior - * @param array $query Data used to execute this query, i.e. conditions, order, etc. - * @return boolean|array False or null will abort the operation. You can return an array to replace the - * $query that will be eventually run. - */ - public function beforeFind(Model $model, $query) { - return true; - } - -/** - * After find callback. Can be used to modify any results returned by find. - * - * @param Model $model Model using this behavior - * @param mixed $results The results of the find operation - * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association) - * @return mixed An array value will replace the value of $results - any other value will be ignored. - */ - public function afterFind(Model $model, $results, $primary = false) { - } - -/** - * beforeValidate is called before a model is validated, you can use this callback to - * add behavior validation rules into a models validate array. Returning false - * will allow you to make the validation fail. - * - * @param Model $model Model using this behavior - * @param array $options Options passed from Model::save(). - * @return mixed False or null will abort the operation. Any other result will continue. - * @see Model::save() - */ - public function beforeValidate(Model $model, $options = array()) { - return true; - } - -/** - * afterValidate is called just after model data was validated, you can use this callback - * to perform any data cleanup or preparation if needed - * - * @param Model $model Model using this behavior - * @return mixed False will stop this event from being passed to other behaviors - */ - public function afterValidate(Model $model) { - return true; - } - -/** - * beforeSave is called before a model is saved. Returning false from a beforeSave callback - * will abort the save operation. - * - * @param Model $model Model using this behavior - * @param array $options Options passed from Model::save(). - * @return mixed False if the operation should abort. Any other result will continue. - * @see Model::save() - */ - public function beforeSave(Model $model, $options = array()) { - return true; - } - -/** - * afterSave is called after a model is saved. - * - * @param Model $model Model using this behavior - * @param boolean $created True if this save created a new record - * @param array $options Options passed from Model::save(). - * @return boolean - * @see Model::save() - */ - public function afterSave(Model $model, $created, $options = array()) { - return true; - } - -/** - * Before delete is called before any delete occurs on the attached model, but after the model's - * beforeDelete is called. Returning false from a beforeDelete will abort the delete. - * - * @param Model $model Model using this behavior - * @param boolean $cascade If true records that depend on this record will also be deleted - * @return mixed False if the operation should abort. Any other result will continue. - */ - public function beforeDelete(Model $model, $cascade = true) { - return true; - } - -/** - * After delete is called after any delete occurs on the attached model. - * - * @param Model $model Model using this behavior - * @return void - */ - public function afterDelete(Model $model) { - } - -/** - * DataSource error callback - * - * @param Model $model Model using this behavior - * @param string $error Error generated in DataSource - * @return void - */ - public function onError(Model $model, $error) { - } - -/** - * If $model's whitelist property is non-empty, $field will be added to it. - * Note: this method should *only* be used in beforeValidate or beforeSave to ensure - * that it only modifies the whitelist for the current save operation. Also make sure - * you explicitly set the value of the field which you are allowing. - * - * @param Model $model Model using this behavior - * @param string $field Field to be added to $model's whitelist - * @return void - */ - protected function _addToWhitelist(Model $model, $field) { - if (is_array($field)) { - foreach ($field as $f) { - $this->_addToWhitelist($model, $f); - } - return; - } - if (!empty($model->whitelist) && !in_array($field, $model->whitelist)) { - $model->whitelist[] = $field; - } - } - -} diff --git a/Cake/Model/Permission.php b/Cake/Model/Permission.php deleted file mode 100644 index 9ad44ea46b8..00000000000 --- a/Cake/Model/Permission.php +++ /dev/null @@ -1,260 +0,0 @@ -useDbConfig = $config; - } - parent::__construct(); - } - -/** - * Checks if the given $aro has access to action $action in $aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @param string $action Action (defaults to *) - * @return boolean Success (true if ARO has access to action in ACO, false otherwise) - */ - public function check($aro, $aco, $action = '*') { - if (!$aro || !$aco) { - return false; - } - - $permKeys = $this->getAcoKeys($this->schema()); - $aroPath = $this->Aro->node($aro); - $acoPath = $this->Aco->node($aco); - - if (!$aroPath || !$acoPath) { - trigger_error(__d('cake_dev', - "%s - Failed ARO/ACO node lookup in permissions check. Node references:\nAro: %s\nAco: %s", - 'DbAcl::check()', - print_r($aro, true), - print_r($aco, true)), - E_USER_WARNING - ); - return false; - } - - if (!$acoPath) { - trigger_error(__d('cake_dev', - "%s - Failed ACO node lookup in permissions check. Node references:\nAro: %s\nAco: %s", - 'DbAcl::check()', - print_r($aro, true), - print_r($aco, true)), - E_USER_WARNING - ); - return false; - } - - if ($action !== '*' && !in_array('_' . $action, $permKeys)) { - trigger_error(__d('cake_dev', "ACO permissions key %s does not exist in %s", $action, 'DbAcl::check()'), E_USER_NOTICE); - return false; - } - - $inherited = array(); - $acoIDs = Hash::extract($acoPath, '{n}.' . $this->Aco->alias . '.id'); - - $count = count($aroPath); - for ($i = 0; $i < $count; $i++) { - $permAlias = $this->alias; - - $perms = $this->find('all', array( - 'conditions' => array( - "{$permAlias}.aro_id" => $aroPath[$i][$this->Aro->alias]['id'], - "{$permAlias}.aco_id" => $acoIDs - ), - 'order' => array($this->Aco->alias . '.lft' => 'desc'), - 'recursive' => 0 - )); - - if (empty($perms)) { - continue; - } - $perms = Hash::extract($perms, '{n}.' . $this->alias); - foreach ($perms as $perm) { - if ($action === '*') { - - foreach ($permKeys as $key) { - if (!empty($perm)) { - if ($perm[$key] == -1) { - return false; - } elseif ($perm[$key] == 1) { - $inherited[$key] = 1; - } - } - } - - if (count($inherited) === count($permKeys)) { - return true; - } - } else { - switch ($perm['_' . $action]) { - case -1: - return false; - case 0: - continue; - case 1: - return true; - } - } - } - } - return false; - } - -/** - * Allow $aro to have access to action $actions in $aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @param string $actions Action (defaults to *) Invalid permissions will result in an exception - * @param integer $value Value to indicate access type (1 to give access, -1 to deny, 0 to inherit) - * @return boolean Success - * @throws Cake\Error\AclException on Invalid permission key. - */ - public function allow($aro, $aco, $actions = '*', $value = 1) { - $perms = $this->getAclLink($aro, $aco); - $permKeys = $this->getAcoKeys($this->schema()); - $save = array(); - - if (!$perms) { - trigger_error(__d('cake_dev', '%s - Invalid node', 'DbAcl::allow()'), E_USER_WARNING); - return false; - } - if (isset($perms[0])) { - $save = $perms[0][$this->alias]; - } - - if ($actions === '*') { - $save = array_combine($permKeys, array_pad(array(), count($permKeys), $value)); - } else { - if (!is_array($actions)) { - $actions = array('_' . $actions); - } - foreach ($actions as $action) { - if ($action{0} !== '_') { - $action = '_' . $action; - } - if (!in_array($action, $permKeys, true)) { - throw new Error\AclException(__d('cake_dev', 'Invalid permission key "%s"', $action)); - } - $save[$action] = $value; - } - } - list($save['aro_id'], $save['aco_id']) = array($perms['aro'], $perms['aco']); - - if ($perms['link'] && !empty($perms['link'])) { - $save['id'] = $perms['link'][0][$this->alias]['id']; - } else { - unset($save['id']); - $this->id = null; - } - return ($this->save($save) !== false); - } - -/** - * Get an array of access-control links between the given Aro and Aco - * - * @param string $aro ARO The requesting object identifier. - * @param string $aco ACO The controlled object identifier. - * @return array Indexed array with: 'aro', 'aco' and 'link' - */ - public function getAclLink($aro, $aco) { - $obj = array(); - $obj['Aro'] = $this->Aro->node($aro); - $obj['Aco'] = $this->Aco->node($aco); - - if (empty($obj['Aro']) || empty($obj['Aco'])) { - return false; - } - $aro = Hash::extract($obj, 'Aro.0.' . $this->Aro->alias . '.id'); - $aco = Hash::extract($obj, 'Aco.0.' . $this->Aco->alias . '.id'); - $aro = current($aro); - $aco = current($aco); - - return array( - 'aro' => $aro, - 'aco' => $aco, - 'link' => $this->find('all', array('conditions' => array( - $this->alias . '.aro_id' => $aro, - $this->alias . '.aco_id' => $aco - ))) - ); - } - -/** - * Get the crud type keys - * - * @param array $keys Permission schema - * @return array permission keys - */ - public function getAcoKeys($keys) { - $newKeys = array(); - $keys = array_keys($keys); - foreach ($keys as $key) { - if (!in_array($key, array('id', 'aro_id', 'aco_id'))) { - $newKeys[] = $key; - } - } - return $newKeys; - } -} diff --git a/Cake/Test/TestApp/Model/AppModel.php b/Cake/Test/TestApp/Model/AppModel.php deleted file mode 100644 index 53f5836c8d1..00000000000 --- a/Cake/Test/TestApp/Model/AppModel.php +++ /dev/null @@ -1,33 +0,0 @@ - - * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 3.0 - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) - */ -namespace TestApp\Model; - -use Cake\TestSuite\Fixture\TestModel; - -/** - * Article class - * - */ -class Article extends TestModel { - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('User'); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Comment' => array('dependent' => true)); - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Tag'); - -/** - * validate property - * - * @var array - */ - public $validate = array( - 'user_id' => 'numeric', - 'title' => array('required' => false, 'rule' => 'notEmpty'), - 'body' => array('required' => false, 'rule' => 'notEmpty'), - ); - -/** - * beforeSaveReturn property - * - * @var bool true - */ - public $beforeSaveReturn = true; - -/** - * beforeSave method - * - * @return void - */ - public function beforeSave($options = array()) { - return $this->beforeSaveReturn; - } - -/** - * titleDuplicate method - * - * @param string $title - * @return void - */ - public static function titleDuplicate($title) { - if ($title === 'My Article Title') { - return false; - } - return true; - } - -} diff --git a/Cake/Test/TestApp/Model/AuthUser.php b/Cake/Test/TestApp/Model/AuthUser.php deleted file mode 100644 index 549351fd29a..00000000000 --- a/Cake/Test/TestApp/Model/AuthUser.php +++ /dev/null @@ -1,35 +0,0 @@ -extra = $extra; - } - -/** - * paginateCount - * - * @return void - */ - public function paginateCount($conditions, $recursive, $extra) { - $this->extraCount = $extra; - } -} diff --git a/Cake/Test/TestApp/Model/ControllerPaginatorModel.php b/Cake/Test/TestApp/Model/ControllerPaginatorModel.php deleted file mode 100644 index 097e6226241..00000000000 --- a/Cake/Test/TestApp/Model/ControllerPaginatorModel.php +++ /dev/null @@ -1,52 +0,0 @@ -extra = $extra; - } - -/** - * paginateCount - * - * @return void - */ - public function paginateCount($conditions, $recursive, $extra) { - $this->extraCount = $extra; - } -} diff --git a/Cake/Test/TestApp/Model/Datasource/Database/TestLocalDriver.php b/Cake/Test/TestApp/Model/Datasource/Database/TestLocalDriver.php deleted file mode 100644 index 605f5686208..00000000000 --- a/Cake/Test/TestApp/Model/Datasource/Database/TestLocalDriver.php +++ /dev/null @@ -1,8 +0,0 @@ - 'PaginatorAuthor.id + 1' - ); - -} diff --git a/Cake/Test/TestApp/Model/PersisterOne.php b/Cake/Test/TestApp/Model/PersisterOne.php deleted file mode 100644 index 7eb2b8cb7f0..00000000000 --- a/Cake/Test/TestApp/Model/PersisterOne.php +++ /dev/null @@ -1,61 +0,0 @@ - array( - 'custom' => array( - 'rule' => array('custom', '.*'), - 'allowEmpty' => true, - 'required' => false, - 'message' => 'Post title is required' - ), - 'between' => array( - 'rule' => array('between', 5, 15), - 'message' => array('You may enter up to %s chars (minimum is %s chars)', 14, 6) - ) - ), - 'body' => array( - 'first_rule' => array( - 'rule' => array('custom', '.*'), - 'allowEmpty' => true, - 'required' => false, - 'message' => 'Post body is required' - ), - 'second_rule' => array( - 'rule' => array('custom', '.*'), - 'allowEmpty' => true, - 'required' => false, - 'message' => 'Post body is super required' - ) - ), - ); - -} diff --git a/Cake/Test/TestApp/Model/PersisterTwo.php b/Cake/Test/TestApp/Model/PersisterTwo.php deleted file mode 100644 index 41561c5aa4b..00000000000 --- a/Cake/Test/TestApp/Model/PersisterTwo.php +++ /dev/null @@ -1,31 +0,0 @@ -name . '.' . $this->primaryKey . ' > ' => '1'); - $options = Hash::merge($options, compact('conditions')); - return parent::find('all', $options); - } - return parent::find($type, $options); - } -} diff --git a/Cake/Test/TestApp/Model/RequestActionPost.php b/Cake/Test/TestApp/Model/RequestActionPost.php deleted file mode 100644 index 1e13e9015d5..00000000000 --- a/Cake/Test/TestApp/Model/RequestActionPost.php +++ /dev/null @@ -1,24 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.5432 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ - -/** - * Class TestPluginAppModel - * - */ -namespace TestPlugin\Model; - -use Cake\TestSuite\Fixture\TestModel; - -class TestPluginAppModel extends TestModel { -} diff --git a/Cake/Test/TestApp/Plugin/TestPlugin/Model/TestPluginAuthUser.php b/Cake/Test/TestApp/Plugin/TestPlugin/Model/TestPluginAuthUser.php deleted file mode 100644 index 6974aa7f7ae..00000000000 --- a/Cake/Test/TestApp/Plugin/TestPlugin/Model/TestPluginAuthUser.php +++ /dev/null @@ -1,39 +0,0 @@ - array( - 'notEmpty' => array( - 'rule' => 'notEmpty', - 'message' => 'I can haz plugin model validation message', - ), - ), - ); - -} diff --git a/Cake/Test/TestApp/Plugin/TestPlugin/Model/TestPluginComment.php b/Cake/Test/TestApp/Plugin/TestPlugin/Model/TestPluginComment.php deleted file mode 100644 index 32e53191afa..00000000000 --- a/Cake/Test/TestApp/Plugin/TestPlugin/Model/TestPluginComment.php +++ /dev/null @@ -1,31 +0,0 @@ - array( - 'rule' => array('custom', '.*'), - 'allowEmpty' => true, - 'required' => false, - 'message' => 'Post title is required' - ), - 'body' => array( - 'first_rule' => array( - 'rule' => array('custom', '.*'), - 'allowEmpty' => true, - 'required' => false, - 'message' => 'Post body is required' - ), - 'Post body is super required' => array( - 'rule' => array('custom', '.*'), - 'allowEmpty' => true, - 'required' => false, - ) - ), - ); - -/** - * Translation domain to use for validation messages - * - * @var string - */ - public $validationDomain = 'test_plugin'; - -} diff --git a/Cake/Test/TestCase/Console/Command/Task/ControllerTaskTest.php b/Cake/Test/TestCase/Console/Command/Task/ControllerTaskTest.php index a313dc55db3..b1fc201d820 100644 --- a/Cake/Test/TestCase/Console/Command/Task/ControllerTaskTest.php +++ b/Cake/Test/TestCase/Console/Command/Task/ControllerTaskTest.php @@ -19,8 +19,7 @@ use Cake\Console\Shell; use Cake\Core\App; use Cake\Core\Plugin; -use Cake\Model\Model; -use Cake\Model\Schema; +use Cake\ORM\Table; use Cake\TestSuite\TestCase; use Cake\Utility\ClassRegistry; use Cake\View\Helper; @@ -29,7 +28,7 @@ * Class BakeArticle * */ -class BakeArticle extends Model { +class BakeArticlesTable extends Table { public $hasMany = array('BakeComment'); @@ -37,7 +36,10 @@ class BakeArticle extends Model { } -class_alias('Cake\Test\TestCase\Console\Command\Task\BakeArticle', 'Cake\Model\BakeArticle'); +class_alias( + 'Cake\Test\TestCase\Console\Command\Task\BakeArticlesTable', + 'Cake\Model\Repository\BakeArticlesTable' +); /** * ControllerTaskTest class diff --git a/Cake/Test/TestCase/Console/Command/Task/TestTaskTest.php b/Cake/Test/TestCase/Console/Command/Task/TestTaskTest.php index 4cf35cd1480..80c66013af2 100644 --- a/Cake/Test/TestCase/Console/Command/Task/TestTaskTest.php +++ b/Cake/Test/TestCase/Console/Command/Task/TestTaskTest.php @@ -24,7 +24,7 @@ use Cake\Core\App; use Cake\Core\Configure; use Cake\Core\Plugin; -use Cake\Model\Model; +use Cake\ORM\Table; use Cake\TestSuite\TestCase; use Cake\Utility\ClassRegistry; @@ -32,14 +32,14 @@ * Test Article model * */ -class TestTaskArticle extends Model { +class TestTaskArticles extends Table { /** * Table name to use * * @var string */ - public $useTable = 'articles'; + public $_table = 'articles'; /** * HasMany Associations @@ -97,7 +97,7 @@ protected function _innerMethod() { * Tag Testing Model * */ -class TestTaskTag extends Model { +class TestTaskTags extends Table { /** * Table name @@ -125,7 +125,7 @@ class TestTaskTag extends Model { * Simulated plugin * */ -class TestTaskAppModel extends Model { +class TestTaskAppModel extends Table { } /** @@ -139,7 +139,7 @@ class TestTaskComment extends TestTaskAppModel { * * @var string */ - public $useTable = 'comments'; + public $_table = 'comments'; /** * Belongs To Associations @@ -254,7 +254,9 @@ public function testMethodIntrospection() { * @return void */ public function testFixtureArrayGenerationFromModel() { - $subject = ClassRegistry::init(__NAMESPACE__ . 'TestTaskArticle'); + $this->markTestIncomplete('Not working right now'); + + $subject = new TestTaskArticlesTable(); $result = $this->Task->generateFixtureList($subject); $expected = array('plugin.test_task.test_task_comment', 'app.articles_tags', 'app.test_task_article', 'app.test_task_tag'); @@ -298,8 +300,9 @@ public function testGetObjectType() { * @return void */ public function testRegistryClearWhenBuildingTestObjects() { - ClassRegistry::flush(); - $model = ClassRegistry::init('TestTaskComment'); + $this->markTestIncomplete('Not working right now'); + + $model = new TestTaskCommentsTable(); $model->bindModel(array( 'belongsTo' => array( 'Random' => array( @@ -391,6 +394,8 @@ public function testGetRealClassname() { * @return void */ public function testBakeModelTest() { + $this->markTestIncomplete('Model tests need reworking.'); + $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true)); $this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true)); @@ -660,6 +665,8 @@ public function testTestCaseFileNamePlugin() { * @return void */ public function testExecuteWithOneArg() { + $this->markTestIncomplete('Tests using models need work'); + $this->Task->args[0] = 'Model'; $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag')); $this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true)); @@ -677,6 +684,8 @@ public function testExecuteWithOneArg() { * @return void */ public function testExecuteWithTwoArgs() { + $this->markTestIncomplete('Tests using models need work'); + $this->Task->args = array('Model', 'TestTaskTag'); $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag')); $this->Task->expects($this->once())->method('createFile') @@ -694,6 +703,8 @@ public function testExecuteWithTwoArgs() { * @return void */ public function testExecuteWithTwoArgsLowerCase() { + $this->markTestIncomplete('Tests using models need work'); + $this->Task->args = array('model', 'TestTaskTag'); $this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag')); $this->Task->expects($this->once())->method('createFile') diff --git a/Cake/Test/TestCase/Console/Command/Task/ViewTaskTest.php b/Cake/Test/TestCase/Console/Command/Task/ViewTaskTest.php index 2a545ff4c5e..5fb8e651f30 100644 --- a/Cake/Test/TestCase/Console/Command/Task/ViewTaskTest.php +++ b/Cake/Test/TestCase/Console/Command/Task/ViewTaskTest.php @@ -23,21 +23,21 @@ use Cake\Controller\Controller; use Cake\Core\Configure; use Cake\Core\Plugin; -use Cake\Model\Model; +use Cake\ORM\Table; use Cake\TestSuite\TestCase; /** * Test View Task Comment Model * */ -class ViewTaskComment extends Model { +class ViewTaskCommentsTable extends Table { /** * Table name * * @var string */ - public $useTable = 'comments'; + public $_table = 'comments'; /** * Belongs To Associations @@ -56,14 +56,14 @@ class ViewTaskComment extends Model { * Test View Task Article Model * */ -class ViewTaskArticle extends Model { +class ViewTaskArticlesTable extends Table { /** * Table name * * @var string */ - public $useTable = 'articles'; + public $_table = 'articles'; } /** @@ -72,7 +72,7 @@ class ViewTaskArticle extends Model { */ class ViewTaskCommentsController extends Controller { - public $modelClass = 'Cake\Model\ViewTaskComments'; + public $modelClass = 'Cake\Model\Repository\ViewTaskCommentsTable'; /** * Testing public controller action @@ -162,8 +162,8 @@ public function admin_delete() { // Alias classes class_alias(__NAMESPACE__ . '\ViewTaskArticlesController', 'Cake\Controller\ViewTaskArticlesController'); class_alias(__NAMESPACE__ . '\ViewTaskCommentsController', 'Cake\Controller\ViewTaskCommentsController'); -class_alias(__NAMESPACE__ . '\ViewTaskComment', 'Cake\Model\ViewTaskComments'); -class_alias(__NAMESPACE__ . '\ViewTaskArticle', 'Cake\Model\ViewTaskArticle'); +class_alias(__NAMESPACE__ . '\ViewTaskCommentsTable', 'Cake\Model\Repository\ViewTaskCommentsTable'); +class_alias(__NAMESPACE__ . '\ViewTaskArticlesTable', 'Cake\Model\Repostiory\ViewTaskArticlesTable'); /** * ViewTaskTest class diff --git a/Cake/Test/TestCase/Controller/Component/Acl/DbAclTest.php b/Cake/Test/TestCase/Controller/Component/Acl/DbAclTest.php deleted file mode 100644 index c1ad542bc79..00000000000 --- a/Cake/Test/TestCase/Controller/Component/Acl/DbAclTest.php +++ /dev/null @@ -1,565 +0,0 @@ - array( - 'with' => 'PermissionTwoTest', - 'className' => 'Cake\Test\TestCase\Controller\Component\AcoTwoTest' - )); -} - -/** - * AcoTwoTest class - * - */ -class AcoTwoTest extends AclNodeTwoTestBase { - -/** - * name property - * - * @var string - */ - public $name = 'AcoTwoTest'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'aco_twos'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('AroTwoTest' => array( - 'with' => 'PermissionTwoTest', - 'className' => 'Cake\Test\TestCase\Controller\Component\AroTwoTest' - )); -} - -/** - * PermissionTwoTest class - * - */ -class PermissionTwoTest extends Permission { - -/** - * name property - * - * @var string - */ - public $name = 'PermissionTwoTest'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'aros_aco_twos'; - -/** - * cacheQueries property - * - * @var boolean - */ - public $cacheQueries = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'AroTwoTest' => array( - 'foreignKey' => 'aro_id', - 'className' => 'Cake\Test\TestCase\Controller\Component\AroTwoTest' - ), - 'AcoTwoTest' => array( - 'foreignKey' => 'aco_id', - 'className' => 'Cake\Test\TestCase\Controller\Component\AcoTwoTest' - ) - ); - -/** - * actsAs property - * - * @var mixed null - */ - public $actsAs = null; -} - -/** - * DbAclTwoTest class - * - */ -class DbAclTwoTest extends DbAcl { - -/** - * construct method - * - */ - public function __construct() { - $this->Aro = new AroTwoTest(); - $this->Aro->Permission = new PermissionTwoTest(); - $this->Aco = new AcoTwoTest(); - $this->Aro->Permission = new PermissionTwoTest(); - - $this->Permission = $this->Aro->Permission; - $this->Permission->Aro = $this->Aro; - $this->Permission->Aco = $this->Aco; - } - -} - -/** - * Test case for AclComponent using the DbAcl implementation. - * - */ -class DbAclTest extends TestCase { - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array('core.aro_two', 'core.aco_two', 'core.aros_aco_two'); - -/** - * setUp method - * - * @return void - */ - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('DbAcl will not work until models do.'); - Configure::write('Acl.classname', __NAMESPACE__ . '\DbAclTwoTest'); - Configure::write('Acl.database', 'test'); - $Collection = new ComponentRegistry(); - $this->Acl = new AclComponent($Collection); - } - -/** - * tearDown method - * - * @return void - */ - public function tearDown() { - parent::tearDown(); - unset($this->Acl); - } - -/** - * testAclCreate method - * - * @return void - */ - public function testCreate() { - $this->Acl->Aro->create(array('alias' => 'Chotchkey')); - $this->assertTrue((bool)$this->Acl->Aro->save()); - - $parent = $this->Acl->Aro->id; - - $this->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Joanna')); - $this->assertTrue((bool)$this->Acl->Aro->save()); - - $this->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Stapler')); - $this->assertTrue((bool)$this->Acl->Aro->save()); - - $root = $this->Acl->Aco->node('ROOT'); - $parent = $root[0]['AcoTwoTest']['id']; - - $this->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'Drinks')); - $this->assertTrue((bool)$this->Acl->Aco->save()); - - $this->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'PiecesOfFlair')); - $this->assertTrue((bool)$this->Acl->Aco->save()); - } - -/** - * testAclCreateWithParent method - * - * @return void - */ - public function testCreateWithParent() { - $parent = $this->Acl->Aro->findByAlias('Peter', null, null, -1); - $this->Acl->Aro->create(); - $this->Acl->Aro->save(array( - 'alias' => 'Subordinate', - 'model' => 'User', - 'foreign_key' => 7, - 'parent_id' => $parent['AroTwoTest']['id'] - )); - $result = $this->Acl->Aro->findByAlias('Subordinate', null, null, -1); - $this->assertEquals(16, $result['AroTwoTest']['lft']); - $this->assertEquals(17, $result['AroTwoTest']['rght']); - } - -/** - * testDbAclAllow method - * - * @expectedException PHPUnit_Framework_Error_Warning - * @return void - */ - public function testAllow() { - $this->assertFalse($this->Acl->check('Micheal', 'tpsReports', 'read')); - $this->assertTrue($this->Acl->allow('Micheal', 'tpsReports', array('read', 'delete', 'update'))); - $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'update')); - $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'read')); - $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete')); - - $this->assertFalse($this->Acl->check('Micheal', 'tpsReports', 'create')); - $this->assertTrue($this->Acl->allow('Micheal', 'ROOT/tpsReports', 'create')); - $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'create')); - $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete')); - $this->assertTrue($this->Acl->allow('Micheal', 'printers', 'create')); - // Michael no longer has his delete permission for tpsReports! - $this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete')); - $this->assertTrue($this->Acl->check('Micheal', 'printers', 'create')); - - $this->assertFalse($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view')); - $this->assertTrue($this->Acl->allow('root/users/Samir', 'ROOT/tpsReports/view', '*')); - $this->assertTrue($this->Acl->check('Samir', 'view', 'read')); - $this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update')); - - $this->assertFalse($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/update', '*')); - $this->assertTrue($this->Acl->allow('root/users/Samir', 'ROOT/tpsReports/update', '*')); - $this->assertTrue($this->Acl->check('Samir', 'update', 'read')); - $this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/update', 'update')); - // Samir should still have his tpsReports/view permissions, but does not - $this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update')); - - $this->assertFalse($this->Acl->allow('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create')); - } - -/** - * Test that allow() with an invalid permission name triggers an error. - * - * @expectedException CakeException - * @return void - */ - public function testAllowInvalidPermission() { - $this->Acl->allow('Micheal', 'tpsReports', 'derp'); - } - -/** - * testAllowInvalidNode method - * - * @expectedException PHPUnit_Framework_Error_Warning - * @return void - */ - public function testAllowInvalidNode() { - $this->Acl->allow('Homer', 'tpsReports', 'create'); - } - -/** - * testDbAclCheck method - * - * @return void - */ - public function testCheck() { - $this->assertTrue($this->Acl->check('Samir', 'print', 'read')); - $this->assertTrue($this->Acl->check('Lumbergh', 'current', 'read')); - $this->assertFalse($this->Acl->check('Milton', 'smash', 'read')); - $this->assertFalse($this->Acl->check('Milton', 'current', 'update')); - - $this->assertFalse($this->Acl->check(null, 'printers', 'create')); - $this->assertFalse($this->Acl->check('managers', null, 'read')); - - $this->assertTrue($this->Acl->check('Bobs', 'ROOT/tpsReports/view/current', 'read')); - $this->assertFalse($this->Acl->check('Samir', 'ROOT/tpsReports/update', 'read')); - - $this->assertFalse($this->Acl->check('root/users/Milton', 'smash', 'delete')); - } - -/** - * testCheckInvalidNode method - * - * @expectedException PHPUnit_Framework_Error_Warning - * @return void - */ - public function testCheckInvalidNode() { - $this->assertFalse($this->Acl->check('WRONG', 'tpsReports', 'read')); - } - -/** - * testCheckInvalidPermission method - * - * @expectedException PHPUnit_Framework_Error_Notice - * @return void - */ - public function testCheckInvalidPermission() { - $this->Acl->check('Lumbergh', 'smash', 'foobar'); - } - -/** - * testCheckMissingPermission method - * - * @expectedException PHPUnit_Framework_Error_Warning - * @return void - */ - public function testCheckMissingPermission() { - $this->Acl->check('users', 'NonExistent', 'read'); - } - -/** - * testDbAclCascadingDeny function - * - * Setup the acl permissions such that Bobs inherits from admin. - * deny Admin delete access to a specific resource, check the permissions are inherited. - * - * @return void - */ - public function testAclCascadingDeny() { - $this->Acl->inherit('Bobs', 'ROOT', '*'); - $this->assertTrue($this->Acl->check('admin', 'tpsReports', 'delete')); - $this->assertTrue($this->Acl->check('Bobs', 'tpsReports', 'delete')); - $this->Acl->deny('admin', 'tpsReports', 'delete'); - $this->assertFalse($this->Acl->check('admin', 'tpsReports', 'delete')); - $this->assertFalse($this->Acl->check('Bobs', 'tpsReports', 'delete')); - } - -/** - * testDbAclDeny method - * - * @expectedException PHPUnit_Framework_Error_Warning - * @return void - */ - public function testDeny() { - $this->assertTrue($this->Acl->check('Micheal', 'smash', 'delete')); - $this->Acl->deny('Micheal', 'smash', 'delete'); - $this->assertFalse($this->Acl->check('Micheal', 'smash', 'delete')); - $this->assertTrue($this->Acl->check('Micheal', 'smash', 'read')); - $this->assertTrue($this->Acl->check('Micheal', 'smash', 'create')); - $this->assertTrue($this->Acl->check('Micheal', 'smash', 'update')); - $this->assertFalse($this->Acl->check('Micheal', 'smash', '*')); - - $this->assertTrue($this->Acl->check('Samir', 'refill', '*')); - $this->Acl->deny('Samir', 'refill', '*'); - $this->assertFalse($this->Acl->check('Samir', 'refill', 'create')); - $this->assertFalse($this->Acl->check('Samir', 'refill', 'update')); - $this->assertFalse($this->Acl->check('Samir', 'refill', 'read')); - $this->assertFalse($this->Acl->check('Samir', 'refill', 'delete')); - - $result = $this->Acl->Aro->Permission->find('all', array('conditions' => array('AroTwoTest.alias' => 'Samir'))); - $expected = '-1'; - $this->assertEquals($expected, $result[0]['PermissionTwoTest']['_delete']); - - $this->assertFalse($this->Acl->deny('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create')); - } - -/** - * testAclNodeLookup method - * - * @return void - */ - public function testAclNodeLookup() { - $result = $this->Acl->Aro->node('root/users/Samir'); - $expected = array( - array('AroTwoTest' => array('id' => '7', 'parent_id' => '4', 'model' => 'User', 'foreign_key' => 3, 'alias' => 'Samir')), - array('AroTwoTest' => array('id' => '4', 'parent_id' => '1', 'model' => 'Group', 'foreign_key' => 3, 'alias' => 'users')), - array('AroTwoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'root')) - ); - $this->assertEquals($expected, $result); - - $result = $this->Acl->Aco->node('ROOT/tpsReports/view/current'); - $expected = array( - array('AcoTwoTest' => array('id' => '4', 'parent_id' => '3', 'model' => null, 'foreign_key' => null, 'alias' => 'current')), - array('AcoTwoTest' => array('id' => '3', 'parent_id' => '2', 'model' => null, 'foreign_key' => null, 'alias' => 'view')), - array('AcoTwoTest' => array('id' => '2', 'parent_id' => '1', 'model' => null, 'foreign_key' => null, 'alias' => 'tpsReports')), - array('AcoTwoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'ROOT')), - ); - $this->assertEquals($expected, $result); - } - -/** - * testDbInherit method - * - * @return void - */ - public function testInherit() { - //parent doesn't have access inherit should still deny - $this->assertFalse($this->Acl->check('Milton', 'smash', 'delete')); - $this->Acl->inherit('Milton', 'smash', 'delete'); - $this->assertFalse($this->Acl->check('Milton', 'smash', 'delete')); - - //inherit parent - $this->assertFalse($this->Acl->check('Milton', 'smash', 'read')); - $this->Acl->inherit('Milton', 'smash', 'read'); - $this->assertTrue($this->Acl->check('Milton', 'smash', 'read')); - } - -/** - * testDbGrant method - * - * @expectedException PHPUnit_Framework_Error_Warning - * @return void - */ - public function testGrant() { - $this->assertFalse($this->Acl->check('Samir', 'tpsReports', 'create')); - $this->Acl->allow('Samir', 'tpsReports', 'create'); - $this->assertTrue($this->Acl->check('Samir', 'tpsReports', 'create')); - - $this->assertFalse($this->Acl->check('Micheal', 'view', 'read')); - $this->Acl->allow('Micheal', 'view', array('read', 'create', 'update')); - $this->assertTrue($this->Acl->check('Micheal', 'view', 'read')); - $this->assertTrue($this->Acl->check('Micheal', 'view', 'create')); - $this->assertTrue($this->Acl->check('Micheal', 'view', 'update')); - $this->assertFalse($this->Acl->check('Micheal', 'view', 'delete')); - - $this->assertFalse($this->Acl->allow('Peter', 'ROOT/tpsReports/DoesNotExist', 'create')); - } - -/** - * testDbRevoke method - * - * @expectedException PHPUnit_Framework_Error_Warning - * @return void - */ - public function testRevoke() { - $this->assertTrue($this->Acl->check('Bobs', 'tpsReports', 'read')); - $this->Acl->deny('Bobs', 'tpsReports', 'read'); - $this->assertFalse($this->Acl->check('Bobs', 'tpsReports', 'read')); - - $this->assertTrue($this->Acl->check('users', 'printers', 'read')); - $this->Acl->deny('users', 'printers', 'read'); - $this->assertFalse($this->Acl->check('users', 'printers', 'read')); - $this->assertFalse($this->Acl->check('Samir', 'printers', 'read')); - $this->assertFalse($this->Acl->check('Peter', 'printers', 'read')); - - $this->Acl->deny('Bobs', 'ROOT/printers/DoesNotExist', 'create'); - } - -/** - * debug function - to help editing/creating test cases for the ACL component - * - * To check the overall ACL status at any time call $this->_debug(); - * Generates a list of the current aro and aco structures and a grid dump of the permissions that are defined - * Only designed to work with the db based ACL - * - * @param boolean $treesToo - * @return void - */ - protected function _debug($printTreesToo = false) { - $this->Acl->Aro->displayField = 'alias'; - $this->Acl->Aco->displayField = 'alias'; - $aros = $this->Acl->Aro->find('list', array('order' => 'lft')); - $acos = $this->Acl->Aco->find('list', array('order' => 'lft')); - $rights = array('*', 'create', 'read', 'update', 'delete'); - $permissions['Aros v Acos >'] = $acos; - foreach ($aros as $aro) { - $row = array(); - foreach ($acos as $aco) { - $perms = ''; - foreach ($rights as $right) { - if ($this->Acl->check($aro, $aco, $right)) { - if ($right === '*') { - $perms .= '****'; - break; - } - $perms .= $right[0]; - } elseif ($right !== '*') { - $perms .= ' '; - } - } - $row[] = $perms; - } - $permissions[$aro] = $row; - } - foreach ($permissions as $key => $values) { - array_unshift($values, $key); - $values = array_map(array(&$this, '_pad'), $values); - $permissions[$key] = implode(' ', $values); - } - $permissions = array_map(array(&$this, '_pad'), $permissions); - array_unshift($permissions, 'Current Permissions :'); - if ($printTreesToo) { - debug(array('aros' => $this->Acl->Aro->generateTreeList(), 'acos' => $this->Acl->Aco->generateTreeList())); - } - debug(implode("\r\n", $permissions)); - } - -/** - * pad function - * Used by debug to format strings used in the data dump - * - * @param string $string - * @param integer $len - * @return void - */ - protected function _pad($string = '', $len = 14) { - return str_pad($string, $len); - } -} diff --git a/Cake/Test/TestCase/Controller/ScaffoldTest.php b/Cake/Test/TestCase/Controller/ScaffoldTest.php deleted file mode 100644 index e40d9af606f..00000000000 --- a/Cake/Test/TestCase/Controller/ScaffoldTest.php +++ /dev/null @@ -1,332 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.5436 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Controller; - -use Cake\Controller\Controller; -use Cake\Controller\Scaffold; -use Cake\Core\Plugin; -use Cake\Network\Request; -use Cake\Routing\Router; -use Cake\TestSuite\TestCase; - -require_once dirname(__DIR__) . DS . 'Model/models.php'; -class_alias('Cake\Test\TestCase\Model\ScaffoldMock', 'Cake\Model\ScaffoldMock'); - -/** - * ScaffoldMockController class - * - */ -class ScaffoldMockController extends Controller { - -/** - * scaffold property - * - * @var mixed - */ - public $scaffold; -} - -/** - * ScaffoldMockControllerWithFields class - * - */ -class ScaffoldMockControllerWithFields extends Controller { - -/** - * name property - * - * @var string - */ - public $name = 'ScaffoldMock'; - -/** - * scaffold property - * - * @var mixed - */ - public $scaffold; - -/** - * function beforeScaffold - * - * @param string method - */ - public function beforeScaffold($method) { - $this->set('scaffoldFields', array('title')); - return true; - } - -} - -/** - * TestScaffoldMock class - * - */ -class TestScaffoldMock extends Scaffold { - -/** - * Overload _scaffold - * - * @param unknown_type $params - */ - protected function _scaffold(Request $request) { - $this->_params = $request; - } - -/** - * Get Params from the Controller. - * - * @return unknown - */ - public function getParams() { - return $this->_params; - } - -} - -/** - * Scaffold Test class - * - */ -class ScaffoldTest extends TestCase { - -/** - * Controller property - * - * @var SecurityTestController - */ - public $Controller; - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array('core.article', 'core.user', 'core.comment', 'core.join_thing', 'core.tag'); - -/** - * setUp method - * - * @return void - */ - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Need to revisit once models work again.'); - Configure::write('Config.language', 'eng'); - $request = new Request(); - $this->Controller = new ScaffoldMockController($request); - $this->Controller->response = $this->getMock('Cake\Network\Response', array('_sendHeader')); - } - -/** - * tearDown method - * - * @return void - */ - public function tearDown() { - parent::tearDown(); - unset($this->Controller); - } - -/** - * Test the correct Generation of Scaffold Params. - * This ensures that the correct action and view will be generated - * - * @return void - */ - public function testScaffoldParams() { - $params = array( - 'plugin' => null, - 'pass' => array(), - 'controller' => 'scaffold_mock', - 'action' => 'admin_edit', - 'admin' => true, - ); - $this->Controller->request->base = ''; - $this->Controller->request->webroot = '/'; - $this->Controller->request->here = '/admin/scaffold_mock/edit'; - $this->Controller->request->addParams($params); - - //set router. - Router::setRequestInfo($this->Controller->request); - - $this->Controller->constructClasses(); - $Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request); - $result = $Scaffold->getParams(); - $this->assertEquals('admin_edit', $result['action']); - } - -/** - * test that the proper names and variable values are set by Scaffold - * - * @return void - */ - public function testScaffoldVariableSetting() { - $params = array( - 'plugin' => null, - 'pass' => array(), - 'controller' => 'scaffold_mock', - 'action' => 'admin_edit', - 'admin' => true, - ); - $this->Controller->request->base = ''; - $this->Controller->request->webroot = '/'; - $this->Controller->request->here = '/admin/scaffold_mock/edit'; - $this->Controller->request->addParams($params); - - //set router. - Router::setRequestInfo($this->Controller->request); - - $this->Controller->constructClasses(); - $Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request); - $result = $Scaffold->controller->viewVars; - - $this->assertEquals('Scaffold :: Admin Edit :: Scaffold Mock', $result['title_for_layout']); - $this->assertEquals('Scaffold Mock', $result['singularHumanName']); - $this->assertEquals('Scaffold Mock', $result['pluralHumanName']); - $this->assertEquals('ScaffoldMock', $result['modelClass']); - $this->assertEquals('id', $result['primaryKey']); - $this->assertEquals('title', $result['displayField']); - $this->assertEquals('scaffoldMock', $result['singularVar']); - $this->assertEquals('scaffoldMock', $result['pluralVar']); - $this->assertEquals(array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated'), $result['scaffoldFields']); - $this->assertArrayHasKey('plugin', $result['associations']['belongsTo']['User']); - } - -/** - * test that Scaffold overrides the view property even if its set to 'Theme' - * - * @return void - */ - public function testScaffoldChangingViewProperty() { - $this->Controller->action = 'edit'; - $this->Controller->theme = 'TestTheme'; - $this->Controller->viewClass = 'Theme'; - $this->Controller->constructClasses(); - new TestScaffoldMock($this->Controller, $this->Controller->request); - - $this->assertEquals('Scaffold', $this->Controller->viewClass); - } - -/** - * test that scaffold outputs flash messages when sessions are unset. - * - * @return void - */ - public function testScaffoldFlashMessages() { - $params = array( - 'plugin' => null, - 'pass' => array(1), - 'url' => array('url' => 'scaffold_mock'), - 'controller' => 'scaffold_mock', - 'action' => 'edit', - ); - $this->Controller->request->base = ''; - $this->Controller->request->webroot = '/'; - $this->Controller->request->here = '/scaffold_mock/edit'; - $this->Controller->request->addParams($params); - - //set router. - Router::reload(); - Router::setRequestInfo($this->Controller->request); - $this->Controller->request->data = array( - 'ScaffoldMock' => array( - 'id' => 1, - 'title' => 'New title', - 'body' => 'new body' - ) - ); - $this->Controller->constructClasses(); - unset($this->Controller->Session); - - ob_start(); - new Scaffold($this->Controller, $this->Controller->request); - $this->Controller->response->send(); - $result = ob_get_clean(); - $this->assertRegExp('/Scaffold Mock has been updated/', $result); - } - -/** - * test that habtm relationship keys get added to scaffoldFields. - * - * @return void - */ - public function testHabtmFieldAdditionWithScaffoldForm() { - Plugin::unload(); - $params = array( - 'plugin' => null, - 'pass' => array(1), - 'url' => array('url' => 'scaffold_mock'), - 'controller' => 'scaffold_mock', - 'action' => 'edit', - ); - $this->Controller->request->base = ''; - $this->Controller->request->webroot = '/'; - $this->Controller->request->here = '/scaffold_mock/edit'; - $this->Controller->request->addParams($params); - - //set router. - Router::reload(); - Router::setRequestInfo($this->Controller->request); - - $this->Controller->constructClasses(); - ob_start(); - $Scaffold = new Scaffold($this->Controller, $this->Controller->request); - $this->Controller->response->send(); - $result = ob_get_clean(); - $this->assertContains('name="ScaffoldTag[ScaffoldTag]"', $result); - - $result = $Scaffold->controller->viewVars; - $this->assertEquals(array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated', 'ScaffoldTag'), $result['scaffoldFields']); - } - -/** - * test that the proper names and variable values are set by Scaffold - * - * @return void - */ - public function testEditScaffoldWithScaffoldFields() { - $request = new Request(); - $this->Controller = new ScaffoldMockControllerWithFields($request); - $this->Controller->response = $this->getMock('Cake\Network\Response', array('_sendHeader')); - - $params = array( - 'plugin' => null, - 'pass' => array(1), - 'url' => array('url' => 'scaffold_mock/edit'), - 'controller' => 'scaffold_mock', - 'action' => 'edit', - ); - $this->Controller->request->base = ''; - $this->Controller->request->webroot = '/'; - $this->Controller->request->here = '/scaffold_mock/edit'; - $this->Controller->request->addParams($params); - - //set router. - Router::reload(); - Router::setRequestInfo($this->Controller->request); - - $this->Controller->constructClasses(); - ob_start(); - new Scaffold($this->Controller, $this->Controller->request); - $this->Controller->response->send(); - $result = ob_get_clean(); - - $this->assertNotRegExp('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result); - } - -} diff --git a/Cake/Test/TestCase/Core/ObjectTest.php b/Cake/Test/TestCase/Core/ObjectTest.php index 3cf684cb0be..2b7e6da9324 100644 --- a/Cake/Test/TestCase/Core/ObjectTest.php +++ b/Cake/Test/TestCase/Core/ObjectTest.php @@ -23,7 +23,6 @@ use Cake\Core\Plugin; use Cake\Log\Log; use Cake\Routing\Router; -use Cake\TestSuite\Fixture\TestModel; use Cake\TestSuite\TestCase; /** @@ -159,18 +158,6 @@ public function set($properties = array()) { } -/** - * ObjectTestModel class - * - */ -class ObjectTestModel extends TestModel { - - public $useTable = false; - - public $name = 'ObjectTestModel'; - -} - /** * Object Test class * diff --git a/Cake/Test/TestCase/Error/ExceptionRendererTest.php b/Cake/Test/TestCase/Error/ExceptionRendererTest.php index e06655f463b..5fe5f8bfedc 100644 --- a/Cake/Test/TestCase/Error/ExceptionRendererTest.php +++ b/Cake/Test/TestCase/Error/ExceptionRendererTest.php @@ -25,23 +25,8 @@ use Cake\Event\Event; use Cake\Network\Request; use Cake\Routing\Router; -use Cake\TestSuite\Fixture\TestModel; use Cake\TestSuite\TestCase; -/** - * Short description for class. - * - */ -class AuthBlueberryUser extends TestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = false; -} - /** * BlueberryComponent class * diff --git a/Cake/Test/TestCase/Model/AclNodeTest.php b/Cake/Test/TestCase/Model/AclNodeTest.php deleted file mode 100644 index 0384609bb20..00000000000 --- a/Cake/Test/TestCase/Model/AclNodeTest.php +++ /dev/null @@ -1,348 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Controller\Component\Acl\DbAcl; -use Cake\Core\App; -use Cake\Model\AclNode; -use Cake\TestSuite\TestCase; - -/** - * DB ACL wrapper test class - * - */ -class DbAclNodeTestBase extends AclNode { - -/** - * useDbConfig property - * - * @var string - */ - public $useDbConfig = 'test'; - -/** - * cacheSources property - * - * @var boolean - */ - public $cacheSources = false; -} - -/** - * Aro Test Wrapper - * - */ -class DbAroTest extends DbAclNodeTestBase { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'aros'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('DbAcoTest' => array('with' => 'DbPermissionTest')); -} - -/** - * Aco Test Wrapper - * - */ -class DbAcoTest extends DbAclNodeTestBase { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'acos'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('DbAroTest' => array('with' => 'DbPermissionTest')); -} - -/** - * Permission Test Wrapper - * - */ -class DbPermissionTest extends TestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'aros_acos'; - -/** - * cacheQueries property - * - * @var boolean - */ - public $cacheQueries = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('DbAroTest' => array('foreignKey' => 'aro_id'), 'DbAcoTest' => array('foreignKey' => 'aco_id')); -} - -/** - * DboActionTest class - * - */ -class DbAcoActionTest extends TestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'aco_actions'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('DbAcoTest' => array('foreignKey' => 'aco_id')); -} - -/** - * DbAroUserTest class - * - */ -class DbAroUserTest extends TestModel { - -/** - * name property - * - * @var string - */ - public $name = 'AuthUser'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'auth_users'; - -/** - * bindNode method - * - * @param string|array|Model $ref - * @return void - */ - public function bindNode($ref = null) { - if (Configure::read('DbAclbindMode') === 'string') { - return 'ROOT/admins/Gandalf'; - } elseif (Configure::read('DbAclbindMode') === 'array') { - return array('DbAroTest' => array('DbAroTest.model' => 'AuthUser', 'DbAroTest.foreign_key' => 2)); - } - } - -} - -/** - * TestDbAcl class - * - */ -class TestDbAcl extends DbAcl { - -/** - * construct method - * - */ - public function __construct() { - $this->Aro = new DbAroTest(); - $this->Aro->Permission = new DbPermissionTest(); - $this->Aco = new DbAcoTest(); - $this->Aro->Permission = new DbPermissionTest(); - } - -} - -/** - * AclNodeTest class - * - */ -class AclNodeTest extends TestCase { - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array('core.aro', 'core.aco', 'core.aros_aco', 'core.aco_action', 'core.auth_user'); - -/** - * setUp method - * - * @return void - */ - public function setUp() { - $this->markTestIncomplete('Not runnable until Models are fixed.'); - parent::setUp(); - Configure::write('Acl.classname', 'TestDbAcl'); - Configure::write('Acl.database', 'test'); - } - -/** - * testNode method - * - * @return void - */ - public function testNode() { - $Aco = new DbAcoTest(); - $result = Hash::extract($Aco->node('Controller1'), '{n}.DbAcoTest.id'); - $expected = array(2, 1); - $this->assertEquals($expected, $result); - - $result = Hash::extract($Aco->node('Controller1/action1'), '{n}.DbAcoTest.id'); - $expected = array(3, 2, 1); - $this->assertEquals($expected, $result); - - $result = Hash::extract($Aco->node('Controller2/action1'), '{n}.DbAcoTest.id'); - $expected = array(7, 6, 1); - $this->assertEquals($expected, $result); - - $result = Hash::extract($Aco->node('Controller1/action2'), '{n}.DbAcoTest.id'); - $expected = array(5, 2, 1); - $this->assertEquals($expected, $result); - - $result = Hash::extract($Aco->node('Controller1/action1/record1'), '{n}.DbAcoTest.id'); - $expected = array(4, 3, 2, 1); - $this->assertEquals($expected, $result); - - $result = Hash::extract($Aco->node('Controller2/action1/record1'), '{n}.DbAcoTest.id'); - $expected = array(8, 7, 6, 1); - $this->assertEquals($expected, $result); - - $this->assertFalse($Aco->node('Controller2/action3')); - - $this->assertFalse($Aco->node('Controller2/action3/record5')); - - $result = $Aco->node(''); - $this->assertEquals(null, $result); - } - -/** - * test that node() doesn't dig deeper than it should. - * - * @return void - */ - public function testNodeWithDuplicatePathSegments() { - $Aco = new DbAcoTest(); - $nodes = $Aco->node('ROOT/Users'); - $this->assertEquals(1, $nodes[0]['DbAcoTest']['parent_id'], 'Parent id does not point at ROOT. %s'); - } - -/** - * testNodeArrayFind method - * - * @return void - */ - public function testNodeArrayFind() { - $Aro = new DbAroTest(); - Configure::write('DbAclbindMode', 'string'); - $result = Hash::extract($Aro->node(array('DbAroUserTest' => array('id' => '1', 'foreign_key' => '1'))), '{n}.DbAroTest.id'); - $expected = array(3, 2, 1); - $this->assertEquals($expected, $result); - - Configure::write('DbAclbindMode', 'array'); - $result = Hash::extract($Aro->node(array('DbAroUserTest' => array('id' => 4, 'foreign_key' => 2))), '{n}.DbAroTest.id'); - $expected = array(4); - $this->assertEquals($expected, $result); - } - -/** - * testNodeObjectFind method - * - * @return void - */ - public function testNodeObjectFind() { - $Aro = new DbAroTest(); - $Model = new DbAroUserTest(); - $Model->id = 1; - $result = Hash::extract($Aro->node($Model), '{n}.DbAroTest.id'); - $expected = array(3, 2, 1); - $this->assertEquals($expected, $result); - - $Model->id = 2; - $result = Hash::extract($Aro->node($Model), '{n}.DbAroTest.id'); - $expected = array(4, 2, 1); - $this->assertEquals($expected, $result); - } - -/** - * testNodeAliasParenting method - * - * @return void - */ - public function testNodeAliasParenting() { - $Aco = ClassRegistry::init('DbAcoTest'); - $db = $Aco->getDataSource(); - $db->truncate($Aco); - - $Aco->create(array('model' => null, 'foreign_key' => null, 'parent_id' => null, 'alias' => 'Application')); - $Aco->save(); - - $Aco->create(array('model' => null, 'foreign_key' => null, 'parent_id' => $Aco->id, 'alias' => 'Pages')); - $Aco->save(); - - $result = $Aco->find('all'); - $expected = array( - array('DbAcoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'Application', 'lft' => '1', 'rght' => '4'), 'DbAroTest' => array()), - array('DbAcoTest' => array('id' => '2', 'parent_id' => '1', 'model' => null, 'foreign_key' => null, 'alias' => 'Pages', 'lft' => '2', 'rght' => '3'), 'DbAroTest' => array()) - ); - $this->assertEquals($expected, $result); - } - -/** - * testNodeActionAuthorize method - * - * @return void - */ - public function testNodeActionAuthorize() { - CakePlugin::load('TestPlugin'); - - $Aro = new DbAroTest(); - $Aro->create(); - $Aro->save(array('model' => 'TestPluginAuthUser', 'foreign_key' => 1)); - $result = $Aro->id; - $expected = 5; - $this->assertEquals($expected, $result); - - $node = $Aro->node(array('TestPlugin.TestPluginAuthUser' => array('id' => 1, 'user' => 'mariano'))); - $result = Hash::get($node, '0.DbAroTest.id'); - $expected = $Aro->id; - $this->assertEquals($expected, $result); - CakePlugin::unload('TestPlugin'); - } -} diff --git a/Cake/Test/TestCase/Model/Behavior/AclBehaviorTest.php b/Cake/Test/TestCase/Model/Behavior/AclBehaviorTest.php deleted file mode 100644 index 2b35230fa79..00000000000 --- a/Cake/Test/TestCase/Model/Behavior/AclBehaviorTest.php +++ /dev/null @@ -1,479 +0,0 @@ - 'both'); - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'Mother' => array( - 'className' => 'AclPerson', - 'foreignKey' => 'mother_id', - ) - ); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'Child' => array( - 'className' => 'AclPerson', - 'foreignKey' => 'mother_id' - ) - ); - -/** - * parentNode method - * - * @return void - */ - public function parentNode() { - if (!$this->id && empty($this->data)) { - return null; - } - if (isset($this->data['AclPerson']['mother_id'])) { - $motherId = $this->data['AclPerson']['mother_id']; - } else { - $motherId = $this->field('mother_id'); - } - if (!$motherId) { - return null; - } - return array('AclPerson' => array('id' => $motherId)); - } - -} - -/** - * AclUser class - * - */ -class AclUser extends TestModel { - -/** - * name property - * - * @var string - */ - public $name = 'User'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'users'; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Acl' => array('type' => 'requester')); - -/** - * parentNode - * - */ - public function parentNode() { - return null; - } - -} - -/** - * AclPost class - */ -class AclPost extends TestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Post'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'posts'; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Acl' => array('type' => 'Controlled')); - -/** - * parentNode - * - */ - public function parentNode() { - return null; - } - -} - -/** - * AclBehaviorTest class - */ -class AclBehaviorTest extends TestCase { - -/** - * Aco property - * - * @var Aco - */ - public $Aco; - -/** - * Aro property - * - * @var Aro - */ - public $Aro; - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array('core.person', 'core.user', 'core.post', 'core.aco', 'core.aro', 'core.aros_aco'); - -/** - * Set up the test - * - * @return void - */ - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Not runnable until Models are fixed.'); - Configure::write('Acl.database', 'test'); - - $this->Aco = new Aco(); - $this->Aro = new Aro(); - } - -/** - * tearDown method - * - * @return void - */ - public function tearDown() { - parent::tearDown(); - unset($this->Aro, $this->Aco); - } - -/** - * Test Setup of AclBehavior - * - * @return void - */ - public function testSetup() { - parent::setUp(); - $User = new AclUser(); - $this->assertTrue(isset($User->Behaviors->Acl->settings['User'])); - $this->assertEquals('requester', $User->Behaviors->Acl->settings['User']['type']); - $this->assertTrue(is_object($User->Aro)); - - $Post = new AclPost(); - $this->assertTrue(isset($Post->Behaviors->Acl->settings['Post'])); - $this->assertEquals('controlled', $Post->Behaviors->Acl->settings['Post']['type']); - $this->assertTrue(is_object($Post->Aco)); - } - -/** - * Test Setup of AclBehavior as both requester and controlled - * - * @return void - */ - public function testSetupMulti() { - $User = new AclPerson(); - $this->assertTrue(isset($User->Behaviors->Acl->settings['AclPerson'])); - $this->assertEquals('both', $User->Behaviors->Acl->settings['AclPerson']['type']); - $this->assertTrue(is_object($User->Aro)); - $this->assertTrue(is_object($User->Aco)); - } - -/** - * test After Save - * - * @return void - */ - public function testAfterSave() { - $Post = new AclPost(); - $data = array( - 'Post' => array( - 'author_id' => 1, - 'title' => 'Acl Post', - 'body' => 'post body', - 'published' => 1 - ), - ); - $Post->save($data); - $result = $this->Aco->find('first', array( - 'conditions' => array('Aco.model' => 'Post', 'Aco.foreign_key' => $Post->id) - )); - $this->assertTrue(is_array($result)); - $this->assertEquals('Post', $result['Aco']['model']); - $this->assertEquals($Post->id, $result['Aco']['foreign_key']); - - $aroData = array( - 'Aro' => array( - 'model' => 'AclPerson', - 'foreign_key' => 2, - 'parent_id' => null - ) - ); - $this->Aro->save($aroData); - - $acoData = array( - 'Aco' => array( - 'model' => 'AclPerson', - 'foreign_key' => 2, - 'parent_id' => null - ) - ); - $this->Aco->save($acoData); - - $Person = new AclPerson(); - $data = array( - 'AclPerson' => array( - 'name' => 'Trent', - 'mother_id' => 2, - 'father_id' => 3, - ), - ); - $Person->save($data); - $result = $this->Aro->find('first', array( - 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id) - )); - $this->assertTrue(is_array($result)); - $this->assertEquals(5, $result['Aro']['parent_id']); - - $node = $Person->node(array('model' => 'AclPerson', 'foreign_key' => 8), 'Aro'); - $this->assertEquals(2, count($node)); - $this->assertEquals(5, $node[0]['Aro']['parent_id']); - $this->assertEquals(null, $node[1]['Aro']['parent_id']); - - $aroData = array( - 'Aro' => array( - 'model' => 'AclPerson', - 'foreign_key' => 1, - 'parent_id' => null - ) - ); - $this->Aro->create(); - $this->Aro->save($aroData); - $acoData = array( - 'Aco' => array( - 'model' => 'AclPerson', - 'foreign_key' => 1, - 'parent_id' => null - )); - $this->Aco->create(); - $this->Aco->save($acoData); - $Person->read(null, 8); - $Person->set('mother_id', 1); - $Person->save(); - $result = $this->Aro->find('first', array( - 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id) - )); - $this->assertTrue(is_array($result)); - $this->assertEquals(7, $result['Aro']['parent_id']); - - $node = $Person->node(array('model' => 'AclPerson', 'foreign_key' => 8), 'Aro'); - $this->assertEquals(2, count($node)); - $this->assertEquals(7, $node[0]['Aro']['parent_id']); - $this->assertEquals(null, $node[1]['Aro']['parent_id']); - } - -/** - * test that an afterSave on an update does not cause parent_id to become null. - * - * @return void - */ - public function testAfterSaveUpdateParentIdNotNull() { - $aroData = array( - 'Aro' => array( - 'model' => 'AclPerson', - 'foreign_key' => 2, - 'parent_id' => null - ) - ); - $this->Aro->save($aroData); - - $acoData = array( - 'Aco' => array( - 'model' => 'AclPerson', - 'foreign_key' => 2, - 'parent_id' => null - ) - ); - $this->Aco->save($acoData); - - $Person = new AclPerson(); - $data = array( - 'AclPerson' => array( - 'name' => 'Trent', - 'mother_id' => 2, - 'father_id' => 3, - ), - ); - $Person->save($data); - $result = $this->Aro->find('first', array( - 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id) - )); - $this->assertTrue(is_array($result)); - $this->assertEquals(5, $result['Aro']['parent_id']); - - $Person->save(array('id' => $Person->id, 'name' => 'Bruce')); - $result = $this->Aro->find('first', array( - 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id) - )); - $this->assertEquals(5, $result['Aro']['parent_id']); - } - -/** - * Test After Delete - * - * @return void - */ - public function testAfterDelete() { - $aroData = array( - 'Aro' => array( - 'model' => 'AclPerson', - 'foreign_key' => 2, - 'parent_id' => null - ) - ); - $this->Aro->save($aroData); - - $acoData = array( - 'Aco' => array( - 'model' => 'AclPerson', - 'foreign_key' => 2, - 'parent_id' => null - ) - ); - $this->Aco->save($acoData); - $Person = new AclPerson(); - - $data = array( - 'AclPerson' => array( - 'name' => 'Trent', - 'mother_id' => 2, - 'father_id' => 3, - ), - ); - $Person->save($data); - $id = $Person->id; - $node = $Person->node(null, 'Aro'); - $this->assertEquals(2, count($node)); - $this->assertEquals(5, $node[0]['Aro']['parent_id']); - $this->assertEquals(null, $node[1]['Aro']['parent_id']); - - $Person->delete($id); - $result = $this->Aro->find('first', array( - 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $id) - )); - $this->assertTrue(empty($result)); - $result = $this->Aro->find('first', array( - 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => 2) - )); - $this->assertFalse(empty($result)); - - $data = array( - 'AclPerson' => array( - 'name' => 'Trent', - 'mother_id' => 2, - 'father_id' => 3, - ), - ); - $Person->save($data); - $id = $Person->id; - $Person->delete(2); - $result = $this->Aro->find('first', array( - 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $id) - )); - $this->assertTrue(empty($result)); - - $result = $this->Aro->find('first', array( - 'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => 2) - )); - $this->assertTrue(empty($result)); - } - -/** - * Test Node() - * - * @return void - */ - public function testNode() { - $Person = new AclPerson(); - $aroData = array( - 'Aro' => array( - 'model' => 'AclPerson', - 'foreign_key' => 2, - 'parent_id' => null - ) - ); - $this->Aro->save($aroData); - - $Person->id = 2; - $result = $Person->node(null, 'Aro'); - $this->assertTrue(is_array($result)); - $this->assertEquals(1, count($result)); - } -} diff --git a/Cake/Test/TestCase/Model/Behavior/TranslateBehaviorTest.php b/Cake/Test/TestCase/Model/Behavior/TranslateBehaviorTest.php deleted file mode 100644 index 644d289940f..00000000000 --- a/Cake/Test/TestCase/Model/Behavior/TranslateBehaviorTest.php +++ /dev/null @@ -1,1269 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.5669 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model\Behavior; - -use Cake\Model\Model; -use Cake\TestSuite\TestCase; - -require_once dirname(__DIR__) . DS . 'models.php'; - -/** - * TranslateBehaviorTest class - * - */ -class TranslateBehaviorTest extends TestCase { - -/** - * autoFixtures property - * - * @var boolean - */ - public $autoFixtures = false; - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array( - 'core.translated_item', 'core.translate', 'core.translate_table', - 'core.translated_article', 'core.translate_article', 'core.user', 'core.comment', 'core.tag', 'core.articles_tag', - 'core.translate_with_prefix' - ); - - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Not runnable until Models are fixed.'); - } -/** - * Test that count queries with conditions get the correct joins - * - * @return void - */ - public function testCountWithConditions() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $Model = new TranslatedItem(); - $Model->locale = 'eng'; - $result = $Model->find('count', array( - 'conditions' => array( - 'I18n__content.locale' => 'eng' - ) - )); - $this->assertEquals(3, $result); - } - -/** - * testTranslateModel method - * - * @return void - */ - public function testTranslateModel() { - $this->loadFixtures('TranslateTable', 'Tag', 'TranslatedItem', 'Translate', 'User', 'TranslatedArticle', 'TranslateArticle'); - $TestModel = new Tag(); - $TestModel->translateTable = 'another_i18n'; - $TestModel->Behaviors->load('Translate', array('title')); - $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); - $this->assertEquals('I18nModel', $translateModel->name); - $this->assertEquals('another_i18n', $translateModel->useTable); - - $TestModel = new User(); - $TestModel->Behaviors->load('Translate', array('title')); - $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); - $this->assertEquals('I18nModel', $translateModel->name); - $this->assertEquals('i18n', $translateModel->useTable); - - $TestModel = new TranslatedArticle(); - $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); - $this->assertEquals('TranslateArticleModel', $translateModel->name); - $this->assertEquals('article_i18n', $translateModel->useTable); - - $TestModel = new TranslatedItem(); - $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); - $this->assertEquals('TranslateTestModel', $translateModel->name); - $this->assertEquals('i18n', $translateModel->useTable); - } - -/** - * testLocaleFalsePlain method - * - * @return void - */ - public function testLocaleFalsePlain() { - $this->loadFixtures('Translate', 'TranslatedItem', 'User'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = false; - - $result = $TestModel->read(null, 1); - $expected = array('TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'translated_article_id' => 1, - )); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('fields' => array('slug'))); - $expected = array( - array('TranslatedItem' => array('slug' => 'first_translated')), - array('TranslatedItem' => array('slug' => 'second_translated')), - array('TranslatedItem' => array('slug' => 'third_translated')) - ); - $this->assertEquals($expected, $result); - } - -/** - * testLocaleFalseAssociations method - * - * @return void - */ - public function testLocaleFalseAssociations() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = false; - $TestModel->unbindTranslation(); - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedItem' => array('id' => 1, 'slug' => 'first_translated', 'translated_article_id' => 1), - 'Title' => array( - array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Title #1'), - array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'), - array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1') - ), - 'Content' => array( - array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'), - array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'), - array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Obsah #1') - ) - ); - $this->assertEquals($expected, $result); - - $TestModel->hasMany['Title']['fields'] = $TestModel->hasMany['Content']['fields'] = array('content'); - $TestModel->hasMany['Title']['conditions']['locale'] = $TestModel->hasMany['Content']['conditions']['locale'] = 'eng'; - - $result = $TestModel->find('all', array('fields' => array('TranslatedItem.slug'))); - $expected = array( - array( - 'TranslatedItem' => array('id' => 1, 'slug' => 'first_translated'), - 'Title' => array(array('foreign_key' => 1, 'content' => 'Title #1')), - 'Content' => array(array('foreign_key' => 1, 'content' => 'Content #1')) - ), - array( - 'TranslatedItem' => array('id' => 2, 'slug' => 'second_translated'), - 'Title' => array(array('foreign_key' => 2, 'content' => 'Title #2')), - 'Content' => array(array('foreign_key' => 2, 'content' => 'Content #2')) - ), - array( - 'TranslatedItem' => array('id' => 3, 'slug' => 'third_translated'), - 'Title' => array(array('foreign_key' => 3, 'content' => 'Title #3')), - 'Content' => array(array('foreign_key' => 3, 'content' => 'Content #3')) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testLocaleSingle method - * - * @return void - */ - public function testLocaleSingle() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'eng'; - - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'eng', - 'title' => 'Title #1', - 'content' => 'Content #1', - 'translated_article_id' => 1, - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all'); - $expected = array( - array( - 'TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'eng', - 'title' => 'Title #1', - 'content' => 'Content #1', - 'translated_article_id' => 1, - ) - ), - array( - 'TranslatedItem' => array( - 'id' => 2, - 'slug' => 'second_translated', - 'locale' => 'eng', - 'title' => 'Title #2', - 'content' => 'Content #2', - 'translated_article_id' => 1, - ) - ), - array( - 'TranslatedItem' => array( - 'id' => 3, - 'slug' => 'third_translated', - 'locale' => 'eng', - 'title' => 'Title #3', - 'content' => 'Content #3', - 'translated_article_id' => 1, - ) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testLocaleSingleWithConditions method - * - * @return void - */ - public function testLocaleSingleWithConditions() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'eng'; - $result = $TestModel->find('all', array('conditions' => array('slug' => 'first_translated'))); - $expected = array( - array( - 'TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'eng', - 'title' => 'Title #1', - 'content' => 'Content #1', - 'translated_article_id' => 1, - ) - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('conditions' => "TranslatedItem.slug = 'first_translated'")); - $expected = array( - array( - 'TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'eng', - 'title' => 'Title #1', - 'content' => 'Content #1', - 'translated_article_id' => 1, - ) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testLocaleSingleAssociations method - * - * @return void - */ - public function testLocaleSingleAssociations() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'eng'; - $TestModel->unbindTranslation(); - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'eng', - 'title' => 'Title #1', - 'content' => 'Content #1', - 'translated_article_id' => 1, - ), - 'Title' => array( - array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Title #1'), - array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'), - array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1') - ), - 'Content' => array( - array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'), - array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'), - array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Obsah #1') - ) - ); - $this->assertEquals($expected, $result); - - $TestModel->hasMany['Title']['fields'] = $TestModel->hasMany['Content']['fields'] = array('content'); - $TestModel->hasMany['Title']['conditions']['locale'] = $TestModel->hasMany['Content']['conditions']['locale'] = 'eng'; - - $result = $TestModel->find('all', array('fields' => array('TranslatedItem.title'))); - $expected = array( - array( - 'TranslatedItem' => array( - 'id' => 1, - 'locale' => 'eng', - 'title' => 'Title #1', - 'slug' => 'first_translated', - 'translated_article_id' => 1, - ), - 'Title' => array(array('foreign_key' => 1, 'content' => 'Title #1')), - 'Content' => array(array('foreign_key' => 1, 'content' => 'Content #1')) - ), - array( - 'TranslatedItem' => array( - 'id' => 2, - 'locale' => 'eng', - 'title' => 'Title #2', - 'slug' => 'second_translated', - 'translated_article_id' => 1, - ), - 'Title' => array(array('foreign_key' => 2, 'content' => 'Title #2')), - 'Content' => array(array('foreign_key' => 2, 'content' => 'Content #2')) - ), - array( - 'TranslatedItem' => array( - 'id' => 3, - 'locale' => 'eng', - 'title' => 'Title #3', - 'slug' => 'third_translated', - 'translated_article_id' => 1, - ), - 'Title' => array(array('foreign_key' => 3, 'content' => 'Title #3')), - 'Content' => array(array('foreign_key' => 3, 'content' => 'Content #3')) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testLocaleMultiple method - * - * @return void - */ - public function testLocaleMultiple() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = array('deu', 'eng', 'cze'); - - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'deu', - 'title' => 'Titel #1', - 'content' => 'Inhalt #1', - 'translated_article_id' => 1, - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('fields' => array('slug', 'title', 'content'))); - $expected = array( - array( - 'TranslatedItem' => array( - 'slug' => 'first_translated', - 'locale' => 'deu', - 'content' => 'Inhalt #1', - 'title' => 'Titel #1', - ) - ), - array( - 'TranslatedItem' => array( - 'slug' => 'second_translated', - 'locale' => 'deu', - 'title' => 'Titel #2', - 'content' => 'Inhalt #2', - ) - ), - array( - 'TranslatedItem' => array( - 'slug' => 'third_translated', - 'locale' => 'deu', - 'title' => 'Titel #3', - 'content' => 'Inhalt #3', - ) - ) - ); - $this->assertEquals($expected, $result); - - $TestModel = new TranslatedItem(); - $TestModel->locale = array('pt-br'); - $result = $TestModel->find('all'); - $this->assertCount(3, $result, '3 records should have been found, no SQL error.'); - } - -/** - * testMissingTranslation method - * - * @return void - */ - public function testMissingTranslation() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'rus'; - $result = $TestModel->read(null, 1); - $this->assertSame(array(), $result); - - $TestModel->locale = array('rus'); - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'rus', - 'title' => '', - 'content' => '', - 'translated_article_id' => 1, - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testTranslatedFindList method - * - * @return void - */ - public function testTranslatedFindList() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'deu'; - $TestModel->displayField = 'title'; - $result = $TestModel->find('list', array('recursive' => 1)); - $expected = array(1 => 'Titel #1', 2 => 'Titel #2', 3 => 'Titel #3'); - $this->assertEquals($expected, $result); - - // SQL Server trigger an error and stops the page even if the debug = 0 - if ($this->db instanceof Sqlserver) { - $debug = Configure::read('debug'); - Configure::write('debug', 0); - - $result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => false)); - $this->assertSame(array(), $result); - - $result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'after')); - $this->assertSame(array(), $result); - Configure::write('debug', $debug); - } - - $result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'before')); - $expected = array(1 => null, 2 => null, 3 => null); - $this->assertEquals($expected, $result); - } - -/** - * testReadSelectedFields method - * - * @return void - */ - public function testReadSelectedFields() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'eng'; - $result = $TestModel->find('all', array('fields' => array('slug', 'TranslatedItem.content'))); - $expected = array( - array('TranslatedItem' => array('slug' => 'first_translated', 'locale' => 'eng', 'content' => 'Content #1')), - array('TranslatedItem' => array('slug' => 'second_translated', 'locale' => 'eng', 'content' => 'Content #2')), - array('TranslatedItem' => array('slug' => 'third_translated', 'locale' => 'eng', 'content' => 'Content #3')) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('fields' => array('TranslatedItem.slug', 'content'))); - $this->assertEquals($expected, $result); - - $TestModel->locale = array('eng', 'deu', 'cze'); - $delete = array(array('locale' => 'deu'), array('field' => 'content', 'locale' => 'eng')); - $I18nModel = ClassRegistry::getObject('TranslateTestModel'); - $I18nModel->deleteAll(array('or' => $delete)); - - $result = $TestModel->find('all', array('fields' => array('title', 'content'))); - $expected = array( - array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #1', 'content' => 'Obsah #1')), - array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #2', 'content' => 'Obsah #2')), - array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #3', 'content' => 'Obsah #3')) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveCreate method - * - * @return void - */ - public function testSaveCreate() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'spa'; - $data = array( - 'slug' => 'fourth_translated', - 'title' => 'Leyenda #4', - 'content' => 'Contenido #4', - 'translated_article_id' => 1, - ); - $TestModel->create($data); - $TestModel->save(); - $result = $TestModel->read(); - $expected = array('TranslatedItem' => array_merge($data, array('id' => $TestModel->id, 'locale' => 'spa'))); - $this->assertEquals($expected, $result); - } - -/** - * test saving/deleting with an alias, uses the model name. - * - * @return void - */ - public function testSaveDeleteIgnoreAlias() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(array('alias' => 'SomethingElse')); - $TestModel->locale = 'spa'; - $data = array( - 'slug' => 'fourth_translated', - 'title' => 'Leyenda #4', - 'content' => 'Contenido #4', - 'translated_article_id' => 1, - ); - $TestModel->create($data); - $TestModel->save(); - $id = $TestModel->id; - $result = $TestModel->read(); - $expected = array($TestModel->alias => array_merge($data, array('id' => $id, 'locale' => 'spa'))); - $this->assertEquals($expected, $result); - - $TestModel->delete($id); - $result = $TestModel->translateModel()->find('count', array( - 'conditions' => array('foreign_key' => $id) - )); - $this->assertEquals(0, $result); - } - -/** - * test save multiple locales method - * - * @return void - */ - public function testSaveMultipleLocales() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $data = array( - 'slug' => 'fourth_translated', - 'title' => array( - 'eng' => 'Title #4', - 'spa' => 'Leyenda #4', - ), - 'content' => array( - 'eng' => 'Content #4', - 'spa' => 'Contenido #4', - ), - 'translated_article_id' => 1, - ); - $TestModel->create(); - $TestModel->save($data); - - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - $TestModel->locale = array('eng', 'spa'); - $result = $TestModel->read(); - - $this->assertCount(2, $result['Title']); - $this->assertEquals($result['Title'][0]['locale'], 'eng'); - $this->assertEquals($result['Title'][0]['content'], 'Title #4'); - $this->assertEquals($result['Title'][1]['locale'], 'spa'); - $this->assertEquals($result['Title'][1]['content'], 'Leyenda #4'); - - $this->assertCount(2, $result['Content']); - } - -/** - * testSaveAssociatedCreate method - * - * @return void - */ - public function testSaveAssociatedMultipleLocale() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $data = array( - 'slug' => 'fourth_translated', - 'title' => array( - 'eng' => 'Title #4', - 'spa' => 'Leyenda #4', - ), - 'content' => array( - 'eng' => 'Content #4', - 'spa' => 'Contenido #4', - ), - 'translated_article_id' => 1, - ); - $TestModel->create(); - $TestModel->saveAssociated($data); - - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - $TestModel->locale = array('eng', 'spa'); - $result = $TestModel->read(); - $this->assertCount(2, $result['Title']); - $this->assertCount(2, $result['Content']); - } - -/** - * Test that saving only some of the translated fields allows the record to be found again. - * - * @return void - */ - public function testSavePartialFields() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'spa'; - $data = array( - 'slug' => 'fourth_translated', - 'title' => 'Leyenda #4', - ); - $TestModel->create($data); - $TestModel->save(); - $result = $TestModel->read(); - $expected = array( - 'TranslatedItem' => array( - 'id' => $TestModel->id, - 'translated_article_id' => null, - 'locale' => 'spa', - 'content' => '', - ) + $data - ); - $this->assertEquals($expected, $result); - } - -/** - * Test that all fields are create with partial data + multiple locales. - * - * @return void - */ - public function testSavePartialFieldMultipleLocales() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'eng'; - $data = array( - 'slug' => 'fifth_translated', - 'title' => array('eng' => 'Title #5', 'spa' => 'Leyenda #5'), - ); - $TestModel->create($data); - $TestModel->save(); - $TestModel->unbindTranslation(); - - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - $result = $TestModel->read(null, $TestModel->id); - $expected = array( - 'TranslatedItem' => array( - 'id' => '4', - 'translated_article_id' => null, - 'slug' => 'fifth_translated', - 'locale' => 'eng', - 'title' => 'Title #5', - 'content' => '' - ), - 'Title' => array( - 0 => array( - 'id' => '19', - 'locale' => 'eng', - 'model' => 'TranslatedItem', - 'foreign_key' => '4', - 'field' => 'title', - 'content' => 'Title #5' - ), - 1 => array( - 'id' => '20', - 'locale' => 'spa', - 'model' => 'TranslatedItem', - 'foreign_key' => '4', - 'field' => 'title', - 'content' => 'Leyenda #5' - ) - ), - 'Content' => array( - 0 => array( - 'id' => '21', - 'locale' => 'eng', - 'model' => 'TranslatedItem', - 'foreign_key' => '4', - 'field' => 'content', - 'content' => '' - ), - 1 => array( - 'id' => '22', - 'locale' => 'spa', - 'model' => 'TranslatedItem', - 'foreign_key' => '4', - 'field' => 'content', - 'content' => '' - ) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveUpdate method - * - * @return void - */ - public function testSaveUpdate() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'spa'; - $oldData = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4', 'translated_article_id' => 1); - $TestModel->create($oldData); - $TestModel->save(); - $id = $TestModel->id; - $newData = array('id' => $id, 'content' => 'Contenido #4'); - $TestModel->create($newData); - $TestModel->save(); - $result = $TestModel->read(null, $id); - $expected = array('TranslatedItem' => array_merge($oldData, $newData, array('locale' => 'spa'))); - $this->assertEquals($expected, $result); - } - -/** - * testMultipleCreate method - * - * @return void - */ - public function testMultipleCreate() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'deu'; - $data = array( - 'slug' => 'new_translated', - 'title' => array('eng' => 'New title', 'spa' => 'Nuevo leyenda'), - 'content' => array('eng' => 'New content', 'spa' => 'Nuevo contenido') - ); - $TestModel->create($data); - $TestModel->save(); - - $TestModel->unbindTranslation(); - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - $TestModel->locale = array('eng', 'spa'); - - $result = $TestModel->read(); - $expected = array( - 'TranslatedItem' => array( - 'id' => 4, - 'slug' => 'new_translated', - 'locale' => 'eng', - 'title' => 'New title', - 'content' => 'New content', - 'translated_article_id' => null, - ), - 'Title' => array( - array('id' => 21, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'title', 'content' => 'New title'), - array('id' => 22, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'title', 'content' => 'Nuevo leyenda') - ), - 'Content' => array( - array('id' => 19, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'content', 'content' => 'New content'), - array('id' => 20, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'content', 'content' => 'Nuevo contenido') - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testMultipleUpdate method - * - * @return void - */ - public function testMultipleUpdate() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'eng'; - $TestModel->validate['title'] = 'notEmpty'; - $data = array('TranslatedItem' => array( - 'id' => 1, - 'title' => array('eng' => 'New Title #1', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'), - 'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1') - )); - $TestModel->create(); - $TestModel->save($data); - - $TestModel->unbindTranslation(); - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedItem' => array( - 'id' => '1', - 'slug' => 'first_translated', - 'locale' => 'eng', - 'title' => 'New Title #1', - 'content' => 'New Content #1', - 'translated_article_id' => 1, - ), - 'Title' => array( - array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'New Title #1'), - array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Neue Titel #1'), - array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Novy Titulek #1') - ), - 'Content' => array( - array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'New Content #1'), - array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Neue Inhalt #1'), - array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Novy Obsah #1') - ) - ); - $this->assertEquals($expected, $result); - - $TestModel->unbindTranslation($translations); - $TestModel->bindTranslation(array('title', 'content'), false); - } - -/** - * testMixedCreateUpdateWithArrayLocale method - * - * @return void - */ - public function testMixedCreateUpdateWithArrayLocale() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = array('cze', 'deu'); - $data = array('TranslatedItem' => array( - 'id' => 1, - 'title' => array('eng' => 'Updated Title #1', 'spa' => 'Nuevo leyenda #1'), - 'content' => 'Upraveny obsah #1' - )); - $TestModel->create(); - $TestModel->save($data); - - $TestModel->unbindTranslation(); - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - $result = $TestModel->read(null, 1); - $result['Title'] = Hash::sort($result['Title'], '{n}.id', 'asc'); - $result['Content'] = Hash::sort($result['Content'], '{n}.id', 'asc'); - $expected = array( - 'TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'cze', - 'title' => 'Titulek #1', - 'content' => 'Upraveny obsah #1', - 'translated_article_id' => 1, - ), - 'Title' => array( - array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Updated Title #1'), - array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'), - array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1'), - array('id' => 19, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Nuevo leyenda #1') - ), - 'Content' => array( - array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'), - array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'), - array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Upraveny obsah #1') - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * Test that saveAll() works with hasMany associations that contain - * translations. - * - * @return void - */ - public function testSaveAllTranslatedAssociations() { - $this->loadFixtures('Translate', 'TranslateArticle', 'TranslatedItem', 'TranslatedArticle', 'User'); - $Model = new TranslatedArticle(); - $Model->locale = 'eng'; - - $data = array( - 'TranslatedArticle' => array( - 'id' => 4, - 'user_id' => 1, - 'published' => 'Y', - 'title' => 'Title (eng) #1', - 'body' => 'Body (eng) #1' - ), - 'TranslatedItem' => array( - array( - 'slug' => '', - 'title' => 'Nuevo leyenda #1', - 'content' => 'Upraveny obsah #1' - ), - array( - 'slug' => '', - 'title' => 'New Title #2', - 'content' => 'New Content #2' - ), - ) - ); - $result = $Model->saveAll($data); - $this->assertTrue($result); - - $result = $Model->TranslatedItem->find('all', array( - 'conditions' => array('translated_article_id' => $Model->id) - )); - $this->assertCount(2, $result); - $this->assertEquals($data['TranslatedItem'][0]['title'], $result[0]['TranslatedItem']['title']); - $this->assertEquals($data['TranslatedItem'][1]['title'], $result[1]['TranslatedItem']['title']); - } - -/** - * testValidation method - * - * @return void - */ - public function testValidation() { - Configure::write('Config.language', 'eng'); - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->locale = 'eng'; - $TestModel->validate['title'] = '/Only this title/'; - $data = array( - 'TranslatedItem' => array( - 'id' => 1, - 'title' => array('eng' => 'New Title #1', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'), - 'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1') - ) - ); - $TestModel->create(); - $this->assertFalse($TestModel->save($data)); - $this->assertEquals(array('The provided value is invalid'), $TestModel->validationErrors['title']); - - $TestModel->locale = 'eng'; - $TestModel->validate['title'] = '/Only this title/'; - $data = array('TranslatedItem' => array( - 'id' => 1, - 'title' => array('eng' => 'Only this title', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'), - 'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1') - )); - $TestModel->create(); - $result = $TestModel->save($data); - $this->assertFalse(empty($result)); - } - -/** - * testAttachDetach method - * - * @return void - */ - public function testAttachDetach() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - - $TestModel->unbindTranslation(); - $translations = array('title' => 'Title', 'content' => 'Content'); - $TestModel->bindTranslation($translations, false); - - $result = array_keys($TestModel->hasMany); - $expected = array('Title', 'Content'); - $this->assertEquals($expected, $result); - - $TestModel->Behaviors->unload('Translate'); - $result = array_keys($TestModel->hasMany); - $expected = array(); - $this->assertEquals($expected, $result); - - $result = isset($TestModel->Behaviors->Translate); - $this->assertFalse($result); - - $result = isset($Behavior->settings[$TestModel->alias]); - $this->assertFalse($result); - - $result = isset($Behavior->runtime[$TestModel->alias]); - $this->assertFalse($result); - - $TestModel->Behaviors->load('Translate', array('title' => 'Title', 'content' => 'Content')); - $result = array_keys($TestModel->hasMany); - $expected = array('Title', 'Content'); - $this->assertEquals($expected, $result); - - $result = isset($TestModel->Behaviors->Translate); - $this->assertTrue($result); - - $Behavior = $TestModel->Behaviors->Translate; - - $result = isset($Behavior->settings[$TestModel->alias]); - $this->assertTrue($result); - - $result = isset($Behavior->runtime[$TestModel->alias]); - $this->assertTrue($result); - } - -/** - * testAnotherTranslateTable method - * - * @return void - */ - public function testAnotherTranslateTable() { - $this->loadFixtures('Translate', 'TranslatedItem', 'TranslateTable'); - - $TestModel = new TranslatedItemWithTable(); - $TestModel->locale = 'eng'; - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedItemWithTable' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'eng', - 'title' => 'Another Title #1', - 'content' => 'Another Content #1', - 'translated_article_id' => 1, - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testTranslateWithAssociations method - * - * @return void - */ - public function testTranslateWithAssociations() { - $this->loadFixtures('TranslateArticle', 'TranslatedArticle', 'TranslatedItem', 'User', 'Comment', 'ArticlesTag', 'Tag'); - - $TestModel = new TranslatedArticle(); - $TestModel->locale = 'eng'; - $recursive = $TestModel->recursive; - - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedArticle' => array( - 'id' => 1, - 'user_id' => 1, - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'locale' => 'eng', - 'title' => 'Title (eng) #1', - 'body' => 'Body (eng) #1' - ), - 'User' => array( - 'id' => 1, - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'TranslatedItem' => array( - array( - 'id' => 1, - 'translated_article_id' => 1, - 'slug' => 'first_translated' - ), - array( - 'id' => 2, - 'translated_article_id' => 1, - 'slug' => 'second_translated' - ), - array( - 'id' => 3, - 'translated_article_id' => 1, - 'slug' => 'third_translated' - ), - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('recursive' => -1)); - $expected = array( - array( - 'TranslatedArticle' => array( - 'id' => 1, - 'user_id' => 1, - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'locale' => 'eng', - 'title' => 'Title (eng) #1', - 'body' => 'Body (eng) #1' - ) - ), - array( - 'TranslatedArticle' => array( - 'id' => 2, - 'user_id' => 3, - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'locale' => 'eng', - 'title' => 'Title (eng) #2', - 'body' => 'Body (eng) #2' - ) - ), - array( - 'TranslatedArticle' => array( - 'id' => 3, - 'user_id' => 1, - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'locale' => 'eng', - 'title' => 'Title (eng) #3', - 'body' => 'Body (eng) #3' - ) - ) - ); - $this->assertEquals($expected, $result); - $this->assertEquals($TestModel->recursive, $recursive); - - $TestModel->recursive = -1; - $result = $TestModel->read(null, 1); - $expected = array( - 'TranslatedArticle' => array( - 'id' => 1, - 'user_id' => 1, - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'locale' => 'eng', - 'title' => 'Title (eng) #1', - 'body' => 'Body (eng) #1' - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testTranslateTableWithPrefix method - * Tests that is possible to have a translation model with a custom tablePrefix - * - * @return void - */ - public function testTranslateTableWithPrefix() { - $this->loadFixtures('TranslateWithPrefix', 'TranslatedItem'); - $TestModel = new TranslatedItem2; - $TestModel->locale = 'eng'; - $result = $TestModel->read(null, 1); - $expected = array('TranslatedItem' => array( - 'id' => 1, - 'slug' => 'first_translated', - 'locale' => 'eng', - 'content' => 'Content #1', - 'title' => 'Title #1', - 'translated_article_id' => 1, - )); - $this->assertEquals($expected, $result); - } - -/** - * Test infinite loops not occurring with unbindTranslation() - * - * @return void - */ - public function testUnbindTranslationInfinteLoop() { - $this->loadFixtures('Translate', 'TranslatedItem'); - - $TestModel = new TranslatedItem(); - $TestModel->Behaviors->unload('Translate'); - $TestModel->actsAs = array(); - $TestModel->Behaviors->load('Translate'); - $TestModel->bindTranslation(array('title', 'content'), true); - $result = $TestModel->unbindTranslation(); - - $this->assertFalse($result); - } - -/** - * Test that an exception is raised when you try to over-write the name attribute. - * - * @expectedException CakeException - * @return void - */ - public function testExceptionOnNameTranslation() { - $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); - $TestModel->bindTranslation(array('name' => 'name')); - } - -/** - * Test that translations can be bound and unbound dynamically. - * - * @return void - */ - public function testUnbindTranslation() { - $this->loadFixtures('Translate', 'TranslatedItem'); - $Model = new TranslatedItem(); - $Model->unbindTranslation(); - $Model->bindTranslation(array('body', 'slug'), false); - - $result = $Model->Behaviors->Translate->settings['TranslatedItem']; - $this->assertEquals(array('body', 'slug'), $result); - - $Model->unbindTranslation(array('body')); - $result = $Model->Behaviors->Translate->settings['TranslatedItem']; - $this->assertNotContains('body', $result); - - $Model->unbindTranslation('slug'); - $result = $Model->Behaviors->Translate->settings['TranslatedItem']; - $this->assertNotContains('slug', $result); - } - -/** - * Test that additional records are not inserted for associated translations. - * - * @return void - */ - public function testNoExtraRowsForAssociatedTranslations() { - $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); - $TestModel->locale = 'spa'; - $TestModel->unbindTranslation(); - $TestModel->bindTranslation(array('name' => 'nameTranslate')); - - $data = array( - 'TranslatedItem' => array( - 'slug' => 'spanish-name', - 'name' => 'Spanish name', - ), - ); - $TestModel->create($data); - $TestModel->save(); - - $Translate = $TestModel->translateModel(); - $results = $Translate->find('all', array( - 'conditions' => array( - 'locale' => $TestModel->locale, - 'foreign_key' => $TestModel->id - ) - )); - $this->assertCount(1, $results, 'Only one field should be saved'); - $this->assertEquals('name', $results[0]['TranslateTestModel']['field']); - } - -} diff --git a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorAfterTest.php b/Cake/Test/TestCase/Model/Behavior/TreeBehaviorAfterTest.php deleted file mode 100644 index c2a82864f9b..00000000000 --- a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorAfterTest.php +++ /dev/null @@ -1,78 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.5330 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model\Behavior; - -use Cake\Model\Model; -use Cake\TestSuite\TestCase; - -require_once dirname(__DIR__) . DS . 'models.php'; - -/** - * TreeBehaviorAfterTest class - * - */ -class TreeBehaviorAfterTest extends TestCase { - -/** - * Whether backup global state for each test method or not - * - * @var boolean - */ - public $backupGlobals = false; - -/** - * settings property - * - * @var array - */ - public $settings = array( - 'modelClass' => 'AfterTree', - 'leftField' => 'lft', - 'rightField' => 'rght', - 'parentField' => 'parent_id' - ); - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array('core.after_tree'); - - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Not runnable until Models are fixed.'); - } -/** - * Tests the afterSave callback in the model - * - * @return void - */ - public function testAftersaveCallback() { - $this->Tree = new AfterTree(); - $this->Tree->order = null; - - $expected = array('AfterTree' => array('name' => 'Six and One Half Changed in AfterTree::afterSave() but not in database', 'parent_id' => 6, 'lft' => 11, 'rght' => 12)); - $result = $this->Tree->save(array('AfterTree' => array('name' => 'Six and One Half', 'parent_id' => 6))); - $expected['AfterTree']['id'] = $this->Tree->id; - $this->assertEquals($expected, $result); - - $expected = array('AfterTree' => array('name' => 'Six and One Half', 'parent_id' => 6, 'lft' => 11, 'rght' => 12, 'id' => 8)); - $result = $this->Tree->find('all'); - $this->assertEquals($expected, $result[7]); - } -} diff --git a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorNumberTest.php b/Cake/Test/TestCase/Model/Behavior/TreeBehaviorNumberTest.php deleted file mode 100644 index a625cb940c6..00000000000 --- a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorNumberTest.php +++ /dev/null @@ -1,1564 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.5330 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model\Behavior; - -use Cake\Model\Model; -use Cake\TestSuite\TestCase; - -require_once dirname(__DIR__) . DS . 'models.php'; - -/** - * TreeBehaviorNumberTest class - * - */ -class TreeBehaviorNumberTest extends TestCase { - -/** - * Whether backup global state for each test method or not - * - * @var boolean - */ - public $backupGlobals = false; - -/** - * settings property - * - * @var array - */ - public $settings = array( - 'modelClass' => 'NumberTree', - 'leftField' => 'lft', - 'rightField' => 'rght', - 'parentField' => 'parent_id' - ); - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array('core.number_tree', 'core.person'); - - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Not runnable until Models are fixed.'); - } -/** - * testInitialize method - * - * @return void - */ - public function testInitialize() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $result = $this->Tree->find('count'); - $this->assertEquals(7, $result); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testDetectInvalidLeft method - * - * @return void - */ - public function testDetectInvalidLeft() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $result = $this->Tree->findByName('1.1'); - - $save[$modelClass]['id'] = $result[$modelClass]['id']; - $save[$modelClass][$leftField] = 0; - - $this->Tree->create(); - $this->Tree->save($save); - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testDetectInvalidRight method - * - * @return void - */ - public function testDetectInvalidRight() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $result = $this->Tree->findByName('1.1'); - - $save[$modelClass]['id'] = $result[$modelClass]['id']; - $save[$modelClass][$rightField] = 0; - - $this->Tree->create(); - $this->Tree->save($save); - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testDetectInvalidParent method - * - * @return void - */ - public function testDetectInvalidParent() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $result = $this->Tree->findByName('1.1'); - - // Bypass behavior and any other logic - $this->Tree->updateAll(array($parentField => null), array('id' => $result[$modelClass]['id'])); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testDetectNoneExistentParent method - * - * @return void - */ - public function testDetectNoneExistentParent() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $result = $this->Tree->findByName('1.1'); - $this->Tree->updateAll(array($parentField => 999999), array('id' => $result[$modelClass]['id'])); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover('MPTT'); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testRecoverUsingParentMode method - * - * @return void - */ - public function testRecoverUsingParentMode() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->Behaviors->disable('Tree'); - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Main', $parentField => null, $leftField => 0, $rightField => 0)); - $node1 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0)); - $node11 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0)); - $node12 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0)); - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Overview', $parentField => $node12, $leftField => 0, $rightField => 0)); - - $this->Tree->Behaviors->enable('Tree'); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - - $result = $this->Tree->find('first', array( - 'fields' => array('name', $parentField, $leftField, $rightField), - 'conditions' => array('name' => 'Main'), - 'recursive' => -1 - )); - $expected = array( - $modelClass => array( - 'name' => 'Main', - $parentField => null, - $leftField => 1, - $rightField => 10 - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testRecoverUsingParentModeAndDelete method - * - * @return void - */ - public function testRecoverUsingParentModeAndDelete() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->Behaviors->disable('Tree'); - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Main', $parentField => null, $leftField => 0, $rightField => 0)); - $node1 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0)); - $node11 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0)); - $node12 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0)); - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Overview', $parentField => $node12, $leftField => 0, $rightField => 0)); - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Lost', $parentField => 9, $leftField => 0, $rightField => 0)); - - $this->Tree->Behaviors->enable('Tree'); - - $this->Tree->bindModel(array('belongsTo' => array('Parent' => array( - 'className' => $this->Tree->name, - 'foreignKey' => $parentField - )))); - $this->Tree->bindModel(array('hasMany' => array('Child' => array( - 'className' => $this->Tree->name, - 'foreignKey' => $parentField - )))); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $count = $this->Tree->find('count'); - $this->assertEquals(6, $count); - - $result = $this->Tree->recover('parent', 'delete'); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - - $count = $this->Tree->find('count'); - $this->assertEquals(5, $count); - - $result = $this->Tree->find('first', array( - 'fields' => array('name', $parentField, $leftField, $rightField), - 'conditions' => array('name' => 'Main'), - 'recursive' => -1 - )); - $expected = array( - $modelClass => array( - 'name' => 'Main', - $parentField => null, - $leftField => 1, - $rightField => 10 - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testRecoverFromMissingParent method - * - * @return void - */ - public function testRecoverFromMissingParent() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $result = $this->Tree->findByName('1.1'); - $this->Tree->updateAll(array($parentField => 999999), array('id' => $result[$modelClass]['id'])); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testDetectInvalidParents method - * - * @return void - */ - public function testDetectInvalidParents() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->updateAll(array($parentField => null)); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testDetectInvalidLftsRghts method - * - * @return void - */ - public function testDetectInvalidLftsRghts() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->updateAll(array($leftField => 0, $rightField => 0)); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $this->Tree->recover(); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * Reproduces a situation where a single node has lft= rght, and all other lft and rght fields follow sequentially - * - * @return void - */ - public function testDetectEqualLftsRghts() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(1, 3); - - $result = $this->Tree->findByName('1.1'); - $this->Tree->updateAll(array($rightField => $result[$modelClass][$leftField]), array('id' => $result[$modelClass]['id'])); - $this->Tree->updateAll(array($leftField => $this->Tree->escapeField($leftField) . ' -1'), - array($leftField . ' >' => $result[$modelClass][$leftField])); - $this->Tree->updateAll(array($rightField => $this->Tree->escapeField($rightField) . ' -1'), - array($rightField . ' >' => $result[$modelClass][$leftField])); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testAddOrphan method - * - * @return void - */ - public function testAddOrphan() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->create(); - $this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null))); - $result = $this->Tree->find('first', array('fields' => array('name', $parentField), 'order' => $modelClass . '.' . $leftField . ' desc')); - $expected = array($modelClass => array('name' => 'testAddOrphan', $parentField => null)); - $this->assertEquals($expected, $result); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testAddMiddle method - * - * @return void - */ - public function testAddMiddle() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); - $initialCount = $this->Tree->find('count'); - - $this->Tree->create(); - $result = $this->Tree->save(array($modelClass => array('name' => 'testAddMiddle', $parentField => $data[$modelClass]['id']))); - $expected = array_merge(array($modelClass => array('name' => 'testAddMiddle', $parentField => '2')), $result); - $this->assertSame($expected, $result); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount + 1, $laterCount); - - $children = $this->Tree->children($data[$modelClass]['id'], true, array('name')); - $expects = array(array($modelClass => array('name' => '1.1.1')), - array($modelClass => array('name' => '1.1.2')), - array($modelClass => array('name' => 'testAddMiddle'))); - $this->assertSame($children, $expects); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testAddWithPreSpecifiedId method - * - * @return void - */ - public function testAddWithPreSpecifiedId() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array( - 'fields' => array('id'), - 'conditions' => array($modelClass . '.name' => '1.1') - )); - - $this->Tree->create(); - $result = $this->Tree->save(array($modelClass => array( - 'id' => 100, - 'name' => 'testAddMiddle', - $parentField => $data[$modelClass]['id']) - )); - $expected = array_merge( - array($modelClass => array('id' => 100, 'name' => 'testAddMiddle', $parentField => '2')), - $result - ); - $this->assertSame($expected, $result); - - $this->assertTrue($this->Tree->verify()); - } - -/** - * testAddInvalid method - * - * @return void - */ - public function testAddInvalid() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $initialCount = $this->Tree->find('count'); - //$this->expectError('Trying to save a node under a none-existant node in TreeBehavior::beforeSave'); - - $this->Tree->create(); - $saveSuccess = $this->Tree->save(array($modelClass => array('name' => 'testAddInvalid', $parentField => 99999))); - $this->assertFalse($saveSuccess); - - $laterCount = $this->Tree->find('count'); - $this->assertSame($initialCount, $laterCount); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testAddNotIndexedByModel method - * - * @return void - */ - public function testAddNotIndexedByModel() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->create(); - $this->Tree->save(array('name' => 'testAddNotIndexed', $parentField => null)); - $result = $this->Tree->find('first', array('fields' => array('name', $parentField), 'order' => $modelClass . '.' . $leftField . ' desc')); - $expected = array($modelClass => array('name' => 'testAddNotIndexed', $parentField => null)); - $this->assertEquals($expected, $result); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testMovePromote method - * - * @return void - */ - public function testMovePromote() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $parentId = $parent[$modelClass]['id']; - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->saveField($parentField, $parentId); - $direct = $this->Tree->children($parentId, true, array('id', 'name', $parentField, $leftField, $rightField)); - $expects = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 5)), - array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 6, $rightField => 11)), - array($modelClass => array('id' => 3, 'name' => '1.1.1', $parentField => 1, $leftField => 12, $rightField => 13))); - $this->assertEquals($direct, $expects); - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testMoveWithWhitelist method - * - * @return void - */ - public function testMoveWithWhitelist() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $parentId = $parent[$modelClass]['id']; - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->whitelist = array($parentField, 'name', 'description'); - $this->Tree->saveField($parentField, $parentId); - - $result = $this->Tree->children($parentId, true, array('id', 'name', $parentField, $leftField, $rightField)); - $expected = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 5)), - array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 6, $rightField => 11)), - array($modelClass => array('id' => 3, 'name' => '1.1.1', $parentField => 1, $leftField => 12, $rightField => 13))); - $this->assertEquals($expected, $result); - $this->assertTrue($this->Tree->verify()); - } - -/** - * testInsertWithWhitelist method - * - * @return void - */ - public function testInsertWithWhitelist() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->whitelist = array('name', $parentField); - $this->Tree->create(); - $this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null))); - $result = $this->Tree->findByName('testAddOrphan', array('name', $parentField, $leftField, $rightField)); - $expected = array('name' => 'testAddOrphan', $parentField => null, $leftField => '15', $rightField => 16); - $this->assertEquals($expected, $result[$modelClass]); - $this->assertTrue($this->Tree->verify()); - } - -/** - * testMoveBefore method - * - * @return void - */ - public function testMoveBefore() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.1'))); - $parentId = $parent[$modelClass]['id']; - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.2'))); - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->saveField($parentField, $parentId); - - $result = $this->Tree->children($parentId, true, array('name')); - $expects = array(array($modelClass => array('name' => '1.1.1')), - array($modelClass => array('name' => '1.1.2')), - array($modelClass => array('name' => '1.2'))); - $this->assertEquals($expects, $result); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testMoveAfter method - * - * @return void - */ - public function testMoveAfter() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.2'))); - $parentId = $parent[$modelClass]['id']; - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->saveField($parentField, $parentId); - - $result = $this->Tree->children($parentId, true, array('name')); - $expects = array(array($modelClass => array('name' => '1.2.1')), - array($modelClass => array('name' => '1.2.2')), - array($modelClass => array('name' => '1.1'))); - $this->assertEquals($expects, $result); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testMoveDemoteInvalid method - * - * @return void - */ - public function testMoveDemoteInvalid() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $parentId = $parent[$modelClass]['id']; - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); - - $expects = $this->Tree->find('all'); - $before = $this->Tree->read(null, $data[$modelClass]['id']); - - $this->Tree->id = $parentId; - $this->Tree->saveField($parentField, $data[$modelClass]['id']); - - $results = $this->Tree->find('all'); - $after = $this->Tree->read(null, $data[$modelClass]['id']); - - $this->assertEquals($expects, $results); - $this->assertEquals($before, $after); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testMoveInvalid method - * - * @return void - */ - public function testMoveInvalid() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $initialCount = $this->Tree->find('count'); - $data = $this->Tree->findByName('1.1'); - - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->saveField($parentField, 999999); - - $laterCount = $this->Tree->find('count'); - $this->assertSame($initialCount, $laterCount); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testMoveSelfInvalid method - * - * @return void - */ - public function testMoveSelfInvalid() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $initialCount = $this->Tree->find('count'); - $data = $this->Tree->findByName('1.1'); - - $this->Tree->id = $data[$modelClass]['id']; - $saveSuccess = $this->Tree->saveField($parentField, $this->Tree->id); - - $this->assertFalse($saveSuccess); - $laterCount = $this->Tree->find('count'); - $this->assertSame($initialCount, $laterCount); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testMoveUpSuccess method - * - * @return void - */ - public function testMoveUpSuccess() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.2'))); - $this->Tree->moveUp($data[$modelClass]['id']); - - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array(array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1.1'))); - $this->assertSame($expected, $result); - } - -/** - * testMoveUpFail method - * - * @return void - */ - public function testMoveUpFail() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.1'))); - - $this->Tree->moveUp($data[$modelClass]['id']); - - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array(array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1.2'))); - $this->assertSame($expected, $result); - } - -/** - * testMoveUp2 method - * - * @return void - */ - public function testMoveUp2() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(1, 10); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); - $this->Tree->moveUp($data[$modelClass]['id'], 2); - - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array( - array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1.5')), - array($modelClass => array('name' => '1.3')), - array($modelClass => array('name' => '1.4')), - array($modelClass => array('name' => '1.6')), - array($modelClass => array('name' => '1.7')), - array($modelClass => array('name' => '1.8')), - array($modelClass => array('name' => '1.9')), - array($modelClass => array('name' => '1.10'))); - $this->assertSame($expected, $result); - } - -/** - * testMoveUpFirst method - * - * @return void - */ - public function testMoveUpFirst() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(1, 10); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); - $this->Tree->moveUp($data[$modelClass]['id'], true); - - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array( - array($modelClass => array('name' => '1.5')), - array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1.3')), - array($modelClass => array('name' => '1.4')), - array($modelClass => array('name' => '1.6')), - array($modelClass => array('name' => '1.7')), - array($modelClass => array('name' => '1.8')), - array($modelClass => array('name' => '1.9')), - array($modelClass => array('name' => '1.10'))); - $this->assertSame($expected, $result); - } - -/** - * testMoveDownSuccess method - * - * @return void - */ - public function testMoveDownSuccess() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); - $this->Tree->moveDown($data[$modelClass]['id']); - - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array(array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1.1'))); - $this->assertSame($expected, $result); - } - -/** - * testMoveDownFail method - * - * @return void - */ - public function testMoveDownFail() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.2'))); - $this->Tree->moveDown($data[$modelClass]['id']); - - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array(array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1.2'))); - $this->assertSame($expected, $result); - } - -/** - * testMoveDownLast method - * - * @return void - */ - public function testMoveDownLast() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(1, 10); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); - $this->Tree->moveDown($data[$modelClass]['id'], true); - - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array( - array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1.3')), - array($modelClass => array('name' => '1.4')), - array($modelClass => array('name' => '1.6')), - array($modelClass => array('name' => '1.7')), - array($modelClass => array('name' => '1.8')), - array($modelClass => array('name' => '1.9')), - array($modelClass => array('name' => '1.10')), - array($modelClass => array('name' => '1.5'))); - $this->assertSame($expected, $result); - } - -/** - * testMoveDown2 method - * - * @return void - */ - public function testMoveDown2() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(1, 10); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); - $this->Tree->moveDown($data[$modelClass]['id'], 2); - - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array( - array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1.3')), - array($modelClass => array('name' => '1.4')), - array($modelClass => array('name' => '1.6')), - array($modelClass => array('name' => '1.7')), - array($modelClass => array('name' => '1.5')), - array($modelClass => array('name' => '1.8')), - array($modelClass => array('name' => '1.9')), - array($modelClass => array('name' => '1.10'))); - $this->assertSame($expected, $result); - } - -/** - * testSaveNoMove method - * - * @return void - */ - public function testSaveNoMove() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(1, 10); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.5'))); - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->saveField('name', 'renamed'); - $parent = $this->Tree->findByName('1. Root', array('id')); - $this->Tree->id = $parent[$modelClass]['id']; - $result = $this->Tree->children(null, true, array('name')); - $expected = array( - array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1.3')), - array($modelClass => array('name' => '1.4')), - array($modelClass => array('name' => 'renamed')), - array($modelClass => array('name' => '1.6')), - array($modelClass => array('name' => '1.7')), - array($modelClass => array('name' => '1.8')), - array($modelClass => array('name' => '1.9')), - array($modelClass => array('name' => '1.10'))); - $this->assertSame($expected, $result); - } - -/** - * testMoveToRootAndMoveUp method - * - * @return void - */ - public function testMoveToRootAndMoveUp() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(1, 1); - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->save(array($parentField => null)); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - - $this->Tree->moveUp(); - - $result = $this->Tree->find('all', array('fields' => 'name', 'order' => $modelClass . '.' . $leftField . ' ASC')); - $expected = array(array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1. Root'))); - $this->assertSame($expected, $result); - } - -/** - * testDelete method - * - * @return void - */ - public function testDelete() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $initialCount = $this->Tree->find('count'); - $result = $this->Tree->findByName('1.1.1'); - - $return = $this->Tree->delete($result[$modelClass]['id']); - $this->assertEquals(true, $return); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount - 1, $laterCount); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - - $initialCount = $this->Tree->find('count'); - $result = $this->Tree->findByName('1.1'); - - $return = $this->Tree->delete($result[$modelClass]['id']); - $this->assertEquals(true, $return); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount - 2, $laterCount); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * Test deleting a record that doesn't exist. - * - * @return void - */ - public function testDeleteDoesNotExist() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->delete(99999); - } - -/** - * testRemove method - * - * @return void - */ - public function testRemove() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $initialCount = $this->Tree->find('count'); - $result = $this->Tree->findByName('1.1'); - - $this->Tree->removeFromTree($result[$modelClass]['id']); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount, $laterCount); - - $children = $this->Tree->children($result[$modelClass][$parentField], true, array('name')); - $expects = array(array($modelClass => array('name' => '1.1.1')), - array($modelClass => array('name' => '1.1.2')), - array($modelClass => array('name' => '1.2'))); - $this->assertEquals($children, $expects); - - $topNodes = $this->Tree->children(false, true, array('name')); - $expects = array(array($modelClass => array('name' => '1. Root')), - array($modelClass => array('name' => '1.1'))); - $this->assertEquals($topNodes, $expects); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testRemoveLastTopParent method - * - * @return void - */ - public function testRemoveLastTopParent() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $initialCount = $this->Tree->find('count'); - $initialTopNodes = $this->Tree->childCount(false); - - $result = $this->Tree->findByName('1. Root'); - $this->Tree->removeFromTree($result[$modelClass]['id']); - - $laterCount = $this->Tree->find('count'); - $laterTopNodes = $this->Tree->childCount(false); - - $this->assertEquals($initialCount, $laterCount); - $this->assertEquals($initialTopNodes, $laterTopNodes); - - $topNodes = $this->Tree->children(false, true, array('name')); - $expects = array(array($modelClass => array('name' => '1.1')), - array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1. Root'))); - - $this->assertEquals($topNodes, $expects); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testRemoveNoChildren method - * - * @return void - */ - public function testRemoveNoChildren() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $initialCount = $this->Tree->find('count'); - - $result = $this->Tree->findByName('1.1.1'); - $this->Tree->removeFromTree($result[$modelClass]['id']); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount, $laterCount); - - $nodes = $this->Tree->find('list', array('order' => $leftField)); - $expects = array( - 1 => '1. Root', - 2 => '1.1', - 4 => '1.1.2', - 5 => '1.2', - 6 => '1.2.1', - 7 => '1.2.2', - 3 => '1.1.1', - ); - - $this->assertEquals($nodes, $expects); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testRemoveAndDelete method - * - * @return void - */ - public function testRemoveAndDelete() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $initialCount = $this->Tree->find('count'); - $result = $this->Tree->findByName('1.1'); - - $this->Tree->removeFromTree($result[$modelClass]['id'], true); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount - 1, $laterCount); - - $children = $this->Tree->children($result[$modelClass][$parentField], true, array('name'), $leftField . ' asc'); - $expects = array( - array($modelClass => array('name' => '1.1.1')), - array($modelClass => array('name' => '1.1.2')), - array($modelClass => array('name' => '1.2')) - ); - $this->assertEquals($children, $expects); - - $topNodes = $this->Tree->children(false, true, array('name')); - $expects = array(array($modelClass => array('name' => '1. Root'))); - $this->assertEquals($topNodes, $expects); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testRemoveAndDeleteNoChildren method - * - * @return void - */ - public function testRemoveAndDeleteNoChildren() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $initialCount = $this->Tree->find('count'); - - $result = $this->Tree->findByName('1.1.1'); - $this->Tree->removeFromTree($result[$modelClass]['id'], true); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount - 1, $laterCount); - - $nodes = $this->Tree->find('list', array('order' => $leftField)); - $expects = array( - 1 => '1. Root', - 2 => '1.1', - 4 => '1.1.2', - 5 => '1.2', - 6 => '1.2.1', - 7 => '1.2.2', - ); - $this->assertEquals($nodes, $expects); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testChildren method - * - * @return void - */ - public function testChildren() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $this->Tree->id = $data[$modelClass]['id']; - - $direct = $this->Tree->children(null, true, array('id', 'name', $parentField, $leftField, $rightField)); - $expects = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 7)), - array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 8, $rightField => 13))); - $this->assertEquals($direct, $expects); - - $total = $this->Tree->children(null, null, array('id', 'name', $parentField, $leftField, $rightField)); - $expects = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 7)), - array($modelClass => array('id' => 3, 'name' => '1.1.1', $parentField => 2, $leftField => 3, $rightField => 4)), - array($modelClass => array('id' => 4, 'name' => '1.1.2', $parentField => 2, $leftField => 5, $rightField => 6)), - array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 8, $rightField => 13)), - array($modelClass => array('id' => 6, 'name' => '1.2.1', $parentField => 5, $leftField => 9, $rightField => 10)), - array($modelClass => array('id' => 7, 'name' => '1.2.2', $parentField => 5, $leftField => 11, $rightField => 12))); - $this->assertEquals($total, $expects); - - $this->assertEquals(array(), $this->Tree->children(10000)); - } - -/** - * testCountChildren method - * - * @return void - */ - public function testCountChildren() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $this->Tree->id = $data[$modelClass]['id']; - - $direct = $this->Tree->childCount(null, true); - $this->assertEquals(2, $direct); - - $total = $this->Tree->childCount(); - $this->assertEquals(6, $total); - - $this->Tree->read(null, $data[$modelClass]['id']); - $id = $this->Tree->field('id', array($modelClass . '.name' => '1.2')); - $total = $this->Tree->childCount($id); - $this->assertEquals(2, $total); - } - -/** - * testGetParentNode method - * - * @return void - */ - public function testGetParentNode() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.2.2'))); - $this->Tree->id = $data[$modelClass]['id']; - - $result = $this->Tree->getParentNode(null, array('name')); - $expects = array($modelClass => array('name' => '1.2')); - $this->assertSame($expects, $result); - } - -/** - * testGetPath method - * - * @return void - */ - public function testGetPath() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1.2.2'))); - $this->Tree->id = $data[$modelClass]['id']; - - $result = $this->Tree->getPath(null, array('name')); - $expects = array(array($modelClass => array('name' => '1. Root')), - array($modelClass => array('name' => '1.2')), - array($modelClass => array('name' => '1.2.2'))); - $this->assertSame($expects, $result); - } - -/** - * testNoAmbiguousColumn method - * - * @return void - */ - public function testNoAmbiguousColumn() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->bindModel(array('belongsTo' => array('Dummy' => - array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $this->Tree->id = $data[$modelClass]['id']; - - $direct = $this->Tree->children(null, true, array('id', 'name', $parentField, $leftField, $rightField)); - $expects = array(array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 7)), - array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 8, $rightField => 13))); - $this->assertEquals($direct, $expects); - - $total = $this->Tree->children(null, null, array('id', 'name', $parentField, $leftField, $rightField)); - $expects = array( - array($modelClass => array('id' => 2, 'name' => '1.1', $parentField => 1, $leftField => 2, $rightField => 7)), - array($modelClass => array('id' => 3, 'name' => '1.1.1', $parentField => 2, $leftField => 3, $rightField => 4)), - array($modelClass => array('id' => 4, 'name' => '1.1.2', $parentField => 2, $leftField => 5, $rightField => 6)), - array($modelClass => array('id' => 5, 'name' => '1.2', $parentField => 1, $leftField => 8, $rightField => 13)), - array($modelClass => array('id' => 6, 'name' => '1.2.1', $parentField => 5, $leftField => 9, $rightField => 10)), - array($modelClass => array('id' => 7, 'name' => '1.2.2', $parentField => 5, $leftField => 11, $rightField => 12)) - ); - $this->assertEquals($total, $expects); - } - -/** - * testReorderTree method - * - * @return void - */ - public function testReorderTree() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(3, 3); - $nodes = $this->Tree->find('list', array('order' => $leftField)); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1'))); - $this->Tree->moveDown($data[$modelClass]['id']); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.2.1'))); - $this->Tree->moveDown($data[$modelClass]['id']); - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.3.2.2'))); - $this->Tree->moveDown($data[$modelClass]['id']); - - $unsortedNodes = $this->Tree->find('list', array('order' => $leftField)); - $this->assertEquals($nodes, $unsortedNodes); - $this->assertNotEquals(array_keys($nodes), array_keys($unsortedNodes)); - - $this->Tree->reorder(); - $sortedNodes = $this->Tree->find('list', array('order' => $leftField)); - $this->assertSame($nodes, $sortedNodes); - } - -/** - * test reordering large-ish trees with cacheQueries = true. - * This caused infinite loops when moving down elements as stale data is returned - * from the memory cache - * - * @return void - */ - public function testReorderBigTreeWithQueryCaching() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 10); - - $original = $this->Tree->cacheQueries; - $this->Tree->cacheQueries = true; - $this->Tree->reorder(array('field' => 'name', 'direction' => 'DESC')); - $this->assertTrue($this->Tree->cacheQueries, 'cacheQueries was not restored after reorder(). %s'); - $this->Tree->cacheQueries = $original; - } - -/** - * testGenerateTreeListWithSelfJoin method - * - * @return void - */ - public function testGenerateTreeListWithSelfJoin() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->bindModel(array('belongsTo' => array('Dummy' => - array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); - $this->Tree->initialize(2, 2); - - $result = $this->Tree->generateTreeList(); - $expected = array(1 => '1. Root', 2 => '_1.1', 3 => '__1.1.1', 4 => '__1.1.2', 5 => '_1.2', 6 => '__1.2.1', 7 => '__1.2.2'); - $this->assertSame($expected, $result); - } - -/** - * Test the formatting options of generateTreeList() - * - * @return void - */ - public function testGenerateTreeListFormatting() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $result = $this->Tree->generateTreeList( - null, - "{n}.$modelClass.id", - array('%s - %s', "{n}.$modelClass.id", "{n}.$modelClass.name") - ); - $this->assertEquals('1 - 1. Root', $result[1]); - $this->assertEquals('_2 - 1.1', $result[2]); - $this->assertEquals('__3 - 1.1.1', $result[3]); - } - -/** - * testArraySyntax method - * - * @return void - */ - public function testArraySyntax() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(3, 3); - $this->assertSame($this->Tree->childCount(2), $this->Tree->childCount(array('id' => 2))); - $this->assertSame($this->Tree->getParentNode(2), $this->Tree->getParentNode(array('id' => 2))); - $this->assertSame($this->Tree->getPath(4), $this->Tree->getPath(array('id' => 4))); - } - -/** - * testFindThreaded method - * - * @return void - */ - public function testFindThreaded() { - $Model = new Person(); - $Model->recursive = -1; - $Model->Behaviors->load('Tree', array('parent' => 'mother_id')); - - $result = $Model->find('threaded'); - $expected = array( - array( - 'Person' => array( - 'id' => '4', - 'name' => 'mother - grand mother', - 'mother_id' => '0', - 'father_id' => '0' - ), - 'children' => array( - array( - 'Person' => array( - 'id' => '2', - 'name' => 'mother', - 'mother_id' => '4', - 'father_id' => '5' - ), - 'children' => array( - array( - 'Person' => array( - 'id' => '1', - 'name' => 'person', - 'mother_id' => '2', - 'father_id' => '3' - ), - 'children' => array() - ) - ) - ) - ) - ), - array( - 'Person' => array( - 'id' => '5', - 'name' => 'mother - grand father', - 'mother_id' => '0', - 'father_id' => '0' - ), - 'children' => array() - ), - array( - 'Person' => array( - 'id' => '6', - 'name' => 'father - grand mother', - 'mother_id' => '0', - 'father_id' => '0' - ), - 'children' => array( - array( - 'Person' => array( - 'id' => '3', - 'name' => 'father', - 'mother_id' => '6', - 'father_id' => '7' - ), - 'children' => array() - ) - ) - ), - array( - 'Person' => array( - 'id' => '7', - 'name' => 'father - grand father', - 'mother_id' => '0', - 'father_id' => '0' - ), - 'children' => array() - ) - ); - $this->assertEquals($expected, $result); - } -} diff --git a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorScopedTest.php b/Cake/Test/TestCase/Model/Behavior/TreeBehaviorScopedTest.php deleted file mode 100644 index e37fb63ac9c..00000000000 --- a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorScopedTest.php +++ /dev/null @@ -1,571 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.5330 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model\Behavior; - -use Cake\Model\Model; -use Cake\TestSuite\TestCase; - -require_once dirname(__DIR__) . DS . 'models.php'; - -/** - * TreeBehaviorScopedTest class - * - */ -class TreeBehaviorScopedTest extends TestCase { - -/** - * Whether backup global state for each test method or not - * - * @var boolean - */ - public $backupGlobals = false; - -/** - * settings property - * - * @var array - */ - public $settings = array( - 'modelClass' => 'FlagTree', - 'leftField' => 'lft', - 'rightField' => 'rght', - 'parentField' => 'parent_id' - ); - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array('core.flag_tree', 'core.ad', 'core.campaign', 'core.translate', 'core.number_tree_two'); - - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Not runnable until Models are fixed.'); - } -/** - * testStringScope method - * - * @return void - */ - public function testStringScope() { - $this->Tree = new FlagTree(); - $this->Tree->order = null; - $this->Tree->initialize(2, 3); - - $this->Tree->id = 1; - $this->Tree->saveField('flag', 1); - $this->Tree->id = 2; - $this->Tree->saveField('flag', 1); - - $result = $this->Tree->children(); - $expected = array( - array('FlagTree' => array('id' => '3', 'name' => '1.1.1', 'parent_id' => '2', 'lft' => '3', 'rght' => '4', 'flag' => '0')), - array('FlagTree' => array('id' => '4', 'name' => '1.1.2', 'parent_id' => '2', 'lft' => '5', 'rght' => '6', 'flag' => '0')), - array('FlagTree' => array('id' => '5', 'name' => '1.1.3', 'parent_id' => '2', 'lft' => '7', 'rght' => '8', 'flag' => '0')) - ); - $this->assertEquals($expected, $result); - - $this->Tree->Behaviors->load('Tree', array('scope' => 'FlagTree.flag = 1')); - $this->assertEquals(array(), $this->Tree->children()); - - $this->Tree->id = 1; - $this->Tree->Behaviors->load('Tree', array('scope' => 'FlagTree.flag = 1')); - - $result = $this->Tree->children(); - $expected = array(array('FlagTree' => array('id' => '2', 'name' => '1.1', 'parent_id' => '1', 'lft' => '2', 'rght' => '9', 'flag' => '1'))); - $this->assertEquals($expected, $result); - - $this->assertTrue($this->Tree->delete()); - $this->assertEquals(11, $this->Tree->find('count')); - } - -/** - * testArrayScope method - * - * @return void - */ - public function testArrayScope() { - $this->Tree = new FlagTree(); - $this->Tree->order = null; - $this->Tree->initialize(2, 3); - - $this->Tree->id = 1; - $this->Tree->saveField('flag', 1); - $this->Tree->id = 2; - $this->Tree->saveField('flag', 1); - - $result = $this->Tree->children(); - $expected = array( - array('FlagTree' => array('id' => '3', 'name' => '1.1.1', 'parent_id' => '2', 'lft' => '3', 'rght' => '4', 'flag' => '0')), - array('FlagTree' => array('id' => '4', 'name' => '1.1.2', 'parent_id' => '2', 'lft' => '5', 'rght' => '6', 'flag' => '0')), - array('FlagTree' => array('id' => '5', 'name' => '1.1.3', 'parent_id' => '2', 'lft' => '7', 'rght' => '8', 'flag' => '0')) - ); - $this->assertEquals($expected, $result); - - $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); - $this->assertEquals(array(), $this->Tree->children()); - - $this->Tree->id = 1; - $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); - - $result = $this->Tree->children(); - $expected = array(array('FlagTree' => array('id' => '2', 'name' => '1.1', 'parent_id' => '1', 'lft' => '2', 'rght' => '9', 'flag' => '1'))); - $this->assertEquals($expected, $result); - - $this->assertTrue($this->Tree->delete()); - $this->assertEquals(11, $this->Tree->find('count')); - } - -/** - * testMoveUpWithScope method - * - * @return void - */ - public function testMoveUpWithScope() { - $this->Ad = new Ad(); - $this->Ad->order = null; - $this->Ad->Behaviors->load('Tree', array('scope' => 'Campaign')); - $this->Ad->moveUp(6); - - $this->Ad->id = 4; - $result = $this->Ad->children(); - $this->assertEquals(array(6, 5), Hash::extract($result, '{n}.Ad.id')); - $this->assertEquals(array(2, 2), Hash::extract($result, '{n}.Campaign.id')); - } - -/** - * testMoveDownWithScope method - * - * @return void - */ - public function testMoveDownWithScope() { - $this->Ad = new Ad(); - $this->Ad->order = null; - $this->Ad->Behaviors->load('Tree', array('scope' => 'Campaign')); - $this->Ad->moveDown(6); - - $this->Ad->id = 4; - $result = $this->Ad->children(); - $this->assertEquals(array(5, 6), Hash::extract($result, '{n}.Ad.id')); - $this->assertEquals(array(2, 2), Hash::extract($result, '{n}.Campaign.id')); - } - -/** - * Tests the interaction (non-interference) between TreeBehavior and other behaviors with respect - * to callback hooks - * - * @return void - */ - public function testTranslatingTree() { - $this->Tree = new FlagTree(); - $this->Tree->order = null; - $this->Tree->cacheQueries = false; - $this->Tree->Behaviors->load('Translate', array('title')); - - //Save - $this->Tree->create(); - $this->Tree->locale = 'eng'; - $data = array('FlagTree' => array( - 'title' => 'name #1', - 'name' => 'test', - 'locale' => 'eng', - 'parent_id' => null, - )); - $this->Tree->save($data); - $result = $this->Tree->find('all'); - $expected = array(array('FlagTree' => array( - 'id' => 1, - 'title' => 'name #1', - 'name' => 'test', - 'parent_id' => null, - 'lft' => 1, - 'rght' => 2, - 'flag' => 0, - 'locale' => 'eng', - ))); - $this->assertEquals($expected, $result); - - // update existing record, same locale - $this->Tree->create(); - $data['FlagTree']['title'] = 'Named 2'; - $this->Tree->id = 1; - $this->Tree->save($data); - $result = $this->Tree->find('all'); - $expected = array(array('FlagTree' => array( - 'id' => 1, - 'title' => 'Named 2', - 'name' => 'test', - 'parent_id' => null, - 'lft' => 1, - 'rght' => 2, - 'flag' => 0, - 'locale' => 'eng', - ))); - $this->assertEquals($expected, $result); - - // update different locale, same record - $this->Tree->create(); - $this->Tree->locale = 'deu'; - $this->Tree->id = 1; - $data = array('FlagTree' => array( - 'id' => 1, - 'parent_id' => null, - 'title' => 'namen #1', - 'name' => 'test', - 'locale' => 'deu', - )); - $this->Tree->save($data); - - $this->Tree->locale = 'deu'; - $result = $this->Tree->find('all'); - $expected = array( - array( - 'FlagTree' => array( - 'id' => 1, - 'title' => 'namen #1', - 'name' => 'test', - 'parent_id' => null, - 'lft' => 1, - 'rght' => 2, - 'flag' => 0, - 'locale' => 'deu', - ) - ) - ); - $this->assertEquals($expected, $result); - - // Save with bindTranslation - $this->Tree->locale = 'eng'; - $data = array( - 'title' => array('eng' => 'New title', 'spa' => 'Nuevo leyenda'), - 'name' => 'test', - 'parent_id' => null - ); - $this->Tree->create($data); - $this->Tree->save(); - - $this->Tree->unbindTranslation(); - $translations = array('title' => 'Title'); - $this->Tree->bindTranslation($translations, false); - $this->Tree->locale = array('eng', 'spa'); - - $result = $this->Tree->read(); - $expected = array( - 'FlagTree' => array( - 'id' => 2, - 'parent_id' => null, - 'locale' => 'eng', - 'name' => 'test', - 'title' => 'New title', - 'flag' => 0, - 'lft' => 3, - 'rght' => 4 - ), - 'Title' => array( - array('id' => 21, 'locale' => 'eng', 'model' => 'FlagTree', 'foreign_key' => 2, 'field' => 'title', 'content' => 'New title'), - array('id' => 22, 'locale' => 'spa', 'model' => 'FlagTree', 'foreign_key' => 2, 'field' => 'title', 'content' => 'Nuevo leyenda') - ), - ); - $this->assertEquals($expected, $result); - } - -/** - * testGenerateTreeListWithSelfJoin method - * - * @return void - */ - public function testAliasesWithScopeInTwoTreeAssociations() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->TreeTwo = new NumberTreeTwo(); - $this->TreeTwo->order = null; - - $record = $this->Tree->find('first'); - - $this->Tree->bindModel(array( - 'hasMany' => array( - 'SecondTree' => array( - 'className' => 'NumberTreeTwo', - 'foreignKey' => 'number_tree_id' - ) - ) - )); - $this->TreeTwo->bindModel(array( - 'belongsTo' => array( - 'FirstTree' => array( - 'className' => $modelClass, - 'foreignKey' => 'number_tree_id' - ) - ) - )); - $this->TreeTwo->Behaviors->load('Tree', array( - 'scope' => 'FirstTree' - )); - - $data = array( - 'NumberTreeTwo' => array( - 'name' => 'First', - 'number_tree_id' => $record['FlagTree']['id'] - ) - ); - $this->TreeTwo->create(); - $result = $this->TreeTwo->save($data); - $this->assertFalse(empty($result)); - - $result = $this->TreeTwo->find('first'); - $expected = array('NumberTreeTwo' => array( - 'id' => 1, - 'name' => 'First', - 'number_tree_id' => $record['FlagTree']['id'], - 'parent_id' => null, - 'lft' => 1, - 'rght' => 2 - )); - $this->assertEquals($expected, $result); - } - -/** - * testGenerateTreeListWithScope method - * - * @return void - */ - public function testGenerateTreeListWithScope() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 3); - - $this->Tree->id = 1; - $this->Tree->saveField('flag', 1); - $this->Tree->id = 2; - $this->Tree->saveField('flag', 1); - - $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); - - $result = $this->Tree->generateTreeList(); - $expected = array( - 1 => '1. Root', - 2 => '_1.1' - ); - $this->assertEquals($expected, $result); - - // As string. - $this->Tree->Behaviors->load('Tree', array('scope' => 'FlagTree.flag = 1')); - - $result = $this->Tree->generateTreeList(); - $this->assertEquals($expected, $result); - - // Merging conditions. - $result = $this->Tree->generateTreeList(array('FlagTree.id >' => 1)); - $expected = array( - 2 => '1.1' - ); - $this->assertEquals($expected, $result); - } - -/** - * testRecoverUsingParentMode method - * - * @return void - */ - public function testRecoverUsingParentMode() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 3); - - $this->Tree->Behaviors->load('Tree', array('scope' => 'FlagTree.flag = 1')); - $this->Tree->Behaviors->disable('Tree'); - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Main', $parentField => null, $leftField => 0, $rightField => 0, 'flag' => 1)); - $node1 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0, 'flag' => 1)); - $node11 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0, 'flag' => 1)); - $node12 = $this->Tree->id; - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0, 'flag' => 1)); - - $this->Tree->create(); - $this->Tree->save(array('name' => 'Overview', $parentField => $node12, $leftField => 0, $rightField => 0, 'flag' => 1)); - - $this->Tree->Behaviors->enable('Tree'); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - - $result = $this->Tree->find('first', array( - 'fields' => array('name', $parentField, $leftField, $rightField, 'flag'), - 'conditions' => array('name' => 'Main'), - 'recursive' => -1 - )); - $expected = array( - $modelClass => array( - 'name' => 'Main', - $parentField => null, - $leftField => 1, - $rightField => 10, - 'flag' => 1 - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testRecoverFromMissingParent method - * - * @return void - */ - public function testRecoverFromMissingParent() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->id = 1; - $this->Tree->saveField('flag', 1); - $this->Tree->id = 2; - $this->Tree->saveField('flag', 1); - - $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); - - $result = $this->Tree->findByName('1.1'); - $this->Tree->updateAll(array($parentField => 999999), array('id' => $result[$modelClass]['id'])); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testDetectInvalidParents method - * - * @return void - */ - public function testDetectInvalidParents() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->id = 1; - $this->Tree->saveField('flag', 1); - $this->Tree->id = 2; - $this->Tree->saveField('flag', 1); - - $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); - - $this->Tree->updateAll(array($parentField => null)); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * testDetectInvalidLftsRghts method - * - * @return void - */ - public function testDetectInvalidLftsRghts() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->id = 1; - $this->Tree->saveField('flag', 1); - $this->Tree->id = 2; - $this->Tree->saveField('flag', 1); - - $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); - - $this->Tree->updateAll(array($leftField => 0, $rightField => 0)); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $this->Tree->recover(); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -/** - * Reproduces a situation where a single node has lft= rght, and all other lft and rght fields follow sequentially - * - * @return void - */ - public function testDetectEqualLftsRghts() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(1, 3); - - $this->Tree->id = 1; - $this->Tree->saveField('flag', 1); - $this->Tree->id = 2; - $this->Tree->saveField('flag', 1); - - $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); - - $result = $this->Tree->findByName('1.1'); - $this->Tree->updateAll(array($rightField => $result[$modelClass][$leftField]), array('id' => $result[$modelClass]['id'])); - $this->Tree->updateAll(array($leftField => $this->Tree->escapeField($leftField) . ' -1'), - array($leftField . ' >' => $result[$modelClass][$leftField])); - $this->Tree->updateAll(array($rightField => $this->Tree->escapeField($rightField) . ' -1'), - array($rightField . ' >' => $result[$modelClass][$leftField])); - - $result = $this->Tree->verify(); - $this->assertNotSame($result, true); - - $result = $this->Tree->recover(); - $this->assertTrue($result); - - $result = $this->Tree->verify(); - $this->assertTrue($result); - } - -} diff --git a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorTest.php b/Cake/Test/TestCase/Model/Behavior/TreeBehaviorTest.php deleted file mode 100644 index 7557e68a1b0..00000000000 --- a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorTest.php +++ /dev/null @@ -1,45 +0,0 @@ -addTestFile(CORE_TEST_CASES . DS . 'Model/Behavior/TreeBehaviorNumberTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/Behavior/TreeBehaviorScopedTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/Behavior/TreeBehaviorAfterTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/Behavior/TreeBehaviorUuidTest.php'); - return $suite; - } -} diff --git a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorUuidTest.php b/Cake/Test/TestCase/Model/Behavior/TreeBehaviorUuidTest.php deleted file mode 100644 index 75bdca13de2..00000000000 --- a/Cake/Test/TestCase/Model/Behavior/TreeBehaviorUuidTest.php +++ /dev/null @@ -1,301 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.5330 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model\Behavior; - -use Cake\Model\Model; -use Cake\TestSuite\TestCase; -use Cake\Utility\String; - -require_once dirname(__DIR__) . DS . 'models.php'; - -/** - * TreeBehaviorUuidTest class - * - */ -class TreeBehaviorUuidTest extends TestCase { - -/** - * Whether backup global state for each test method or not - * - * @var boolean - */ - public $backupGlobals = false; - -/** - * settings property - * - * @var array - */ - public $settings = array( - 'modelClass' => 'UuidTree', - 'leftField' => 'lft', - 'rightField' => 'rght', - 'parentField' => 'parent_id' - ); - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array('core.uuid_tree'); - - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Not runnable until Models are fixed.'); - } -/** - * testAddWithPreSpecifiedId method - * - * @return void - */ - public function testAddWithPreSpecifiedId() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array( - 'fields' => array('id'), - 'conditions' => array($modelClass . '.name' => '1.1') - )); - - $id = String::uuid(); - $this->Tree->create(); - $result = $this->Tree->save(array($modelClass => array( - 'id' => $id, - 'name' => 'testAddMiddle', - $parentField => $data[$modelClass]['id']) - )); - $expected = array_merge( - array($modelClass => array('id' => $id, 'name' => 'testAddMiddle', $parentField => '2')), - $result - ); - $this->assertSame($expected, $result); - - $this->assertTrue($this->Tree->verify()); - } - -/** - * testMovePromote method - * - * @return void - */ - public function testMovePromote() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $parentId = $parent[$modelClass]['id']; - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->saveField($parentField, $parentId); - $direct = $this->Tree->children($parentId, true, array('name', $leftField, $rightField)); - $expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 5)), - array($modelClass => array('name' => '1.2', $leftField => 6, $rightField => 11)), - array($modelClass => array('name' => '1.1.1', $leftField => 12, $rightField => 13))); - $this->assertEquals($direct, $expects); - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testMoveWithWhitelist method - * - * @return void - */ - public function testMoveWithWhitelist() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $this->Tree->id = null; - - $parent = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $parentId = $parent[$modelClass]['id']; - - $data = $this->Tree->find('first', array('fields' => array('id'), 'conditions' => array($modelClass . '.name' => '1.1.1'))); - $this->Tree->id = $data[$modelClass]['id']; - $this->Tree->whitelist = array($parentField, 'name', 'description'); - $this->Tree->saveField($parentField, $parentId); - - $result = $this->Tree->children($parentId, true, array('name', $leftField, $rightField)); - $expected = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 5)), - array($modelClass => array('name' => '1.2', $leftField => 6, $rightField => 11)), - array($modelClass => array('name' => '1.1.1', $leftField => 12, $rightField => 13))); - $this->assertEquals($expected, $result); - $this->assertTrue($this->Tree->verify()); - } - -/** - * testRemoveNoChildren method - * - * @return void - */ - public function testRemoveNoChildren() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $initialCount = $this->Tree->find('count'); - - $result = $this->Tree->findByName('1.1.1'); - $this->Tree->removeFromTree($result[$modelClass]['id']); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount, $laterCount); - - $nodes = $this->Tree->find('list', array('order' => $leftField)); - $expects = array( - '1. Root', - '1.1', - '1.1.2', - '1.2', - '1.2.1', - '1.2.2', - '1.1.1', - ); - - $this->assertEquals(array_values($nodes), $expects); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testRemoveAndDeleteNoChildren method - * - * @return void - */ - public function testRemoveAndDeleteNoChildren() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - $initialCount = $this->Tree->find('count'); - - $result = $this->Tree->findByName('1.1.1'); - $this->Tree->removeFromTree($result[$modelClass]['id'], true); - - $laterCount = $this->Tree->find('count'); - $this->assertEquals($initialCount - 1, $laterCount); - - $nodes = $this->Tree->find('list', array('order' => $leftField)); - $expects = array( - '1. Root', - '1.1', - '1.1.2', - '1.2', - '1.2.1', - '1.2.2', - ); - $this->assertEquals(array_values($nodes), $expects); - - $validTree = $this->Tree->verify(); - $this->assertTrue($validTree); - } - -/** - * testChildren method - * - * @return void - */ - public function testChildren() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $data = $this->Tree->find('first', array('conditions' => array($modelClass . '.name' => '1. Root'))); - $this->Tree->id = $data[$modelClass]['id']; - - $direct = $this->Tree->children(null, true, array('name', $leftField, $rightField)); - $expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)), - array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13))); - $this->assertEquals($direct, $expects); - - $total = $this->Tree->children(null, null, array('name', $leftField, $rightField)); - $expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)), - array($modelClass => array('name' => '1.1.1', $leftField => 3, $rightField => 4)), - array($modelClass => array('name' => '1.1.2', $leftField => 5, $rightField => 6)), - array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13)), - array($modelClass => array('name' => '1.2.1', $leftField => 9, $rightField => 10)), - array($modelClass => array('name' => '1.2.2', $leftField => 11, $rightField => 12))); - $this->assertEquals($total, $expects); - } - -/** - * testNoAmbiguousColumn method - * - * @return void - */ - public function testNoAmbiguousColumn() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->initialize(2, 2); - - $this->Tree->bindModel(array('belongsTo' => array('Dummy' => - array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); - - $data = $this->Tree->find('first', array( - 'conditions' => array($modelClass . '.name' => '1. Root'), - 'recursive' => -1 - )); - $this->Tree->id = $data[$modelClass]['id']; - - $direct = $this->Tree->children(null, true, array('name', $leftField, $rightField)); - $expects = array(array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)), - array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13))); - $this->assertEquals($direct, $expects); - - $total = $this->Tree->children(null, null, array('name', $leftField, $rightField)); - $expects = array( - array($modelClass => array('name' => '1.1', $leftField => 2, $rightField => 7)), - array($modelClass => array('name' => '1.1.1', $leftField => 3, $rightField => 4)), - array($modelClass => array('name' => '1.1.2', $leftField => 5, $rightField => 6)), - array($modelClass => array('name' => '1.2', $leftField => 8, $rightField => 13)), - array($modelClass => array('name' => '1.2.1', $leftField => 9, $rightField => 10)), - array($modelClass => array('name' => '1.2.2', $leftField => 11, $rightField => 12)) - ); - $this->assertEquals($total, $expects); - } - -/** - * testGenerateTreeListWithSelfJoin method - * - * @return void - */ - public function testGenerateTreeListWithSelfJoin() { - extract($this->settings); - $this->Tree = new $modelClass(); - $this->Tree->order = null; - $this->Tree->bindModel(array('belongsTo' => array('Dummy' => - array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); - $this->Tree->initialize(2, 2); - - $result = $this->Tree->generateTreeList(); - $expected = array('1. Root', '_1.1', '__1.1.1', '__1.1.2', '_1.2', '__1.2.1', '__1.2.2'); - $this->assertSame(array_values($result), $expected); - } -} diff --git a/Cake/Test/TestCase/Model/BehaviorCollectionTest.php b/Cake/Test/TestCase/Model/BehaviorCollectionTest.php deleted file mode 100644 index 7f715e39adb..00000000000 --- a/Cake/Test/TestCase/Model/BehaviorCollectionTest.php +++ /dev/null @@ -1,1260 +0,0 @@ - 'testMethod', '/look for\s+(.+)/' => 'speakEnglish'); - -/** - * setup method - * - * @param Model $model - * @param array $config - * @return void - */ - public function setup(Model $model, $config = array()) { - parent::setup($model, $config); - if (isset($config['mangle'])) { - $config['mangle'] .= ' mangled'; - } - $this->settings[$model->alias] = array_merge(array('beforeFind' => 'on', 'afterFind' => 'off'), $config); - } - -/** - * beforeFind method - * - * @param Model $model - * @param array $query - * @return void - */ - public function beforeFind(Model $model, $query) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['beforeFind']) || $settings['beforeFind'] === 'off') { - return parent::beforeFind($model, $query); - } - switch ($settings['beforeFind']) { - case 'on': - return false; - case 'test': - return null; - case 'modify': - $query['fields'] = array($model->alias . '.id', $model->alias . '.name', $model->alias . '.mytime'); - $query['recursive'] = -1; - return $query; - } - } - -/** - * afterFind method - * - * @param Model $model - * @param array $results - * @param boolean $primary - * @return void - */ - public function afterFind(Model $model, $results, $primary = false) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['afterFind']) || $settings['afterFind'] === 'off') { - return parent::afterFind($model, $results, $primary); - } - switch ($settings['afterFind']) { - case 'on': - return array(); - case 'test': - return true; - case 'test2': - return null; - case 'modify': - return Hash::extract($results, "{n}.{$model->alias}"); - } - } - -/** - * beforeSave method - * - * @param Model $model Model using this behavior - * @param array $options Options passed from Model::save(). - * @return mixed False if the operation should abort. Any other result will continue. - * @see Model::save() - */ - public function beforeSave(Model $model, $options = array()) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['beforeSave']) || $settings['beforeSave'] === 'off') { - return parent::beforeSave($model, $options); - } - switch ($settings['beforeSave']) { - case 'on': - return false; - case 'test': - return true; - case 'modify': - $model->data[$model->alias]['name'] .= ' modified before'; - return true; - } - } - -/** - * afterSave method - * - * @param Model $model - * @param boolean $created - * @param array $options Options passed from Model::save(). - * @return void - */ - public function afterSave(Model $model, $created, $options = array()) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['afterSave']) || $settings['afterSave'] === 'off') { - return parent::afterSave($model, $created, $options); - } - $string = 'modified after'; - if ($created) { - $string .= ' on create'; - } - switch ($settings['afterSave']) { - case 'on': - $model->data[$model->alias]['aftersave'] = $string; - break; - case 'test': - unset($model->data[$model->alias]['name']); - break; - case 'test2': - return false; - case 'modify': - $model->data[$model->alias]['name'] .= ' ' . $string; - break; - } - } - -/** - * beforeValidate Callback - * - * @param Model $Model Model invalidFields was called on. - * @param array $options Options passed from Model::save(). - * @return boolean - * @see Model::save() - */ - public function beforeValidate(Model $model, $options = array()) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['validate']) || $settings['validate'] === 'off') { - return parent::beforeValidate($model, $options); - } - switch ($settings['validate']) { - case 'on': - $model->invalidate('name'); - return true; - case 'test': - return null; - case 'whitelist': - $this->_addToWhitelist($model, array('name')); - return true; - case 'stop': - $model->invalidate('name'); - return false; - } - } - -/** - * afterValidate method - * - * @param Model $model - * @param boolean $cascade - * @return void - */ - public function afterValidate(Model $model) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['afterValidate']) || $settings['afterValidate'] === 'off') { - return parent::afterValidate($model); - } - switch ($settings['afterValidate']) { - case 'on': - return false; - case 'test': - $model->data = array('foo'); - return true; - } - } - -/** - * beforeDelete method - * - * @param Model $model - * @param boolean $cascade - * @return void - */ - public function beforeDelete(Model $model, $cascade = true) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['beforeDelete']) || $settings['beforeDelete'] === 'off') { - return parent::beforeDelete($model, $cascade); - } - switch ($settings['beforeDelete']) { - case 'on': - return false; - case 'test': - return null; - case 'test2': - echo 'beforeDelete success'; - if ($cascade) { - echo ' (cascading) '; - } - return true; - } - } - -/** - * afterDelete method - * - * @param Model $model - * @return void - */ - public function afterDelete(Model $model) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['afterDelete']) || $settings['afterDelete'] === 'off') { - return parent::afterDelete($model); - } - switch ($settings['afterDelete']) { - case 'on': - echo 'afterDelete success'; - break; - } - } - -/** - * onError method - * - * @param Model $model - * @return void - */ - public function onError(Model $model, $error) { - $settings = $this->settings[$model->alias]; - if (!isset($settings['onError']) || $settings['onError'] === 'off') { - return parent::onError($model, $error); - } - echo "onError trigger success"; - } - -/** - * beforeTest method - * - * @param Model $model - * @return void - */ - public function beforeTest(Model $model) { - if (!isset($model->beforeTestResult)) { - $model->beforeTestResult = array(); - } - $model->beforeTestResult[] = strtolower(get_class($this)); - return strtolower(get_class($this)); - } - -/** - * testMethod method - * - * @param Model $model - * @param boolean $param - * @return void - */ - public function testMethod(Model $model, $param = true) { - if ($param === true) { - return 'working'; - } - } - -/** - * testData method - * - * @param Model $model - * @return void - */ - public function testData(Model $model) { - if (!isset($model->data['Apple']['field'])) { - return false; - } - $model->data['Apple']['field_2'] = true; - return true; - } - -/** - * validateField method - * - * @param Model $model - * @param string|array $field - * @return void - */ - public function validateField(Model $model, $field) { - return current($field) === 'Orange'; - } - -/** - * speakEnglish method - * - * @param Model $model - * @param string $method - * @param string $query - * @return void - */ - public function speakEnglish(Model $model, $method, $query) { - $method = preg_replace('/look for\s+/', 'Item.name = \'', $method); - $query = preg_replace('/^in\s+/', 'Location.name = \'', $query); - return $method . '\' AND ' . $query . '\''; - } - -} - -/** - * Test2Behavior class - * - */ -class Test2Behavior extends TestBehavior { - - public $mapMethods = array('/mappingRobot(\w+)/' => 'mapped'); - - public function resolveMethod(Model $model, $stuff) { - } - - public function mapped(Model $model, $method, $query) { - } - -} - -/** - * Test3Behavior class - * - */ -class Test3Behavior extends TestBehavior { -} - -/** - * Test4Behavior class - * - */ -class Test4Behavior extends ModelBehavior { - - public function setup(Model $model, $config = null) { - $model->bindModel( - array('hasMany' => array('Comment')) - ); - } - -} - -/** - * Test5Behavior class - * - */ -class Test5Behavior extends ModelBehavior { - - public function setup(Model $model, $config = null) { - $model->bindModel( - array('belongsTo' => array('User')) - ); - } - -} - -/** - * Test6Behavior class - * - */ -class Test6Behavior extends ModelBehavior { - - public function setup(Model $model, $config = null) { - $model->bindModel( - array('hasAndBelongsToMany' => array('Tag')) - ); - } - -} - -/** - * Test7Behavior class - * - */ -class Test7Behavior extends ModelBehavior { - - public function setup(Model $model, $config = null) { - $model->bindModel( - array('hasOne' => array('Attachment')) - ); - } - -} - -/** - * Extended TestBehavior - */ -class TestAliasBehavior extends TestBehavior { -} - -/** - * FirstBehavior - */ -class FirstBehavior extends ModelBehavior { - - public function beforeFind(Model $model, $query = array()) { - $model->called[] = get_class($this); - return $query; - } - -} - -/** - * SecondBehavior - */ -class SecondBehavior extends FirstBehavior { -} - -/** - * ThirdBehavior - */ -class ThirdBehavior extends FirstBehavior { -} - -/** - * Orangutan Model - */ -class Orangutan extends Monkey { - - public $called = array(); - -} - -/** - * BehaviorCollection class - * - */ -class BehaviorCollectionTest extends TestCase { - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array( - 'core.apple', 'core.sample', 'core.article', 'core.user', 'core.comment', - 'core.attachment', 'core.tag', 'core.articles_tag', 'core.translate', - 'core.device' - ); - - public function setUp() { - $this->markTestIncomplete('Not working yet. Models are not complete.'); - } - -/** - * Test load() with enabled => false - * - */ - public function testLoadDisabled() { - $Apple = new Apple(); - $this->assertSame(array(), $Apple->Behaviors->loaded()); - - $Apple->Behaviors->load('Translate', array('enabled' => false)); - $this->assertTrue($Apple->Behaviors->loaded('Translate')); - $this->assertFalse($Apple->Behaviors->enabled('Translate')); - } - -/** - * Tests loading aliased behaviors - */ - public function testLoadAlias() { - $Apple = new Apple(); - $this->assertSame(array(), $Apple->Behaviors->loaded()); - - $Apple->Behaviors->load('Test', array('className' => 'TestAlias', 'somesetting' => true)); - $this->assertSame(array('Test'), $Apple->Behaviors->loaded()); - $this->assertInstanceOf('TestAliasBehavior', $Apple->Behaviors->Test); - $this->assertTrue($Apple->Behaviors->Test->settings['Apple']['somesetting']); - - $this->assertEquals('working', $Apple->Behaviors->Test->testMethod($Apple, true)); - $this->assertEquals('working', $Apple->testMethod(true)); - $this->assertEquals('working', $Apple->Behaviors->dispatchMethod($Apple, 'testMethod')); - - CakePlugin::load('TestPlugin'); - $this->assertTrue($Apple->Behaviors->load('SomeOther', array('className' => 'TestPlugin.TestPluginPersisterOne'))); - $this->assertInstanceOf('TestPluginPersisterOneBehavior', $Apple->Behaviors->SomeOther); - - $result = $Apple->Behaviors->loaded(); - $this->assertEquals(array('Test', 'SomeOther'), $result, 'loaded() results are wrong.'); - CakePlugin::unload(); - } - -/** - * testBehaviorBinding method - * - * @return void - */ - public function testBehaviorBinding() { - $Apple = new Apple(); - $this->assertSame(array(), $Apple->Behaviors->loaded()); - - $Apple->Behaviors->load('Test', array('key' => 'value')); - $this->assertSame(array('Test'), $Apple->Behaviors->loaded()); - $this->assertEquals('testbehavior', strtolower(get_class($Apple->Behaviors->Test))); - $expected = array('beforeFind' => 'on', 'afterFind' => 'off', 'key' => 'value'); - $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); - $this->assertEquals(array('priority', 'Apple'), array_keys($Apple->Behaviors->Test->settings)); - - $this->assertSame($Apple->Sample->Behaviors->loaded(), array()); - $Apple->Sample->Behaviors->load('Test', array('key2' => 'value2')); - $this->assertSame($Apple->Sample->Behaviors->loaded(), array('Test')); - $this->assertEquals(array('beforeFind' => 'on', 'afterFind' => 'off', 'key2' => 'value2'), $Apple->Sample->Behaviors->Test->settings['Sample']); - - $this->assertEquals(array('priority', 'Apple', 'Sample'), array_keys($Apple->Behaviors->Test->settings)); - $this->assertSame( - $Apple->Sample->Behaviors->Test->settings, - $Apple->Behaviors->Test->settings - ); - $this->assertNotSame($Apple->Behaviors->Test->settings['Apple'], $Apple->Sample->Behaviors->Test->settings['Sample']); - - $Apple->Behaviors->load('Test', array('key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); - $Apple->Sample->Behaviors->load('Test', array('key' => 'value', 'key3' => 'value3', 'beforeFind' => 'off')); - $this->assertEquals(array('beforeFind' => 'off', 'afterFind' => 'off', 'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'), $Apple->Behaviors->Test->settings['Apple']); - $this->assertEquals($Apple->Behaviors->Test->settings['Apple'], $Apple->Sample->Behaviors->Test->settings['Sample']); - - $this->assertFalse(isset($Apple->Child->Behaviors->Test)); - $Apple->Child->Behaviors->load('Test', array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); - $this->assertEquals($Apple->Child->Behaviors->Test->settings['Child'], $Apple->Sample->Behaviors->Test->settings['Sample']); - - $this->assertFalse(isset($Apple->Parent->Behaviors->Test)); - $Apple->Parent->Behaviors->load('Test', array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); - $this->assertEquals($Apple->Parent->Behaviors->Test->settings['Parent'], $Apple->Sample->Behaviors->Test->settings['Sample']); - - $Apple->Parent->Behaviors->load('Test', array('key' => 'value', 'key2' => 'value', 'key3' => 'value', 'beforeFind' => 'off')); - $this->assertNotEquals($Apple->Parent->Behaviors->Test->settings['Parent'], $Apple->Sample->Behaviors->Test->settings['Sample']); - - $Apple->Behaviors->load('Plugin.Test', array('key' => 'new value')); - $expected = array( - 'beforeFind' => 'off', 'afterFind' => 'off', 'key' => 'new value', - 'key2' => 'value2', 'key3' => 'value3' - ); - $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); - - $current = $Apple->Behaviors->Test->settings['Apple']; - $expected = array_merge($current, array('mangle' => 'trigger mangled')); - $Apple->Behaviors->load('Test', array('mangle' => 'trigger')); - $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); - - $Apple->Behaviors->load('Test'); - $expected = array_merge($current, array('mangle' => 'trigger mangled mangled')); - - $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); - $Apple->Behaviors->load('Test', array('mangle' => 'trigger')); - $expected = array_merge($current, array('mangle' => 'trigger mangled')); - $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); - } - -/** - * test that attach()/detach() works with plugin.banana - * - * @return void - */ - public function testDetachWithPluginNames() { - $Apple = new Apple(); - $Apple->Behaviors->load('Plugin.Test'); - $this->assertTrue(isset($Apple->Behaviors->Test), 'Missing behavior'); - $this->assertEquals(array('Test'), $Apple->Behaviors->loaded()); - - $Apple->Behaviors->unload('Plugin.Test'); - $this->assertEquals(array(), $Apple->Behaviors->loaded()); - - $Apple->Behaviors->load('Plugin.Test'); - $this->assertTrue(isset($Apple->Behaviors->Test), 'Missing behavior'); - $this->assertEquals(array('Test'), $Apple->Behaviors->loaded()); - - $Apple->Behaviors->unload('Test'); - $this->assertEquals(array(), $Apple->Behaviors->loaded()); - } - -/** - * test that attaching a non existent Behavior triggers a cake error. - * - * @expectedException MissingBehaviorException - * @return void - */ - public function testInvalidBehaviorCausingCakeError() { - $Apple = new Apple(); - $Apple->Behaviors->load('NoSuchBehavior'); - } - -/** - * testBehaviorToggling method - * - * @return void - */ - public function testBehaviorToggling() { - $Apple = new Apple(); - $this->assertSame($Apple->Behaviors->enabled(), array()); - - $Apple->Behaviors->init('Apple', array('Test' => array('key' => 'value'))); - $this->assertSame($Apple->Behaviors->enabled(), array('Test')); - - $Apple->Behaviors->disable('Test'); - $this->assertSame(array('Test'), $Apple->Behaviors->loaded()); - $this->assertSame($Apple->Behaviors->enabled(), array()); - - $Apple->Sample->Behaviors->load('Test'); - $this->assertTrue($Apple->Sample->Behaviors->enabled('Test')); - $this->assertSame($Apple->Behaviors->enabled(), array()); - - $Apple->Behaviors->enable('Test'); - $this->assertTrue($Apple->Behaviors->loaded('Test')); - $this->assertSame($Apple->Behaviors->enabled(), array('Test')); - - $Apple->Behaviors->disable('Test'); - $this->assertSame($Apple->Behaviors->enabled(), array()); - $Apple->Behaviors->load('Test', array('enabled' => true)); - $this->assertSame($Apple->Behaviors->enabled(), array('Test')); - $Apple->Behaviors->load('Test', array('enabled' => false)); - $this->assertSame($Apple->Behaviors->enabled(), array()); - $Apple->Behaviors->unload('Test'); - $this->assertSame($Apple->Behaviors->enabled(), array()); - } - -/** - * testBehaviorFindCallbacks method - * - * @return void - */ - public function testBehaviorFindCallbacks() { - $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); - - $Apple = new Apple(); - $expected = $Apple->find('all'); - - $Apple->Behaviors->load('Test'); - $this->assertNull($Apple->find('all')); - - $Apple->Behaviors->load('Test', array('beforeFind' => 'off')); - $this->assertSame($expected, $Apple->find('all')); - - $Apple->Behaviors->load('Test', array('beforeFind' => 'test')); - $this->assertSame($expected, $Apple->find('all')); - - $Apple->Behaviors->load('Test', array('beforeFind' => 'modify')); - $expected2 = array( - array('Apple' => array('id' => '1', 'name' => 'Red Apple 1', 'mytime' => '22:57:17')), - array('Apple' => array('id' => '2', 'name' => 'Bright Red Apple', 'mytime' => '22:57:17')), - array('Apple' => array('id' => '3', 'name' => 'green blue', 'mytime' => '22:57:17')) - ); - $result = $Apple->find('all', array('conditions' => array('Apple.id <' => '4'))); - $this->assertEquals($expected2, $result); - - $Apple->Behaviors->disable('Test'); - $result = $Apple->find('all'); - $this->assertEquals($expected, $result); - - $Apple->Behaviors->load('Test', array('beforeFind' => 'off', 'afterFind' => 'on')); - $this->assertSame($Apple->find('all'), array()); - - $Apple->Behaviors->load('Test', array('afterFind' => 'off')); - $this->assertEquals($expected, $Apple->find('all')); - - $Apple->Behaviors->load('Test', array('afterFind' => 'test')); - $this->assertEquals($expected, $Apple->find('all')); - - $Apple->Behaviors->load('Test', array('afterFind' => 'test2')); - $this->assertEquals($expected, $Apple->find('all')); - - $Apple->Behaviors->load('Test', array('afterFind' => 'modify')); - $expected = array( - array('id' => '1', 'apple_id' => '2', 'color' => 'Red 1', 'name' => 'Red Apple 1', 'created' => '2006-11-22 10:38:58', 'date' => '1951-01-04', 'modified' => '2006-12-01 13:31:26', 'mytime' => '22:57:17'), - array('id' => '2', 'apple_id' => '1', 'color' => 'Bright Red 1', 'name' => 'Bright Red Apple', 'created' => '2006-11-22 10:43:13', 'date' => '2014-01-01', 'modified' => '2006-11-30 18:38:10', 'mytime' => '22:57:17'), - array('id' => '3', 'apple_id' => '2', 'color' => 'blue green', 'name' => 'green blue', 'created' => '2006-12-25 05:13:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:24', 'mytime' => '22:57:17'), - array('id' => '4', 'apple_id' => '2', 'color' => 'Blue Green', 'name' => 'Test Name', 'created' => '2006-12-25 05:23:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:36', 'mytime' => '22:57:17'), - array('id' => '5', 'apple_id' => '5', 'color' => 'Green', 'name' => 'Blue Green', 'created' => '2006-12-25 05:24:06', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:16', 'mytime' => '22:57:17'), - array('id' => '6', 'apple_id' => '4', 'color' => 'My new appleOrange', 'name' => 'My new apple', 'created' => '2006-12-25 05:29:39', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:39', 'mytime' => '22:57:17'), - array('id' => '7', 'apple_id' => '6', 'color' => 'Some wierd color', 'name' => 'Some odd color', 'created' => '2006-12-25 05:34:21', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:34:21', 'mytime' => '22:57:17') - ); - $this->assertEquals($expected, $Apple->find('all')); - } - -/** - * testBehaviorHasManyFindCallbacks method - * - * @return void - */ - public function testBehaviorHasManyFindCallbacks() { - $Apple = new Apple(); - $Apple->unbindModel(array('hasOne' => array('Sample'), 'belongsTo' => array('Parent')), false); - $expected = $Apple->find('all'); - - $Apple->unbindModel(array('hasMany' => array('Child'))); - $wellBehaved = $Apple->find('all'); - $Apple->Child->Behaviors->load('Test', array('afterFind' => 'modify')); - $Apple->unbindModel(array('hasMany' => array('Child'))); - $this->assertSame($Apple->find('all'), $wellBehaved); - - $Apple->Child->Behaviors->load('Test', array('before' => 'off')); - $this->assertSame($expected, $Apple->find('all')); - - $Apple->Child->Behaviors->load('Test', array('before' => 'test')); - $this->assertSame($expected, $Apple->find('all')); - - $Apple->Child->Behaviors->load('Test', array('before' => 'modify')); - $result = $Apple->find('all', array('fields' => array('Apple.id'), 'conditions' => array('Apple.id <' => '4'))); - - $Apple->Child->Behaviors->disable('Test'); - $result = $Apple->find('all'); - $this->assertEquals($expected, $result); - - $Apple->Child->Behaviors->load('Test', array('before' => 'off', 'after' => 'on')); - - $Apple->Child->Behaviors->load('Test', array('after' => 'off')); - $this->assertEquals($expected, $Apple->find('all')); - - $Apple->Child->Behaviors->load('Test', array('after' => 'test')); - $this->assertEquals($expected, $Apple->find('all')); - - $Apple->Child->Behaviors->load('Test', array('after' => 'test2')); - $this->assertEquals($expected, $Apple->find('all')); - } - -/** - * testBehaviorHasOneFindCallbacks method - * - * @return void - */ - public function testBehaviorHasOneFindCallbacks() { - $Apple = new Apple(); - $Apple->unbindModel(array('hasMany' => array('Child'), 'belongsTo' => array('Parent')), false); - $expected = $Apple->find('all'); - - $Apple->unbindModel(array('hasOne' => array('Sample'))); - $wellBehaved = $Apple->find('all'); - $Apple->Sample->Behaviors->load('Test'); - $Apple->unbindModel(array('hasOne' => array('Sample'))); - $this->assertSame($Apple->find('all'), $wellBehaved); - - $Apple->Sample->Behaviors->load('Test', array('before' => 'off')); - $this->assertSame($expected, $Apple->find('all')); - - $Apple->Sample->Behaviors->load('Test', array('before' => 'test')); - $this->assertSame($expected, $Apple->find('all')); - - $Apple->Sample->Behaviors->disable('Test'); - $result = $Apple->find('all'); - $this->assertEquals($expected, $result); - - $Apple->Sample->Behaviors->load('Test', array('after' => 'off')); - $this->assertEquals($expected, $Apple->find('all')); - - $Apple->Sample->Behaviors->load('Test', array('after' => 'test')); - $this->assertEquals($expected, $Apple->find('all')); - - $Apple->Sample->Behaviors->load('Test', array('after' => 'test2')); - $this->assertEquals($expected, $Apple->find('all')); - } - -/** - * testBehaviorBelongsToFindCallbacks method - * - * @return void - */ - public function testBehaviorBelongsToFindCallbacks() { - $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); - - $conditions = array('order' => 'Apple.id ASC'); - $Apple = new Apple(); - $Apple->unbindModel(array('hasMany' => array('Child'), 'hasOne' => array('Sample')), false); - $expected = $Apple->find('all', $conditions); - - $Apple->unbindModel(array('belongsTo' => array('Parent'))); - $wellBehaved = $Apple->find('all', $conditions); - $Apple->Parent->Behaviors->load('Test'); - $Apple->unbindModel(array('belongsTo' => array('Parent'))); - $this->assertSame($Apple->find('all', $conditions), $wellBehaved); - - $Apple->Parent->Behaviors->load('Test', array('before' => 'off')); - $this->assertSame($expected, $Apple->find('all', $conditions)); - - $Apple->Parent->Behaviors->load('Test', array('before' => 'test')); - $this->assertSame($expected, $Apple->find('all', $conditions)); - - $Apple->Parent->Behaviors->load('Test', array('before' => 'modify')); - $expected2 = array( - array( - 'Apple' => array('id' => 1), - 'Parent' => array('id' => 2, 'name' => 'Bright Red Apple', 'mytime' => '22:57:17')), - array( - 'Apple' => array('id' => 2), - 'Parent' => array('id' => 1, 'name' => 'Red Apple 1', 'mytime' => '22:57:17')), - array( - 'Apple' => array('id' => 3), - 'Parent' => array('id' => 2, 'name' => 'Bright Red Apple', 'mytime' => '22:57:17')) - ); - $result2 = $Apple->find('all', array( - 'fields' => array('Apple.id', 'Parent.id', 'Parent.name', 'Parent.mytime'), - 'conditions' => array('Apple.id <' => '4'), - 'order' => 'Apple.id ASC', - )); - $this->assertEquals($expected2, $result2); - - $Apple->Parent->Behaviors->disable('Test'); - $result = $Apple->find('all', $conditions); - $this->assertEquals($expected, $result); - - $Apple->Parent->Behaviors->load('Test', array('after' => 'off')); - $this->assertEquals($expected, $Apple->find('all', $conditions)); - - $Apple->Parent->Behaviors->load('Test', array('after' => 'test')); - $this->assertEquals($expected, $Apple->find('all', $conditions)); - - $Apple->Parent->Behaviors->load('Test', array('after' => 'test2')); - $this->assertEquals($expected, $Apple->find('all', $conditions)); - } - -/** - * testBehaviorSaveCallbacks method - * - * @return void - */ - public function testBehaviorSaveCallbacks() { - $Sample = new Sample(); - $record = array('Sample' => array('apple_id' => 6, 'name' => 'sample99')); - - $Sample->Behaviors->load('Test', array('beforeSave' => 'on')); - $Sample->create(); - $this->assertSame(false, $Sample->save($record)); - - $Sample->Behaviors->load('Test', array('beforeSave' => 'off')); - $Sample->create(); - $result = $Sample->save($record); - $expected = $record; - $expected['Sample']['id'] = $Sample->id; - $this->assertSame($expected, $result); - - $Sample->Behaviors->load('Test', array('beforeSave' => 'test')); - $Sample->create(); - $result = $Sample->save($record); - $expected = $record; - $expected['Sample']['id'] = $Sample->id; - $this->assertSame($expected, $result); - - $Sample->Behaviors->load('Test', array('beforeSave' => 'modify')); - $expected = Hash::insert($record, 'Sample.name', 'sample99 modified before'); - $Sample->create(); - $result = $Sample->save($record); - $expected['Sample']['id'] = $Sample->id; - $this->assertSame($expected, $result); - - $Sample->Behaviors->disable('Test'); - $this->assertSame($record, $Sample->save($record)); - - $Sample->Behaviors->load('Test', array('beforeSave' => 'off', 'afterSave' => 'on')); - $expected = Hash::merge($record, array('Sample' => array('aftersave' => 'modified after on create'))); - $Sample->create(); - $result = $Sample->save($record); - $expected['Sample']['id'] = $Sample->id; - $this->assertEquals($expected, $result); - - $Sample->Behaviors->load('Test', array('beforeSave' => 'modify', 'afterSave' => 'modify')); - $expected = Hash::merge($record, array('Sample' => array('name' => 'sample99 modified before modified after on create'))); - $Sample->create(); - $result = $Sample->save($record); - $expected['Sample']['id'] = $Sample->id; - $this->assertSame($expected, $result); - - $Sample->Behaviors->load('Test', array('beforeSave' => 'off', 'afterSave' => 'test')); - $Sample->create(); - $expected = $record; - unset($expected['Sample']['name']); - $result = $Sample->save($record); - $expected['Sample']['id'] = $Sample->id; - $this->assertSame($expected, $result); - - $Sample->Behaviors->load('Test', array('afterSave' => 'test2')); - $Sample->create(); - $expected = $record; - $result = $Sample->save($record); - $expected['Sample']['id'] = $Sample->id; - $this->assertSame($expected, $result); - - $Sample->Behaviors->load('Test', array('beforeFind' => 'off', 'afterFind' => 'off')); - $Sample->recursive = -1; - $record2 = $Sample->read(null, 1); - - $Sample->Behaviors->load('Test', array('afterSave' => 'on')); - $expected = Hash::merge($record2, array('Sample' => array('aftersave' => 'modified after'))); - $Sample->create(); - $this->assertSame($expected, $Sample->save($record2)); - - $Sample->Behaviors->load('Test', array('afterSave' => 'modify')); - $expected = Hash::merge($record2, array('Sample' => array('name' => 'sample1 modified after'))); - $Sample->create(); - $this->assertSame($expected, $Sample->save($record2)); - } - -/** - * testBehaviorDeleteCallbacks method - * - * @return void - */ - public function testBehaviorDeleteCallbacks() { - $Apple = new Apple(); - - $Apple->Behaviors->load('Test', array('beforeFind' => 'off', 'beforeDelete' => 'off')); - $this->assertTrue($Apple->delete(6)); - - $Apple->Behaviors->load('Test', array('beforeDelete' => 'on')); - $this->assertFalse($Apple->delete(4)); - - $Apple->Behaviors->load('Test', array('beforeDelete' => 'test2')); - - ob_start(); - $results = $Apple->delete(4); - $this->assertSame(trim(ob_get_clean()), 'beforeDelete success (cascading)'); - $this->assertTrue($results); - - ob_start(); - $results = $Apple->delete(3, false); - $this->assertSame(trim(ob_get_clean()), 'beforeDelete success'); - $this->assertTrue($results); - - $Apple->Behaviors->load('Test', array('beforeDelete' => 'off', 'afterDelete' => 'on')); - ob_start(); - $results = $Apple->delete(2, false); - $this->assertSame(trim(ob_get_clean()), 'afterDelete success'); - $this->assertTrue($results); - } - -/** - * testBehaviorOnErrorCallback method - * - * @return void - */ - public function testBehaviorOnErrorCallback() { - $Apple = new Apple(); - - $Apple->Behaviors->load('Test', array('beforeFind' => 'off', 'onError' => 'on')); - ob_start(); - $Apple->Behaviors->Test->onError($Apple, ''); - $this->assertSame(trim(ob_get_clean()), 'onError trigger success'); - } - -/** - * testBehaviorValidateCallback method - * - * @return void - */ - public function testBehaviorValidateCallback() { - $Apple = new Apple(); - - $Apple->Behaviors->load('Test'); - $this->assertTrue($Apple->validates()); - - $Apple->Behaviors->load('Test', array('validate' => 'on')); - $this->assertFalse($Apple->validates()); - $this->assertSame($Apple->validationErrors, array('name' => array(true))); - - $Apple->Behaviors->load('Test', array('validate' => 'stop')); - $this->assertFalse($Apple->validates()); - $this->assertSame($Apple->validationErrors, array('name' => array(true, true))); - - $Apple->Behaviors->load('Test', array('validate' => 'whitelist')); - $Apple->validates(); - $this->assertSame($Apple->whitelist, array()); - - $Apple->whitelist = array('unknown'); - $Apple->validates(); - $this->assertSame($Apple->whitelist, array('unknown', 'name')); - } - -/** - * testBehaviorValidateAfterCallback method - * - * @return void - */ - public function testBehaviorValidateAfterCallback() { - $Apple = new Apple(); - - $Apple->Behaviors->load('Test'); - $this->assertTrue($Apple->validates()); - - $Apple->Behaviors->load('Test', array('afterValidate' => 'on')); - $this->assertTrue($Apple->validates()); - $this->assertSame($Apple->validationErrors, array()); - - $Apple->Behaviors->load('Test', array('afterValidate' => 'test')); - $Apple->data = array('bar'); - $Apple->validates(); - $this->assertEquals(array('foo'), $Apple->data); - } - -/** - * testBehaviorValidateMethods method - * - * @return void - */ - public function testBehaviorValidateMethods() { - $Apple = new Apple(); - $Apple->Behaviors->load('Test'); - $Apple->validate['color'] = 'validateField'; - - $result = $Apple->save(array('name' => 'Genetically Modified Apple', 'color' => 'Orange')); - $this->assertEquals(array('name', 'color', 'modified', 'created', 'id'), array_keys($result['Apple'])); - - $Apple->create(); - $result = $Apple->save(array('name' => 'Regular Apple', 'color' => 'Red')); - $this->assertFalse($result); - } - -/** - * testBehaviorMethodDispatching method - * - * @return void - */ - public function testBehaviorMethodDispatching() { - $Apple = new Apple(); - $Apple->Behaviors->load('Test'); - - $expected = 'working'; - $this->assertEquals($expected, $Apple->testMethod()); - $this->assertEquals($expected, $Apple->Behaviors->dispatchMethod($Apple, 'testMethod')); - - $result = $Apple->Behaviors->dispatchMethod($Apple, 'wtf'); - $this->assertEquals(array('unhandled'), $result); - - $result = $Apple->{'look for the remote'}('in the couch'); - $expected = "Item.name = 'the remote' AND Location.name = 'the couch'"; - $this->assertEquals($expected, $result); - - $result = $Apple->{'look for THE REMOTE'}('in the couch'); - $expected = "Item.name = 'THE REMOTE' AND Location.name = 'the couch'"; - $this->assertEquals($expected, $result, 'Mapped method was lowercased.'); - } - -/** - * testBehaviorMethodDispatchingWithData method - * - * @return void - */ - public function testBehaviorMethodDispatchingWithData() { - $Apple = new Apple(); - $Apple->Behaviors->load('Test'); - - $Apple->set('field', 'value'); - $this->assertTrue($Apple->testData()); - $this->assertTrue($Apple->data['Apple']['field_2']); - - $this->assertTrue($Apple->testData('one', 'two', 'three', 'four', 'five', 'six')); - } - -/** - * undocumented function - * - * @return void - */ - public function testBindModelCallsInBehaviors() { - // hasMany - $Article = new Article(); - $Article->unbindModel(array('hasMany' => array('Comment'))); - $result = $Article->find('first'); - $this->assertFalse(array_key_exists('Comment', $result)); - - $Article->Behaviors->load('Test4'); - $result = $Article->find('first'); - $this->assertTrue(array_key_exists('Comment', $result)); - - // belongsTo - $Article->unbindModel(array('belongsTo' => array('User'))); - $result = $Article->find('first'); - $this->assertFalse(array_key_exists('User', $result)); - - $Article->Behaviors->load('Test5'); - $result = $Article->find('first'); - $this->assertTrue(array_key_exists('User', $result)); - - // hasAndBelongsToMany - $Article->unbindModel(array('hasAndBelongsToMany' => array('Tag'))); - $result = $Article->find('first'); - $this->assertFalse(array_key_exists('Tag', $result)); - - $Article->Behaviors->load('Test6'); - $result = $Article->find('first'); - $this->assertTrue(array_key_exists('Comment', $result)); - - // hasOne - $Comment = new Comment(); - $Comment->unbindModel(array('hasOne' => array('Attachment'))); - $result = $Comment->find('first'); - $this->assertFalse(array_key_exists('Attachment', $result)); - - $Comment->Behaviors->load('Test7'); - $result = $Comment->find('first'); - $this->assertTrue(array_key_exists('Attachment', $result)); - } - -/** - * Test attach and detaching - * - * @return void - */ - public function testBehaviorAttachAndDetach() { - $Sample = new Sample(); - $Sample->actsAs = array('Test3' => array('bar'), 'Test2' => array('foo', 'bar')); - $Sample->Behaviors->init($Sample->alias, $Sample->actsAs); - $Sample->Behaviors->load('Test2'); - $Sample->Behaviors->unload('Test3'); - - $Sample->Behaviors->trigger('beforeTest', array(&$Sample)); - } - -/** - * test that hasMethod works with basic functions. - * - * @return void - */ - public function testHasMethodBasic() { - new Sample(); - $Collection = new BehaviorCollection(); - $Collection->init('Sample', array('Test', 'Test2')); - - $this->assertTrue($Collection->hasMethod('testMethod')); - $this->assertTrue($Collection->hasMethod('resolveMethod')); - - $this->assertFalse($Collection->hasMethod('No method')); - } - -/** - * test that hasMethod works with mapped methods. - * - * @return void - */ - public function testHasMethodMappedMethods() { - new Sample(); - $Collection = new BehaviorCollection(); - $Collection->init('Sample', array('Test', 'Test2')); - - $this->assertTrue($Collection->hasMethod('look for the remote in the couch')); - $this->assertTrue($Collection->hasMethod('mappingRobotOnTheRoof')); - } - -/** - * test hasMethod returning a 'callback' - * - * @return void - */ - public function testHasMethodAsCallback() { - new Sample(); - $Collection = new BehaviorCollection(); - $Collection->init('Sample', array('Test', 'Test2')); - - $result = $Collection->hasMethod('testMethod', true); - $expected = array('Test', 'testMethod'); - $this->assertEquals($expected, $result); - - $result = $Collection->hasMethod('resolveMethod', true); - $expected = array('Test2', 'resolveMethod'); - $this->assertEquals($expected, $result); - - $result = $Collection->hasMethod('mappingRobotOnTheRoof', true); - $expected = array('Test2', 'mapped', 'mappingRobotOnTheRoof'); - $this->assertEquals($expected, $result); - } - -/** - * Test that behavior priority - */ - public function testBehaviorOrderCallbacks() { - $model = ClassRegistry::init('Orangutan'); - $model->Behaviors->init('Orangutan', array( - 'Second' => array('priority' => 9), - 'Third', - 'First' => array('priority' => 8), - )); - - $this->assertEmpty($model->called); - - $model->find('first'); - $expected = array( - 'FirstBehavior', - 'SecondBehavior', - 'ThirdBehavior', - ); - $this->assertEquals($expected, $model->called); - - $model->called = array(); - $model->Behaviors->load('Third', array('priority' => 1)); - - $model->find('first'); - $expected = array( - 'ThirdBehavior', - 'FirstBehavior', - 'SecondBehavior' - ); - $this->assertEquals($expected, $model->called); - - $model->called = array(); - $model->Behaviors->load('First'); - - $model->find('first'); - $expected = array( - 'ThirdBehavior', - 'SecondBehavior', - 'FirstBehavior' - ); - $this->assertEquals($expected, $model->called); - - $model->called = array(); - $model->Behaviors->unload('Third'); - - $model->find('first'); - $expected = array( - 'SecondBehavior', - 'FirstBehavior' - ); - $this->assertEquals($expected, $model->called); - - $model->called = array(); - $model->Behaviors->disable('Second'); - - $model->find('first'); - $expected = array( - 'FirstBehavior' - ); - $this->assertEquals($expected, $model->called); - - $model->called = array(); - $model->Behaviors->enable('Second'); - - $model->find('first'); - $expected = array( - 'SecondBehavior', - 'FirstBehavior' - ); - $this->assertEquals($expected, $model->called); - } - -} diff --git a/Cake/Test/TestCase/Model/Datasource/DataSourceTest.php b/Cake/Test/TestCase/Model/Datasource/DataSourceTest.php deleted file mode 100644 index 3d52fe8bd9f..00000000000 --- a/Cake/Test/TestCase/Model/Datasource/DataSourceTest.php +++ /dev/null @@ -1,250 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice. - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model\Datasource; - -use Cake\Database\ConnectionManager; -use Cake\Model\Datasource\DataSource; -use Cake\Model\Model; -use Cake\TestSuite\TestCase; - -/** - * TestSource - * - */ -class TestSource extends DataSource { - -/** - * _schema - * @var type - */ - protected $_schema = array( - 'id' => array( - 'type' => 'integer', - 'null' => false, - 'key' => 'primary', - 'length' => 11, - ), - 'text' => array( - 'type' => 'string', - 'null' => true, - 'length' => 140, - ), - 'status' => array( - 'type' => 'string', - 'null' => true, - 'length' => 140, - ), - 'customField' => array( - 'type' => 'string', - 'null' => true, - 'length' => 255, - ), - ); - -/** - * listSources - * - * @return boolean - */ - public function listSources($data = null) { - return null; - } - -/** - * Returns the schema for the datasource to enable create/update - * - * @param object $Model - * @return array - */ - public function describe($Model) { - return $this->_schema; - } - -/** - * Just return $func to pass to read() to figure out the COUNT - * Required for delete/update to work - * - * @param Model $Model - * @param type $func - * @param type $params - * @return array - */ - public function calculate(Model $Model, $func, $params = array()) { - return $func; - } - -} - -/** - * DataSourceTest class - * - */ -class DataSourceTest extends TestCase { - -/** - * Name of test source - * - * @var string - */ - public $sourceName = 'myapitest'; - -/** - * setUp method - * - * @return void - */ - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Not working as models are not complete.'); - $this->Source = $this->getMock( - __NAMESPACE__ . '\TestSource', - array('create', 'read', 'update', 'delete') - ); - ConnectionManager::create($this->sourceName, array( - 'datasource' => get_class($this->Source), - 'apiKey' => '1234abcd', - )); - $this->Model = $this->getMock( - 'Cake\Model\Model', - array('getDataSource'), - array(array('ds' => $this->sourceName)) - ); - $this->Model->expects($this->any()) - ->method('getDataSource') - ->will($this->returnValue($this->Source)); - } - -/** - * tearDown method - * - * @return void - */ - public function tearDown() { - parent::tearDown(); - unset($this->Model, $this->Source); - ConnectionManager::drop($this->sourceName); - } - -/** - * testCreate - * - * @return void - */ - public function testCreate() { - $data = array( - $this->Model->alias => array( - 'text' => 'This is a test', - 'status' => 'Test status', - 'customField' => array( - 'array', 'field', 'type', - 'for', 'custom', 'datasources', - ), - ), - ); - $this->Source->expects($this->once()) - ->method('create') - ->with( - $this->equalTo($this->Model), - $this->equalTo(array_keys($data[$this->Model->alias])), - $this->equalTo(array_values($data[$this->Model->alias])) - ); - $this->Model->save($data); - } - -/** - * testRead - * - * @return void - */ - public function testRead() { - $expected = array( - 'conditions' => array('status' => 'test'), - 'fields' => null, - 'joins' => array(), - 'limit' => 10, - 'offset' => null, - 'order' => array(array('status')), - 'page' => 1, - 'group' => null, - 'callbacks' => true, - ); - $this->Source->expects($this->once()) - ->method('read') - ->with( - $this->anything(), - $this->equalTo($expected) - ); - $this->Model->find('all', array( - 'conditions' => array('status' => 'test'), - 'limit' => 10, - 'order' => array('status'), - )); - } - -/** - * testUpdate - * - * @return void - */ - public function testUpdate() { - $data = array( - $this->Model->alias => array( - 'id' => 1, - 'text' => 'This is a test', - 'status' => 'Test status', - 'customField' => array( - 'array', 'field', 'type', - 'for', 'custom', 'datasources', - ), - ), - ); - $this->Source->expects($this->any()) - ->method('read') - ->will($this->returnValue(array( - array($this->Model->alias => array('count' => 1)) - ))); - $this->Source->expects($this->once()) - ->method('update') - ->with( - $this->equalTo($this->Model), - $this->equalTo(array_keys($data[$this->Model->alias])), - $this->equalTo(array_values($data[$this->Model->alias])) - ); - $this->Model->save($data); - } - -/** - * testDelete - * - * @return void - */ - public function testDelete() { - $this->Source->expects($this->any()) - ->method('read') - ->will($this->returnValue(array( - array($this->Model->alias => array('count' => 1)) - ))); - $this->Source->expects($this->once()) - ->method('delete') - ->with( - $this->equalTo($this->Model), - $this->equalTo(array($this->Model->alias . '.id' => 1)) - ); - $this->Model->delete(1); - } - -} diff --git a/Cake/Test/TestCase/Model/ModelCrossSchemaHabtmTest.php b/Cake/Test/TestCase/Model/ModelCrossSchemaHabtmTest.php deleted file mode 100644 index 57734bd3ff1..00000000000 --- a/Cake/Test/TestCase/Model/ModelCrossSchemaHabtmTest.php +++ /dev/null @@ -1,239 +0,0 @@ - false on *both* database connections, - * or one connection will step on the other. - * - * CakePHP(tm) Tests - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 2.1 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Model\Model; -use Cake\Model\ModelBehavior; -use Cake\TestSuite\TestCase; -use Cake\Test\TestCase\Model\ModelTestBase; - -/** - * Class ModelCrossSchemaHabtmTest - * - */ -class ModelCrossSchemaHabtmTest extends ModelTestBase { - -/** - * Fixtures to be used - * - * @var array - */ - public $fixtures = array( - 'core.player', 'core.guild', 'core.guilds_player', - 'core.armor', 'core.armors_player', - ); - -/** - * Don't drop tables if they exist - * - * @var boolean - */ - public $dropTables = false; - -/** - * Don't auto load fixtures - * - * @var boolean - */ - public $autoFixtures = false; - -/** - * setUp method - * - * @return void - */ - public function setUp() { - parent::setUp(); - $this->_checkConfigs(); - } - -/** - * Check if primary and secondary test databases are configured. - * - * @return void - */ - protected function _checkConfigs() { - $config = ConnectionManager::enumConnectionObjects(); - $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.'); - $this->skipIf( - !isset($config['test']) || !isset($config['test2']), - 'Primary and secondary test databases not configured, ' . - 'skipping cross-database join tests.' . - ' To run these tests, you must define $test and $test2 in your database configuration.' - ); - } - -/** - * testModelDatasources method - * - * @return void - */ - public function testModelDatasources() { - $this->loadFixtures('Player', 'Guild', 'GuildsPlayer'); - - $Player = ClassRegistry::init('Player'); - $this->assertEquals('test', $Player->useDbConfig); - $this->assertEquals('test', $Player->Guild->useDbConfig); - $this->assertEquals('test2', $Player->GuildsPlayer->useDbConfig); - - $this->assertEquals('test', $Player->getDataSource()->configKeyName); - $this->assertEquals('test', $Player->Guild->getDataSource()->configKeyName); - $this->assertEquals('test2', $Player->GuildsPlayer->getDataSource()->configKeyName); - } - -/** - * testHabtmFind method - * - * @return void - */ - public function testHabtmFind() { - $this->loadFixtures('Player', 'Guild', 'GuildsPlayer'); - $Player = ClassRegistry::init('Player'); - - $players = $Player->find('all', array( - 'fields' => array('id', 'name'), - 'contain' => array( - 'Guild' => array( - 'conditions' => array( - 'Guild.name' => 'Wizards', - ), - ), - ), - )); - $this->assertEquals(4, count($players)); - $wizards = Hash::extract($players, '{n}.Guild.{n}[name=Wizards]'); - $this->assertEquals(1, count($wizards)); - - $players = $Player->find('all', array( - 'fields' => array('id', 'name'), - 'conditions' => array( - 'Player.id' => 1, - ), - )); - $this->assertEquals(1, count($players)); - $wizards = Hash::extract($players, '{n}.Guild.{n}'); - $this->assertEquals(2, count($wizards)); - } - -/** - * testHabtmSave method - * - * @return void - */ - public function testHabtmSave() { - $this->loadFixtures('Player', 'Guild', 'GuildsPlayer'); - $Player = ClassRegistry::init('Player'); - $players = $Player->find('count'); - $this->assertEquals(4, $players); - - $player = $Player->create(array( - 'name' => 'rchavik', - )); - - $results = $Player->saveAll($player, array('validate' => 'first')); - $this->assertNotSame(false, $results); - $count = $Player->find('count'); - $this->assertEquals(5, $count); - - $count = $Player->GuildsPlayer->find('count'); - $this->assertEquals(3, $count); - - $player = $Player->findByName('rchavik'); - $this->assertEmpty($player['Guild']); - - $player['Guild']['Guild'] = array(1, 2, 3); - $Player->save($player); - - $player = $Player->findByName('rchavik'); - $this->assertEquals(3, count($player['Guild'])); - - $players = $Player->find('all', array( - 'contain' => array( - 'conditions' => array( - 'Guild.name' => 'Rangers', - ), - ), - )); - $rangers = Hash::extract($players, '{n}.Guild.{n}[name=Rangers]'); - $this->assertEquals(2, count($rangers)); - } - -/** - * testHabtmWithThreeDatabases method - * - * @return void - */ - public function testHabtmWithThreeDatabases() { - $config = ConnectionManager::enumConnectionObjects(); - $this->skipIf( - !isset($config['test']) || !isset($config['test2']) || !isset($config['test_database_three']), - 'Primary, secondary, and tertiary test databases not configured,' . - ' skipping test. To run these tests, you must define ' . - '$test, $test2, and $test_database_three in your database configuration.' - ); - - $this->loadFixtures('Player', 'Guild', 'GuildsPlayer', 'Armor', 'ArmorsPlayer'); - - $Player = ClassRegistry::init('Player'); - $Player->bindModel(array( - 'hasAndBelongsToMany' => array( - 'Armor' => array( - 'with' => 'ArmorsPlayer', - 'unique' => true, - ), - ), - ), false); - $this->assertEquals('test', $Player->useDbConfig); - $this->assertEquals('test2', $Player->Armor->useDbConfig); - $this->assertEquals('test_database_three', $Player->ArmorsPlayer->useDbConfig); - $players = $Player->find('count'); - $this->assertEquals(4, $players); - - $spongebob = $Player->create(array( - 'id' => 10, - 'name' => 'spongebob', - )); - $spongebob['Armor'] = array('Armor' => array(1, 2, 3, 4)); - $result = $Player->save($spongebob); - - $expected = array( - 'Player' => array( - 'id' => 10, - 'name' => 'spongebob', - ), - 'Armor' => array( - 'Armor' => array( - 1, 2, 3, 4, - ), - ), - ); - unset($result['Player']['created']); - unset($result['Player']['updated']); - $this->assertEquals($expected, $result); - - $spongebob = $Player->find('all', array( - 'conditions' => array( - 'Player.id' => 10, - ) - )); - $spongeBobsArmors = Hash::extract($spongebob, '{n}.Armor.{n}'); - $this->assertEquals(4, count($spongeBobsArmors)); - } -} diff --git a/Cake/Test/TestCase/Model/ModelDeleteTest.php b/Cake/Test/TestCase/Model/ModelDeleteTest.php deleted file mode 100644 index 8b6a4705579..00000000000 --- a/Cake/Test/TestCase/Model/ModelDeleteTest.php +++ /dev/null @@ -1,952 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Model\Model; -use Cake\Model\ModelBehavior; -use Cake\TestSuite\TestCase; -use Cake\Test\TestCase\Model\ModelTestBase; - -/** - * ModelDeleteTest - * - */ -class ModelDeleteTest extends ModelTestBase { - -/** - * testDeleteHabtmReferenceWithConditions method - * - * @return void - */ - public function testDeleteHabtmReferenceWithConditions() { - $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio', 'Syfile', 'Image'); - - $Portfolio = new Portfolio(); - $Portfolio->hasAndBelongsToMany['Item']['conditions'] = array('ItemsPortfolio.item_id >' => 1); - - $result = $Portfolio->find('first', array( - 'conditions' => array('Portfolio.id' => 1) - )); - $expected = array( - array( - 'id' => 3, - 'syfile_id' => 3, - 'published' => false, - 'name' => 'Item 3', - 'ItemsPortfolio' => array( - 'id' => 3, - 'item_id' => 3, - 'portfolio_id' => 1 - )), - array( - 'id' => 4, - 'syfile_id' => 4, - 'published' => false, - 'name' => 'Item 4', - 'ItemsPortfolio' => array( - 'id' => 4, - 'item_id' => 4, - 'portfolio_id' => 1 - )), - array( - 'id' => 5, - 'syfile_id' => 5, - 'published' => false, - 'name' => 'Item 5', - 'ItemsPortfolio' => array( - 'id' => 5, - 'item_id' => 5, - 'portfolio_id' => 1 - ))); - $this->assertEquals($expected, $result['Item']); - - $result = $Portfolio->ItemsPortfolio->find('all', array( - 'conditions' => array('ItemsPortfolio.portfolio_id' => 1) - )); - $expected = array( - array( - 'ItemsPortfolio' => array( - 'id' => 1, - 'item_id' => 1, - 'portfolio_id' => 1 - )), - array( - 'ItemsPortfolio' => array( - 'id' => 3, - 'item_id' => 3, - 'portfolio_id' => 1 - )), - array( - 'ItemsPortfolio' => array( - 'id' => 4, - 'item_id' => 4, - 'portfolio_id' => 1 - )), - array( - 'ItemsPortfolio' => array( - 'id' => 5, - 'item_id' => 5, - 'portfolio_id' => 1 - ))); - $this->assertEquals($expected, $result); - - $Portfolio->delete(1); - - $result = $Portfolio->find('first', array( - 'conditions' => array('Portfolio.id' => 1) - )); - $this->assertSame(array(), $result); - - $result = $Portfolio->ItemsPortfolio->find('all', array( - 'conditions' => array('ItemsPortfolio.portfolio_id' => 1) - )); - $this->assertSame(array(), $result); - } - -/** - * testDeleteArticleBLinks method - * - * @return void - */ - public function testDeleteArticleBLinks() { - $this->loadFixtures('Article', 'ArticlesTag', 'Tag', 'User'); - $TestModel = new ArticleB(); - - $result = $TestModel->ArticlesTag->find('all'); - $expected = array( - array('ArticlesTag' => array('article_id' => '1', 'tag_id' => '1')), - array('ArticlesTag' => array('article_id' => '1', 'tag_id' => '2')), - array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '1')), - array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '3')) - ); - $this->assertEquals($expected, $result); - - $TestModel->delete(1); - $result = $TestModel->ArticlesTag->find('all'); - - $expected = array( - array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '1')), - array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '3')) - ); - $this->assertEquals($expected, $result); - } - -/** - * testDeleteDependentWithConditions method - * - * @return void - */ - public function testDeleteDependentWithConditions() { - $this->loadFixtures('Cd', 'Book', 'OverallFavorite'); - - $Cd = new Cd(); - $Book = new Book(); - $OverallFavorite = new OverallFavorite(); - - $Cd->delete(1); - - $result = $OverallFavorite->find('all', array( - 'fields' => array('model_type', 'model_id', 'priority') - )); - $expected = array( - array( - 'OverallFavorite' => array( - 'model_type' => 'Book', - 'model_id' => 1, - 'priority' => 2 - ))); - - $this->assertTrue(is_array($result)); - $this->assertEquals($expected, $result); - - $Book->delete(1); - - $result = $OverallFavorite->find('all', array( - 'fields' => array('model_type', 'model_id', 'priority') - )); - $expected = array(); - - $this->assertTrue(is_array($result)); - $this->assertEquals($expected, $result); - } - -/** - * testDel method - * - * @return void - */ - public function testDelete() { - $this->loadFixtures('Article', 'Comment', 'Attachment'); - $TestModel = new Article(); - - $result = $TestModel->delete(2); - $this->assertTrue($result); - - $result = $TestModel->read(null, 2); - $this->assertSame(array(), $result); - - $TestModel->recursive = -1; - $result = $TestModel->find('all', array( - 'fields' => array('id', 'title') - )); - $expected = array( - array('Article' => array( - 'id' => 1, - 'title' => 'First Article' - )), - array('Article' => array( - 'id' => 3, - 'title' => 'Third Article' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->delete(3); - $this->assertTrue($result); - - $result = $TestModel->read(null, 3); - $this->assertSame(array(), $result); - - $TestModel->recursive = -1; - $result = $TestModel->find('all', array( - 'fields' => array('id', 'title') - )); - $expected = array( - array('Article' => array( - 'id' => 1, - 'title' => 'First Article' - ))); - - $this->assertEquals($expected, $result); - - // make sure deleting a non-existent record doesn't break save() - // ticket #6293 - $this->loadFixtures('Uuid'); - $Uuid = new Uuid(); - $data = array( - 'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3', - '52C8865C-10EE-4302-AE6C-6E7D8E12E2C8', - '8208C7FE-E89C-47C5-B378-DED6C271F9B8'); - foreach ($data as $id) { - $Uuid->save(array('id' => $id)); - } - $Uuid->delete('52C8865C-10EE-4302-AE6C-6E7D8E12E2C8'); - $Uuid->delete('52C8865C-10EE-4302-AE6C-6E7D8E12E2C8'); - foreach ($data as $id) { - $Uuid->save(array('id' => $id)); - } - $result = $Uuid->find('all', array( - 'conditions' => array('id' => $data), - 'fields' => array('id'), - 'order' => 'id')); - $expected = array( - array('Uuid' => array( - 'id' => '52C8865C-10EE-4302-AE6C-6E7D8E12E2C8')), - array('Uuid' => array( - 'id' => '8208C7FE-E89C-47C5-B378-DED6C271F9B8')), - array('Uuid' => array( - 'id' => 'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3'))); - $this->assertEquals($expected, $result); - } - -/** - * test that delete() updates the correct records counterCache() records. - * - * @return void - */ - public function testDeleteUpdatingCounterCacheCorrectly() { - $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); - $User = new CounterCacheUser(); - - $User->Post->delete(3); - $result = $User->read(null, 301); - $this->assertEquals(0, $result['User']['post_count']); - - $result = $User->read(null, 66); - $this->assertEquals(2, $result['User']['post_count']); - } - -/** - * testDeleteAll method - * - * @return void - */ - public function testDeleteAll() { - $this->loadFixtures('Article'); - $TestModel = new Article(); - - $data = array('Article' => array( - 'user_id' => 2, - 'id' => 4, - 'title' => 'Fourth Article', - 'published' => 'N' - )); - $result = $TestModel->set($data) && $TestModel->save(); - $this->assertTrue($result); - - $data = array('Article' => array( - 'user_id' => 2, - 'id' => 5, - 'title' => 'Fifth Article', - 'published' => 'Y' - )); - $result = $TestModel->set($data) && $TestModel->save(); - $this->assertTrue($result); - - $data = array('Article' => array( - 'user_id' => 1, - 'id' => 6, - 'title' => 'Sixth Article', - 'published' => 'N' - )); - $result = $TestModel->set($data) && $TestModel->save(); - $this->assertTrue($result); - - $TestModel->recursive = -1; - $result = $TestModel->find('all', array( - 'fields' => array('id', 'user_id', 'title', 'published'), - 'order' => array('Article.id' => 'ASC') - )); - - $expected = array( - array('Article' => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'published' => 'Y' - )), - array('Article' => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'published' => 'Y' - )), - array('Article' => array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Article', - 'published' => 'Y')), - array('Article' => array( - 'id' => 4, - 'user_id' => 2, - 'title' => 'Fourth Article', - 'published' => 'N' - )), - array('Article' => array( - 'id' => 5, - 'user_id' => 2, - 'title' => 'Fifth Article', - 'published' => 'Y' - )), - array('Article' => array( - 'id' => 6, - 'user_id' => 1, - 'title' => 'Sixth Article', - 'published' => 'N' - ))); - - $this->assertEquals($expected, $result); - - $result = $TestModel->deleteAll(array('Article.published' => 'N')); - $this->assertTrue($result); - - $TestModel->recursive = -1; - $result = $TestModel->find('all', array( - 'fields' => array('id', 'user_id', 'title', 'published'), - 'order' => array('Article.id' => 'ASC') - )); - $expected = array( - array('Article' => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'published' => 'Y' - )), - array('Article' => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'published' => 'Y' - )), - array('Article' => array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Article', - 'published' => 'Y' - )), - array('Article' => array( - 'id' => 5, - 'user_id' => 2, - 'title' => 'Fifth Article', - 'published' => 'Y' - ))); - $this->assertEquals($expected, $result); - - $data = array('Article.user_id' => array(2, 3)); - $result = $TestModel->deleteAll($data, true, true); - $this->assertTrue($result); - - $TestModel->recursive = -1; - $result = $TestModel->find('all', array( - 'fields' => array('id', 'user_id', 'title', 'published'), - 'order' => array('Article.id' => 'ASC') - )); - $expected = array( - array('Article' => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'published' => 'Y' - )), - array('Article' => array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Article', - 'published' => 'Y' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->deleteAll(array('Article.user_id' => 999)); - $this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s'); - } - -/** - * testDeleteAllUnknownColumn method - * - * @expectedException PDOException - * @return void - */ - public function testDeleteAllUnknownColumn() { - $this->loadFixtures('Article'); - $TestModel = new Article(); - $result = $TestModel->deleteAll(array('Article.non_existent_field' => 999)); - $this->assertFalse($result, 'deleteAll returned true when find query generated sql error. %s'); - } - -/** - * testDeleteAllFailedFind method - * - * Eg: Behavior callback stops the event, find returns null - * - * @return void - */ - public function testDeleteAllFailedFind() { - $this->loadFixtures('Article'); - $this->getMock('Article', array('find'), array(), 'ArticleDeleteAll'); - - $TestModel = new ArticleDeleteAll(); - $TestModel->expects($this->once()) - ->method('find') - ->will($this->returnValue(null)); - - $result = $TestModel->deleteAll(array('Article.user_id' => 999)); - $this->assertFalse($result); - } - -/** - * testDeleteAllMultipleRowsPerId method - * - * Ensure find done in deleteAll only returns distinct ids. A wacky combination - * of association and conditions can sometimes generate multiple rows per id. - * - * @return void - */ - public function testDeleteAllMultipleRowsPerId() { - $this->loadFixtures('Article', 'User'); - - $TestModel = new Article(); - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment'), - 'hasAndBelongsToMany' => array('Tag') - ), false); - $TestModel->bindModel(array( - 'belongsTo' => array( - 'User' => array( - 'foreignKey' => false, - 'conditions' => array( - 'Article.user_id = 1' - ) - ) - ) - ), false); - - $result = $TestModel->deleteAll( - array('Article.user_id' => array(1, 3)), - true, - true - ); - - $this->assertTrue($result); - } - -/** - * testDeleteAllWithOrderProperty - * - * Ensure find done in deleteAll works with models that has $order property set - * - * @return void - */ - public function testDeleteAllWithOrderProperty() { - $this->loadFixtures('Article', 'User'); - - $TestModel = new Article(); - $TestModel->order = 'Article.published desc'; - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment'), - 'hasAndBelongsToMany' => array('Tag') - ), false); - - $result = $TestModel->deleteAll( - array('Article.user_id' => array(1, 3)), - true, - true - ); - - $this->assertTrue($result); - } - -/** - * testRecursiveDel method - * - * @return void - */ - public function testRecursiveDel() { - $this->loadFixtures('Article', 'Comment', 'Attachment'); - $TestModel = new Article(); - - $result = $TestModel->delete(2); - $this->assertTrue($result); - - $TestModel->recursive = 2; - $result = $TestModel->read(null, 2); - $this->assertSame(array(), $result); - - $result = $TestModel->Comment->read(null, 5); - $this->assertSame(array(), $result); - - $result = $TestModel->Comment->read(null, 6); - $this->assertSame(array(), $result); - - $result = $TestModel->Comment->Attachment->read(null, 1); - $this->assertSame(array(), $result); - - $result = $TestModel->find('count'); - $this->assertEquals(2, $result); - - $result = $TestModel->Comment->find('count'); - $this->assertEquals(4, $result); - - $result = $TestModel->Comment->Attachment->find('count'); - $this->assertEquals(0, $result); - } - -/** - * testDependentExclusiveDelete method - * - * @return void - */ - public function testDependentExclusiveDelete() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article10(); - - $result = $TestModel->find('all'); - $this->assertEquals(4, count($result[0]['Comment'])); - $this->assertEquals(2, count($result[1]['Comment'])); - $this->assertEquals(6, $TestModel->Comment->find('count')); - - $TestModel->delete(1); - $this->assertEquals(2, $TestModel->Comment->find('count')); - } - -/** - * testDeleteLinks method - * - * @return void - */ - public function testDeleteLinks() { - $this->loadFixtures('Article', 'ArticlesTag', 'Tag'); - $TestModel = new Article(); - - $result = $TestModel->ArticlesTag->find('all'); - $expected = array( - array('ArticlesTag' => array( - 'article_id' => '1', - 'tag_id' => '1' - )), - array('ArticlesTag' => array( - 'article_id' => '1', - 'tag_id' => '2' - )), - array('ArticlesTag' => array( - 'article_id' => '2', - 'tag_id' => '1' - )), - array('ArticlesTag' => array( - 'article_id' => '2', - 'tag_id' => '3' - ))); - $this->assertEquals($expected, $result); - - $TestModel->delete(1); - $result = $TestModel->ArticlesTag->find('all'); - - $expected = array( - array('ArticlesTag' => array( - 'article_id' => '2', - 'tag_id' => '1' - )), - array('ArticlesTag' => array( - 'article_id' => '2', - 'tag_id' => '3' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->deleteAll(array('Article.user_id' => 999)); - $this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s'); - } - -/** - * test that a plugin model as the 'with' model doesn't have issues - * - * @return void - */ - public function testDeleteLinksWithPLuginJoinModel() { - $this->loadFixtures('Article', 'ArticlesTag', 'Tag'); - $Article = new Article(); - $Article->unbindModel(array('hasAndBelongsToMany' => array('Tag')), false); - unset($Article->Tag, $Article->ArticleTags); - $Article->bindModel(array('hasAndBelongsToMany' => array( - 'Tag' => array('with' => 'TestPlugin.ArticlesTag') - )), false); - - $Article->ArticlesTag->order = null; - $this->assertTrue($Article->delete(1)); - } - -/** - * testDeleteDependent method - * - * @return void - */ - public function testDeleteDependent() { - $this->loadFixtures('Bidding', 'BiddingMessage', 'Article', - 'ArticlesTag', 'Comment', 'User', 'Attachment' - ); - $Bidding = new Bidding(); - $result = $Bidding->find('all', array('order' => array('Bidding.id' => 'ASC'))); - $expected = array( - array( - 'Bidding' => array('id' => 1, 'bid' => 'One', 'name' => 'Bid 1'), - 'BiddingMessage' => array('bidding' => 'One', 'name' => 'Message 1'), - ), - array( - 'Bidding' => array('id' => 2, 'bid' => 'Two', 'name' => 'Bid 2'), - 'BiddingMessage' => array('bidding' => 'Two', 'name' => 'Message 2'), - ), - array( - 'Bidding' => array('id' => 3, 'bid' => 'Three', 'name' => 'Bid 3'), - 'BiddingMessage' => array('bidding' => 'Three', 'name' => 'Message 3'), - ), - array( - 'Bidding' => array('id' => 4, 'bid' => 'Five', 'name' => 'Bid 5'), - 'BiddingMessage' => array('bidding' => '', 'name' => ''), - ), - ); - $this->assertEquals($expected, $result); - - $Bidding->delete(4, true); - $result = $Bidding->find('all', array('order' => array('Bidding.id' => 'ASC'))); - $expected = array( - array( - 'Bidding' => array('id' => 1, 'bid' => 'One', 'name' => 'Bid 1'), - 'BiddingMessage' => array('bidding' => 'One', 'name' => 'Message 1'), - ), - array( - 'Bidding' => array('id' => 2, 'bid' => 'Two', 'name' => 'Bid 2'), - 'BiddingMessage' => array('bidding' => 'Two', 'name' => 'Message 2'), - ), - array( - 'Bidding' => array('id' => 3, 'bid' => 'Three', 'name' => 'Bid 3'), - 'BiddingMessage' => array('bidding' => 'Three', 'name' => 'Message 3'), - ), - ); - $this->assertEquals($expected, $result); - - $Bidding->delete(2, true); - $result = $Bidding->find('all', array('order' => array('Bidding.id' => 'ASC'))); - $expected = array( - array( - 'Bidding' => array('id' => 1, 'bid' => 'One', 'name' => 'Bid 1'), - 'BiddingMessage' => array('bidding' => 'One', 'name' => 'Message 1'), - ), - array( - 'Bidding' => array('id' => 3, 'bid' => 'Three', 'name' => 'Bid 3'), - 'BiddingMessage' => array('bidding' => 'Three', 'name' => 'Message 3'), - ), - ); - $this->assertEquals($expected, $result); - - $result = $Bidding->BiddingMessage->find('all', array('order' => array('BiddingMessage.name' => 'ASC'))); - $expected = array( - array( - 'BiddingMessage' => array('bidding' => 'One', 'name' => 'Message 1'), - 'Bidding' => array('id' => 1, 'bid' => 'One', 'name' => 'Bid 1'), - ), - array( - 'BiddingMessage' => array('bidding' => 'Three', 'name' => 'Message 3'), - 'Bidding' => array('id' => 3, 'bid' => 'Three', 'name' => 'Bid 3'), - ), - array( - 'BiddingMessage' => array('bidding' => 'Four', 'name' => 'Message 4'), - 'Bidding' => array('id' => '', 'bid' => '', 'name' => ''), - ), - ); - $this->assertEquals($expected, $result); - - $Article = new Article(); - $result = $Article->Comment->find('count', array( - 'conditions' => array('Comment.article_id' => 1) - )); - $this->assertEquals(4, $result); - - $result = $Article->delete(1, true); - $this->assertTrue($result); - - $result = $Article->Comment->find('count', array( - 'conditions' => array('Comment.article_id' => 1) - )); - $this->assertEquals(0, $result); - } - -/** - * test deleteLinks with Multiple habtm associations - * - * @return void - */ - public function testDeleteLinksWithMultipleHabtmAssociations() { - $this->loadFixtures('JoinA', 'JoinB', 'JoinC', 'JoinAB', 'JoinAC'); - $JoinA = new JoinA(); - - //create two new join records to expose the issue. - $JoinA->JoinAsJoinC->create(array( - 'join_a_id' => 1, - 'join_c_id' => 2, - )); - $JoinA->JoinAsJoinC->save(); - $JoinA->JoinAsJoinB->create(array( - 'join_a_id' => 1, - 'join_b_id' => 2, - )); - $JoinA->JoinAsJoinB->save(); - - $result = $JoinA->delete(1); - $this->assertTrue($result, 'Delete failed %s'); - - $joinedBs = $JoinA->JoinAsJoinB->find('count', array( - 'conditions' => array('JoinAsJoinB.join_a_id' => 1) - )); - $this->assertEquals(0, $joinedBs, 'JoinA/JoinB link records left over. %s'); - - $joinedBs = $JoinA->JoinAsJoinC->find('count', array( - 'conditions' => array('JoinAsJoinC.join_a_id' => 1) - )); - $this->assertEquals(0, $joinedBs, 'JoinA/JoinC link records left over. %s'); - } - -/** - * testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable method - * - * @return void - */ - public function testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable() { - $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies'); - $ThePaper = new ThePaper(); - $ThePaper->id = 1; - $ThePaper->save(array('Monkey' => array(2, 3))); - - $result = $ThePaper->findById(1); - $expected = array( - array( - 'id' => '2', - 'device_type_id' => '1', - 'name' => 'Device 2', - 'typ' => '1' - ), - array( - 'id' => '3', - 'device_type_id' => '1', - 'name' => 'Device 3', - 'typ' => '2' - )); - $this->assertEquals($expected, $result['Monkey']); - - $ThePaper = new ThePaper(); - $ThePaper->id = 2; - $ThePaper->save(array('Monkey' => array(2, 3))); - - $result = $ThePaper->findById(2); - $expected = array( - array( - 'id' => '2', - 'device_type_id' => '1', - 'name' => 'Device 2', - 'typ' => '1' - ), - array( - 'id' => '3', - 'device_type_id' => '1', - 'name' => 'Device 3', - 'typ' => '2' - )); - $this->assertEquals($expected, $result['Monkey']); - - $ThePaper->delete(1); - $result = $ThePaper->findById(2); - $expected = array( - array( - 'id' => '2', - 'device_type_id' => '1', - 'name' => 'Device 2', - 'typ' => '1' - ), - array( - 'id' => '3', - 'device_type_id' => '1', - 'name' => 'Device 3', - 'typ' => '2' - )); - $this->assertEquals($expected, $result['Monkey']); - } - -/** - * test that beforeDelete returning false can abort deletion. - * - * @return void - */ - public function testBeforeDeleteDeleteAbortion() { - $this->loadFixtures('Post'); - $Model = new CallbackPostTestModel(); - $Model->beforeDeleteReturn = false; - - $result = $Model->delete(1); - $this->assertFalse($result); - - $exists = $Model->findById(1); - $this->assertTrue(is_array($exists)); - } - -/** - * test for a habtm deletion error that occurs in postgres but should not. - * And should not occur in any dbo. - * - * @return void - */ - public function testDeleteHabtmPostgresFailure() { - $this->loadFixtures('Article', 'Tag', 'ArticlesTag'); - - $Article = ClassRegistry::init('Article'); - $Article->hasAndBelongsToMany['Tag']['unique'] = true; - - $Tag = ClassRegistry::init('Tag'); - $Tag->bindModel(array('hasAndBelongsToMany' => array( - 'Article' => array( - 'className' => 'Article', - 'unique' => true - ) - )), true); - - // Article 1 should have Tag.1 and Tag.2 - $before = $Article->find("all", array( - "conditions" => array("Article.id" => 1), - )); - $this->assertEquals(2, count($before[0]['Tag']), 'Tag count for Article.id = 1 is incorrect, should be 2 %s'); - - // From now on, Tag #1 is only associated with Post #1 - $submittedData = array( - "Tag" => array("id" => 1, 'tag' => 'tag1'), - "Article" => array( - "Article" => array(1) - ) - ); - $Tag->save($submittedData); - - // One more submission (The other way around) to make sure the reverse save looks good. - $submittedData = array( - "Article" => array("id" => 2, 'title' => 'second article'), - "Tag" => array( - "Tag" => array(2, 3) - ) - ); - - // ERROR: - // Postgresql: DELETE FROM "articles_tags" WHERE tag_id IN ('1', '3') - // MySQL: DELETE `ArticlesTag` FROM `articles_tags` AS `ArticlesTag` WHERE `ArticlesTag`.`article_id` = 2 AND `ArticlesTag`.`tag_id` IN (1, 3) - $Article->save($submittedData); - - // Want to make sure Article #1 has Tag #1 and Tag #2 still. - $after = $Article->find("all", array( - "conditions" => array("Article.id" => 1), - )); - - // Removing Article #2 from Tag #1 is all that should have happened. - $this->assertEquals(count($before[0]["Tag"]), count($after[0]["Tag"])); - } - -/** - * test that deleting records inside the beforeDelete doesn't truncate the table. - * - * @return void - */ - public function testBeforeDeleteWipingTable() { - $this->loadFixtures('Comment'); - - $Comment = new BeforeDeleteComment(); - // Delete 3 records. - $Comment->delete(4); - $result = $Comment->find('count'); - - $this->assertTrue($result > 1, 'Comments are all gone.'); - $Comment->create(array( - 'article_id' => 1, - 'user_id' => 2, - 'comment' => 'new record', - 'published' => 'Y' - )); - $Comment->save(); - - $Comment->delete(5); - $result = $Comment->find('count'); - - $this->assertTrue($result > 1, 'Comments are all gone.'); - } - -/** - * test that deleting the same record from the beforeDelete and the delete doesn't truncate the table. - * - * @return void - */ - public function testBeforeDeleteWipingTableWithDuplicateDelete() { - $this->loadFixtures('Comment'); - - $Comment = new BeforeDeleteComment(); - $Comment->delete(1); - - $result = $Comment->find('count'); - $this->assertTrue($result > 1, 'Comments are all gone.'); - } -} diff --git a/Cake/Test/TestCase/Model/ModelIntegrationTest.php b/Cake/Test/TestCase/Model/ModelIntegrationTest.php deleted file mode 100644 index efb8478b9bf..00000000000 --- a/Cake/Test/TestCase/Model/ModelIntegrationTest.php +++ /dev/null @@ -1,2441 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Database\ConnectionManager; -use Cake\Model\Model; -use Cake\Model\ModelBehavior; -use Cake\TestSuite\TestCase; -use Cake\Test\TestCase\Model\ModelTestBase; -use Cake\Utility\Hash; - -/** - * ModelIntegrationTest - * - */ -class ModelIntegrationTest extends ModelTestBase { - -/** - * testAssociationLazyLoading - * - * @group lazyloading - * @return void - */ - public function testAssociationLazyLoading() { - $this->loadFixtures('ArticleFeaturedsTags'); - $Article = new ArticleFeatured(); - $this->assertTrue(isset($Article->belongsTo['User'])); - $this->assertFalse(property_exists($Article, 'User')); - $this->assertInstanceOf('User', $Article->User); - - $this->assertTrue(isset($Article->belongsTo['Category'])); - $this->assertFalse(property_exists($Article, 'Category')); - $this->assertTrue(isset($Article->Category)); - $this->assertInstanceOf('Category', $Article->Category); - - $this->assertTrue(isset($Article->hasMany['Comment'])); - $this->assertFalse(property_exists($Article, 'Comment')); - $this->assertTrue(isset($Article->Comment)); - $this->assertInstanceOf('Comment', $Article->Comment); - - $this->assertTrue(isset($Article->hasAndBelongsToMany['Tag'])); - //There was not enough information to setup the association (joinTable and associationForeignKey) - //so the model was not lazy loaded - $this->assertTrue(property_exists($Article, 'Tag')); - $this->assertTrue(isset($Article->Tag)); - $this->assertInstanceOf('Tag', $Article->Tag); - - $this->assertFalse(property_exists($Article, 'ArticleFeaturedsTag')); - $this->assertInstanceOf('AppModel', $Article->ArticleFeaturedsTag); - $this->assertEquals('article_featureds_tags', $Article->hasAndBelongsToMany['Tag']['joinTable']); - $this->assertEquals('tag_id', $Article->hasAndBelongsToMany['Tag']['associationForeignKey']); - } - -/** - * testAssociationLazyLoadWithHABTM - * - * @group lazyloading - * @return void - */ - public function testAssociationLazyLoadWithHABTM() { - $this->loadFixtures('FruitsUuidTag', 'ArticlesTag'); - $this->db->cacheSources = false; - $Article = new ArticleB(); - $this->assertTrue(isset($Article->hasAndBelongsToMany['TagB'])); - $this->assertFalse(property_exists($Article, 'TagB')); - $this->assertInstanceOf('TagB', $Article->TagB); - - $this->assertFalse(property_exists($Article, 'ArticlesTag')); - $this->assertInstanceOf('AppModel', $Article->ArticlesTag); - - $UuidTag = new UuidTag(); - $this->assertTrue(isset($UuidTag->hasAndBelongsToMany['Fruit'])); - $this->assertFalse(property_exists($UuidTag, 'Fruit')); - $this->assertFalse(property_exists($UuidTag, 'FruitsUuidTag')); - $this->assertTrue(isset($UuidTag->Fruit)); - - $this->assertFalse(property_exists($UuidTag, 'FruitsUuidTag')); - $this->assertTrue(isset($UuidTag->FruitsUuidTag)); - $this->assertInstanceOf('FruitsUuidTag', $UuidTag->FruitsUuidTag); - } - -/** - * testAssociationLazyLoadWithBindModel - * - * @group lazyloading - * @return void - */ - public function testAssociationLazyLoadWithBindModel() { - $this->loadFixtures('Article', 'User'); - $Article = new ArticleB(); - - $this->assertFalse(isset($Article->belongsTo['User'])); - $this->assertFalse(property_exists($Article, 'User')); - - $Article->bindModel(array('belongsTo' => array('User'))); - $this->assertTrue(isset($Article->belongsTo['User'])); - $this->assertFalse(property_exists($Article, 'User')); - $this->assertInstanceOf('User', $Article->User); - } - -/** - * Tests that creating a model with no existent database table associated will throw an exception - * - * @expectedException MissingTableException - * @return void - */ - public function testMissingTable() { - $Article = new ArticleB(false, uniqid()); - $Article->schema(); - } - -/** - * testPkInHAbtmLinkModelArticleB - * - * @return void - */ - public function testPkInHabtmLinkModelArticleB() { - $this->loadFixtures('Article', 'Tag', 'ArticlesTag'); - $TestModel = new ArticleB(); - $this->assertEquals('article_id', $TestModel->ArticlesTag->primaryKey); - } - -/** - * Tests that $cacheSources is restored despite the settings on the model. - * - * @return void - */ - public function testCacheSourcesRestored() { - $this->loadFixtures('JoinA', 'JoinB', 'JoinAB', 'JoinC', 'JoinAC'); - $this->db->cacheSources = true; - $TestModel = new JoinA(); - $TestModel->cacheSources = false; - $TestModel->setSource('join_as'); - $this->assertTrue($this->db->cacheSources); - - $this->db->cacheSources = false; - $TestModel = new JoinA(); - $TestModel->cacheSources = true; - $TestModel->setSource('join_as'); - $this->assertFalse($this->db->cacheSources); - } - -/** - * testPkInHabtmLinkModel method - * - * @return void - */ - public function testPkInHabtmLinkModel() { - //Test Nonconformant Models - $this->loadFixtures('Content', 'ContentAccount', 'Account', 'JoinC', 'JoinAC', 'ItemsPortfolio'); - $TestModel = new Content(); - $this->assertEquals('iContentAccountsId', $TestModel->ContentAccount->primaryKey); - - //test conformant models with no PK in the join table - $this->loadFixtures('Article', 'Tag'); - $TestModel = new Article(); - $this->assertEquals('article_id', $TestModel->ArticlesTag->primaryKey); - - //test conformant models with PK in join table - $TestModel = new Portfolio(); - $this->assertEquals('id', $TestModel->ItemsPortfolio->primaryKey); - - //test conformant models with PK in join table - join table contains extra field - $this->loadFixtures('JoinA', 'JoinB', 'JoinAB'); - $TestModel = new JoinA(); - $this->assertEquals('id', $TestModel->JoinAsJoinB->primaryKey); - } - -/** - * testDynamicBehaviorAttachment method - * - * @return void - */ - public function testDynamicBehaviorAttachment() { - $this->loadFixtures('Apple', 'Sample', 'Author'); - $TestModel = new Apple(); - $this->assertEquals(array(), $TestModel->Behaviors->loaded()); - - $TestModel->Behaviors->load('Tree', array('left' => 'left_field', 'right' => 'right_field')); - $this->assertTrue(is_object($TestModel->Behaviors->Tree)); - $this->assertEquals(array('Tree'), $TestModel->Behaviors->loaded()); - - $expected = array( - 'parent' => 'parent_id', - 'left' => 'left_field', - 'right' => 'right_field', - 'scope' => '1 = 1', - 'type' => 'nested', - '__parentChange' => false, - 'recursive' => -1 - ); - $this->assertEquals($expected, $TestModel->Behaviors->Tree->settings['Apple']); - - $TestModel->Behaviors->load('Tree', array('enabled' => false)); - $this->assertEquals($expected, $TestModel->Behaviors->Tree->settings['Apple']); - $this->assertEquals(array('Tree'), $TestModel->Behaviors->loaded()); - - $TestModel->Behaviors->unload('Tree'); - $this->assertEquals(array(), $TestModel->Behaviors->loaded()); - $this->assertFalse(isset($TestModel->Behaviors->Tree)); - } - -/** - * testFindWithJoinsOption method - * - * @return void - */ - public function testFindWithJoinsOption() { - $this->loadFixtures('Article', 'User'); - $TestUser = new User(); - - $options = array( - 'fields' => array( - 'user', - 'Article.published', - ), - 'joins' => array( - array( - 'table' => 'articles', - 'alias' => 'Article', - 'type' => 'LEFT', - 'conditions' => array( - 'User.id = Article.user_id', - ), - ), - ), - 'group' => array('User.user', 'Article.published'), - 'recursive' => -1, - 'order' => array('User.user') - ); - $result = $TestUser->find('all', $options); - $expected = array( - array('User' => array('user' => 'garrett'), 'Article' => array('published' => '')), - array('User' => array('user' => 'larry'), 'Article' => array('published' => 'Y')), - array('User' => array('user' => 'mariano'), 'Article' => array('published' => 'Y')), - array('User' => array('user' => 'nate'), 'Article' => array('published' => '')) - ); - $this->assertEquals($expected, $result); - } - -/** - * Tests cross database joins. Requires $test and $test2 to both be set in datasources.php - * NOTE: When testing on MySQL, you must set 'persistent' => false on *both* database connections, - * or one connection will step on the other. - */ - public function testCrossDatabaseJoins() { - $config = ConnectionManager::enumConnectionObjects(); - - $skip = (!isset($config['test']) || !isset($config['test2'])); - if ($skip) { - $this->markTestSkipped('Primary and secondary test databases not configured, skipping cross-database - join tests. To run theses tests defined $test and $test2 in your database configuration.' - ); - } - - $this->loadFixtures('Article', 'Tag', 'ArticlesTag', 'User', 'Comment'); - $TestModel = new Article(); - - $expected = array( - array( - 'Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - ), - array( - 'id' => '3', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Third Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:49:23', - 'updated' => '2007-03-18 10:51:31' - ), - array( - 'id' => '4', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - )), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ))), - array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ), - 'Comment' => array( - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - )), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))), - array( - 'Article' => array( - 'id' => '3', - 'user_id' => '1', - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Comment' => array(), - 'Tag' => array() - )); - $this->assertEquals($expected, $TestModel->find('all')); - - $db2 = ConnectionManager::getDataSource('test2'); - $this->fixtureManager->loadSingle('User', $db2); - $this->fixtureManager->loadSingle('Comment', $db2); - $this->assertEquals(3, $TestModel->find('count')); - - $TestModel->User->setDataSource('test2'); - $TestModel->Comment->setDataSource('test2'); - - foreach ($expected as $key => $value) { - unset($value['Comment'], $value['Tag']); - $expected[$key] = $value; - } - - $TestModel->recursive = 0; - $result = $TestModel->find('all'); - $this->assertEquals($expected, $result); - - foreach ($expected as $key => $value) { - unset($value['Comment'], $value['Tag']); - $expected[$key] = $value; - } - - $TestModel->recursive = 0; - $result = $TestModel->find('all'); - $this->assertEquals($expected, $result); - - $result = Hash::extract($TestModel->User->find('all'), '{n}.User.id'); - $this->assertEquals(array('1', '2', '3', '4'), $result); - $this->assertEquals($expected, $TestModel->find('all')); - - $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment'))); - $expected = array( - array( - 'Comment' => array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - ), - 'Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - array( - 'Comment' => array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - ), - 'User' => array( - 'id' => '4', - 'user' => 'garrett', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:22:23', - 'updated' => '2007-03-17 01:24:31' - ), - 'Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - array( - 'Comment' => array( - 'id' => '3', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Third Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:49:23', - 'updated' => '2007-03-18 10:51:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - array( - 'Comment' => array( - 'id' => '4', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - array( - 'Comment' => array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - )), - array( - 'Comment' => array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - ), - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - ), - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ))); - $this->assertEquals($expected, $TestModel->Comment->find('all')); - } - -/** - * test HABM operations without clobbering existing records #275 - * - * @return void - */ - public function testHABTMKeepExisting() { - $this->loadFixtures('Site', 'Domain', 'DomainsSite'); - - $Site = new Site(); - $results = $Site->find('count'); - $expected = 3; - $this->assertEquals($expected, $results); - - $data = $Site->findById(1); - - // include api.cakephp.org - $data['Domain'] = array('Domain' => array(1, 2, 3)); - $Site->save($data); - - $Site->id = 1; - $results = $Site->read(); - $expected = 3; // 3 domains belonging to cakephp - $this->assertEquals($expected, count($results['Domain'])); - - $Site->id = 2; - $results = $Site->read(); - $expected = 2; // 2 domains belonging to markstory - $this->assertEquals($expected, count($results['Domain'])); - - $Site->id = 3; - $results = $Site->read(); - $expected = 2; - $this->assertEquals($expected, count($results['Domain'])); - $results['Domain'] = array('Domain' => array(7)); - $Site->save($results); // remove association from domain 6 - $results = $Site->read(); - $expected = 1; // only 1 domain left belonging to rchavik - $this->assertEquals($expected, count($results['Domain'])); - - // add deleted domain back - $results['Domain'] = array('Domain' => array(6, 7)); - $Site->save($results); - $results = $Site->read(); - $expected = 2; // 2 domains belonging to rchavik - $this->assertEquals($expected, count($results['Domain'])); - - $Site->DomainsSite->id = $results['Domain'][0]['DomainsSite']['id']; - $Site->DomainsSite->saveField('active', true); - - $results = $Site->Domain->DomainsSite->find('count', array( - 'conditions' => array( - 'DomainsSite.active' => true, - ), - )); - $expected = 5; - $this->assertEquals($expected, $results); - - // activate api.cakephp.org - $activated = $Site->DomainsSite->findByDomainId(3); - $activated['DomainsSite']['active'] = true; - $Site->DomainsSite->save($activated); - - $results = $Site->DomainsSite->find('count', array( - 'conditions' => array( - 'DomainsSite.active' => true, - ), - )); - $expected = 6; - $this->assertEquals($expected, $results); - - // remove 2 previously active domains, and leave $activated alone - $data = array( - 'Site' => array('id' => 1, 'name' => 'cakephp (modified)'), - 'Domain' => array( - 'Domain' => array(3), - ) - ); - $Site->create($data); - $Site->save($data); - - // tests that record is still identical prior to removal - $Site->id = 1; - $results = $Site->read(); - unset($results['Domain'][0]['DomainsSite']['updated']); - unset($activated['DomainsSite']['updated']); - $this->assertEquals($activated['DomainsSite'], $results['Domain'][0]['DomainsSite']); - } - -/** - * testHABTMKeepExistingAlternateDataFormat - * - * @return void - */ - public function testHABTMKeepExistingAlternateDataFormat() { - $this->loadFixtures('Site', 'Domain', 'DomainsSite'); - - $Site = new Site(); - - $expected = array( - array( - 'DomainsSite' => array( - 'id' => 1, - 'site_id' => 1, - 'domain_id' => 1, - 'active' => true, - 'created' => '2007-03-17 01:16:23' - ) - ), - array( - 'DomainsSite' => array( - 'id' => 2, - 'site_id' => 1, - 'domain_id' => 2, - 'active' => true, - 'created' => '2007-03-17 01:16:23' - ) - ) - ); - $result = $Site->DomainsSite->find('all', array( - 'conditions' => array('DomainsSite.site_id' => 1), - 'fields' => array( - 'DomainsSite.id', - 'DomainsSite.site_id', - 'DomainsSite.domain_id', - 'DomainsSite.active', - 'DomainsSite.created' - ), - 'order' => 'DomainsSite.id' - )); - $this->assertEquals($expected, $result); - - $time = date('Y-m-d H:i:s'); - $data = array( - 'Site' => array( - 'id' => 1 - ), - 'Domain' => array( - array( - 'site_id' => 1, - 'domain_id' => 3, - 'created' => $time, - ), - array( - 'id' => 2, - 'site_id' => 1, - 'domain_id' => 2 - ), - ) - ); - $Site->save($data); - $expected = array( - array( - 'DomainsSite' => array( - 'id' => 2, - 'site_id' => 1, - 'domain_id' => 2, - 'active' => true, - 'created' => '2007-03-17 01:16:23' - ) - ), - array( - 'DomainsSite' => array( - 'id' => 7, - 'site_id' => 1, - 'domain_id' => 3, - 'active' => false, - 'created' => $time - ) - ) - ); - $result = $Site->DomainsSite->find('all', array( - 'conditions' => array('DomainsSite.site_id' => 1), - 'fields' => array( - 'DomainsSite.id', - 'DomainsSite.site_id', - 'DomainsSite.domain_id', - 'DomainsSite.active', - 'DomainsSite.created' - ), - 'order' => 'DomainsSite.id' - )); - $this->assertEquals($expected, $result); - } - -/** - * test HABM operations without clobbering existing records #275 - * - * @return void - */ - public function testHABTMKeepExistingWithThreeDbs() { - $config = ConnectionManager::enumConnectionObjects(); - $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.'); - $this->skipIf( - !isset($config['test']) || !isset($config['test2']) || !isset($config['test_database_three']), - 'Primary, secondary, and tertiary test databases not configured, skipping test. To run this test define $test, $test2, and $test_database_three in your database configuration.' - ); - - $this->loadFixtures('Player', 'Guild', 'GuildsPlayer', 'Armor', 'ArmorsPlayer'); - $Player = ClassRegistry::init('Player'); - $Player->bindModel(array( - 'hasAndBelongsToMany' => array( - 'Armor' => array( - 'with' => 'ArmorsPlayer', - 'unique' => 'keepExisting', - ), - ), - ), false); - $this->assertEquals('test', $Player->useDbConfig); - $this->assertEquals('test', $Player->Guild->useDbConfig); - $this->assertEquals('test2', $Player->Guild->GuildsPlayer->useDbConfig); - $this->assertEquals('test2', $Player->Armor->useDbConfig); - $this->assertEquals('test_database_three', $Player->ArmorsPlayer->useDbConfig); - - $players = $Player->find('all'); - $this->assertEquals(4, count($players)); - $playersGuilds = Hash::extract($players, '{n}.Guild.{n}.GuildsPlayer'); - $this->assertEquals(3, count($playersGuilds)); - $playersArmors = Hash::extract($players, '{n}.Armor.{n}.ArmorsPlayer'); - $this->assertEquals(3, count($playersArmors)); - unset($players); - - $larry = $Player->findByName('larry'); - $larrysArmor = Hash::extract($larry, 'Armor.{n}.ArmorsPlayer'); - $this->assertEquals(1, count($larrysArmor)); - - $larry['Guild']['Guild'] = array(1, 3); // larry joins another guild - $larry['Armor']['Armor'] = array(2, 3); // purchases chainmail - $Player->save($larry); - unset($larry); - - $larry = $Player->findByName('larry'); - $larrysGuild = Hash::extract($larry, 'Guild.{n}.GuildsPlayer'); - $this->assertEquals(2, count($larrysGuild)); - $larrysArmor = Hash::extract($larry, 'Armor.{n}.ArmorsPlayer'); - $this->assertEquals(2, count($larrysArmor)); - - $Player->ArmorsPlayer->id = 3; - $Player->ArmorsPlayer->saveField('broken', true); // larry's cloak broke - - $larry = $Player->findByName('larry'); - $larrysCloak = Hash::extract($larry, 'Armor.{n}.ArmorsPlayer[armor_id=3]', $larry); - $this->assertNotEmpty($larrysCloak); - $this->assertTrue($larrysCloak[0]['broken']); // still broken - } - -/** - * testDisplayField method - * - * @return void - */ - public function testDisplayField() { - $this->loadFixtures('Post', 'Comment', 'Person', 'User'); - $Post = new Post(); - $Comment = new Comment(); - $Person = new Person(); - - $this->assertEquals('title', $Post->displayField); - $this->assertEquals('name', $Person->displayField); - $this->assertEquals('id', $Comment->displayField); - } - -/** - * testSchema method - * - * @return void - */ - public function testSchema() { - $Post = new Post(); - - $result = $Post->schema(); - $columns = array('id', 'author_id', 'title', 'body', 'published', 'created', 'updated'); - $this->assertEquals($columns, array_keys($result)); - - $types = array('integer', 'integer', 'string', 'text', 'string', 'datetime', 'datetime'); - $this->assertEquals(Hash::extract(array_values($result), '{n}.type'), $types); - - $result = $Post->schema('body'); - $this->assertEquals('text', $result['type']); - $this->assertNull($Post->schema('foo')); - - $this->assertEquals($Post->getColumnTypes(), array_combine($columns, $types)); - } - -/** - * Check schema() on a model with useTable = false; - * - * @return void - */ - public function testSchemaUseTableFalse() { - $model = new TheVoid(); - $result = $model->schema(); - $this->assertNull($result); - - $result = $model->create(); - $this->assertEmpty($result); - } - -/** - * data provider for time tests. - * - * @return array - */ - public static function timeProvider() { - $db = ConnectionManager::getDataSource('test'); - $now = 'NOW()'; - return array( - // blank - array( - array('hour' => '', 'min' => '', 'meridian' => ''), - '' - ), - // missing hour - array( - array('hour' => '', 'min' => '00', 'meridian' => 'pm'), - '' - ), - // all blank - array( - array('hour' => '', 'min' => '', 'sec' => ''), - '' - ), - // set and empty merdian - array( - array('hour' => '1', 'min' => '00', 'meridian' => ''), - '' - ), - // midnight - array( - array('hour' => '12', 'min' => '0', 'meridian' => 'am'), - '00:00:00' - ), - array( - array('hour' => '00', 'min' => '00'), - '00:00:00' - ), - // 3am - array( - array('hour' => '03', 'min' => '04', 'sec' => '04'), - '03:04:04' - ), - array( - array('hour' => '3', 'min' => '4', 'sec' => '4'), - '03:04:04' - ), - array( - array('hour' => '03', 'min' => '4', 'sec' => '4'), - '03:04:04' - ), - array( - $now, - $now - ) - ); - } - -/** - * test deconstruct with time fields. - * - * @dataProvider timeProvider - * @return void - */ - public function testDeconstructFieldsTime($input, $result) { - $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); - - $this->loadFixtures('Apple'); - $TestModel = new Apple(); - - $data = array( - 'Apple' => array( - 'mytime' => $input - ) - ); - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('mytime' => $result)); - $this->assertEquals($expected, $TestModel->data); - } - -/** - * testDeconstructFields with datetime, timestamp, and date fields - * - * @return void - */ - public function testDeconstructFieldsDateTime() { - $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); - - $this->loadFixtures('Apple'); - $TestModel = new Apple(); - - //test null/empty values first - $data['Apple']['created']['year'] = ''; - $data['Apple']['created']['month'] = ''; - $data['Apple']['created']['day'] = ''; - $data['Apple']['created']['hour'] = ''; - $data['Apple']['created']['min'] = ''; - $data['Apple']['created']['sec'] = ''; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('created' => '')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['date']['year'] = ''; - $data['Apple']['date']['month'] = ''; - $data['Apple']['date']['day'] = ''; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('date' => '')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['year'] = '2007'; - $data['Apple']['created']['month'] = '08'; - $data['Apple']['created']['day'] = '20'; - $data['Apple']['created']['hour'] = ''; - $data['Apple']['created']['min'] = ''; - $data['Apple']['created']['sec'] = ''; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('created' => '2007-08-20 00:00:00')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['year'] = '2007'; - $data['Apple']['created']['month'] = '08'; - $data['Apple']['created']['day'] = '20'; - $data['Apple']['created']['hour'] = '10'; - $data['Apple']['created']['min'] = '12'; - $data['Apple']['created']['sec'] = ''; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('created' => '2007-08-20 10:12:00')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['year'] = '2007'; - $data['Apple']['created']['month'] = ''; - $data['Apple']['created']['day'] = '12'; - $data['Apple']['created']['hour'] = '20'; - $data['Apple']['created']['min'] = ''; - $data['Apple']['created']['sec'] = ''; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('created' => '')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['hour'] = '20'; - $data['Apple']['created']['min'] = '33'; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('created' => '')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['hour'] = '20'; - $data['Apple']['created']['min'] = '33'; - $data['Apple']['created']['sec'] = '33'; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('created' => '')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['hour'] = '13'; - $data['Apple']['created']['min'] = '00'; - $data['Apple']['date']['year'] = '2006'; - $data['Apple']['date']['month'] = '12'; - $data['Apple']['date']['day'] = '25'; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array( - 'Apple' => array( - 'created' => '', - 'date' => '2006-12-25' - )); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['year'] = '2007'; - $data['Apple']['created']['month'] = '08'; - $data['Apple']['created']['day'] = '20'; - $data['Apple']['created']['hour'] = '10'; - $data['Apple']['created']['min'] = '12'; - $data['Apple']['created']['sec'] = '09'; - $data['Apple']['date']['year'] = '2006'; - $data['Apple']['date']['month'] = '12'; - $data['Apple']['date']['day'] = '25'; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array( - 'Apple' => array( - 'created' => '2007-08-20 10:12:09', - 'date' => '2006-12-25' - )); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['year'] = '--'; - $data['Apple']['created']['month'] = '--'; - $data['Apple']['created']['day'] = '--'; - $data['Apple']['created']['hour'] = '--'; - $data['Apple']['created']['min'] = '--'; - $data['Apple']['created']['sec'] = '--'; - $data['Apple']['date']['year'] = '--'; - $data['Apple']['date']['month'] = '--'; - $data['Apple']['date']['day'] = '--'; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('created' => '', 'date' => '')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['created']['year'] = '2007'; - $data['Apple']['created']['month'] = '--'; - $data['Apple']['created']['day'] = '20'; - $data['Apple']['created']['hour'] = '10'; - $data['Apple']['created']['min'] = '12'; - $data['Apple']['created']['sec'] = '09'; - $data['Apple']['date']['year'] = '2006'; - $data['Apple']['date']['month'] = '12'; - $data['Apple']['date']['day'] = '25'; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('created' => '', 'date' => '2006-12-25')); - $this->assertEquals($expected, $TestModel->data); - - $data = array(); - $data['Apple']['date']['year'] = '2006'; - $data['Apple']['date']['month'] = '12'; - $data['Apple']['date']['day'] = '25'; - - $TestModel->data = null; - $TestModel->set($data); - $expected = array('Apple' => array('date' => '2006-12-25')); - $this->assertEquals($expected, $TestModel->data); - - $db = ConnectionManager::getDataSource('test'); - $data = array(); - $data['Apple']['modified'] = $db->expression('NOW()'); - $TestModel->data = null; - $TestModel->set($data); - $this->assertEquals($TestModel->data, $data); - } - -/** - * testTablePrefixSwitching method - * - * @return void - */ - public function testTablePrefixSwitching() { - ConnectionManager::create('database1', - array_merge($this->db->config, array('prefix' => 'aaa_') - )); - ConnectionManager::create('database2', - array_merge($this->db->config, array('prefix' => 'bbb_') - )); - - $db1 = ConnectionManager::getDataSource('database1'); - $db2 = ConnectionManager::getDataSource('database2'); - - $TestModel = new Apple(); - $TestModel->setDataSource('database1'); - $this->assertContains('aaa_apples', $this->db->fullTableName($TestModel)); - $this->assertContains('aaa_apples', $db1->fullTableName($TestModel)); - $this->assertContains('aaa_apples', $db2->fullTableName($TestModel)); - - $TestModel->setDataSource('database2'); - $this->assertContains('bbb_apples', $this->db->fullTableName($TestModel)); - $this->assertContains('bbb_apples', $db1->fullTableName($TestModel)); - $this->assertContains('bbb_apples', $db2->fullTableName($TestModel)); - - $TestModel = new Apple(); - $TestModel->tablePrefix = 'custom_'; - $this->assertContains('custom_apples', $this->db->fullTableName($TestModel)); - $TestModel->setDataSource('database1'); - $this->assertContains('custom_apples', $this->db->fullTableName($TestModel)); - $this->assertContains('custom_apples', $db1->fullTableName($TestModel)); - - $TestModel = new Apple(); - $TestModel->setDataSource('database1'); - $this->assertContains('aaa_apples', $this->db->fullTableName($TestModel)); - $TestModel->tablePrefix = ''; - $TestModel->setDataSource('database2'); - $this->assertContains('apples', $db2->fullTableName($TestModel)); - $this->assertContains('apples', $db1->fullTableName($TestModel)); - - $TestModel->tablePrefix = null; - $TestModel->setDataSource('database1'); - $this->assertContains('aaa_apples', $db2->fullTableName($TestModel)); - $this->assertContains('aaa_apples', $db1->fullTableName($TestModel)); - - $TestModel->tablePrefix = false; - $TestModel->setDataSource('database2'); - $this->assertContains('apples', $db2->fullTableName($TestModel)); - $this->assertContains('apples', $db1->fullTableName($TestModel)); - } - -/** - * Tests validation parameter order in custom validation methods - * - * @return void - */ - public function testInvalidAssociation() { - $TestModel = new ValidationTest1(); - $this->assertNull($TestModel->getAssociated('Foo')); - } - -/** - * testLoadModelSecondIteration method - * - * @return void - */ - public function testLoadModelSecondIteration() { - $this->loadFixtures('Apple', 'Message', 'Thread', 'Bid'); - $model = new ModelA(); - $this->assertInstanceOf('ModelA', $model); - - $this->assertInstanceOf('ModelB', $model->ModelB); - $this->assertInstanceOf('ModelD', $model->ModelB->ModelD); - - $this->assertInstanceOf('ModelC', $model->ModelC); - $this->assertInstanceOf('ModelD', $model->ModelC->ModelD); - } - -/** - * ensure that exists() does not persist between method calls reset on create - * - * @return void - */ - public function testResetOfExistsOnCreate() { - $this->loadFixtures('Article'); - $Article = new Article(); - $Article->id = 1; - $Article->saveField('title', 'Reset me'); - $Article->delete(); - $Article->id = 1; - $this->assertFalse($Article->exists()); - - $Article->create(); - $this->assertFalse($Article->exists()); - $Article->id = 2; - $Article->saveField('title', 'Staying alive'); - $result = $Article->read(null, 2); - $this->assertEquals('Staying alive', $result['Article']['title']); - } - -/** - * testUseTableFalseExistsCheck method - * - * @return void - */ - public function testUseTableFalseExistsCheck() { - $this->loadFixtures('Article'); - $Article = new Article(); - $Article->id = 1337; - $result = $Article->exists(); - $this->assertFalse($result); - - $Article->useTable = false; - $Article->id = null; - $result = $Article->exists(); - $this->assertFalse($result); - - // An article with primary key of '1' has been loaded by the fixtures. - $Article->useTable = false; - $Article->id = 1; - $result = $Article->exists(); - $this->assertTrue($result); - } - -/** - * testPluginAssociations method - * - * @return void - */ - public function testPluginAssociations() { - $this->loadFixtures('TestPluginArticle', 'User', 'TestPluginComment'); - $TestModel = new TestPluginArticle(); - - $result = $TestModel->find('all'); - $expected = array( - array( - 'TestPluginArticle' => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Plugin Article', - 'body' => 'First Plugin Article Body', - 'published' => 'Y', - 'created' => '2008-09-24 10:39:23', - 'updated' => '2008-09-24 10:41:31' - ), - 'User' => array( - 'id' => 1, - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'TestPluginComment' => array( - array( - 'id' => 1, - 'article_id' => 1, - 'user_id' => 2, - 'comment' => 'First Comment for First Plugin Article', - 'published' => 'Y', - 'created' => '2008-09-24 10:45:23', - 'updated' => '2008-09-24 10:47:31' - ), - array( - 'id' => 2, - 'article_id' => 1, - 'user_id' => 4, - 'comment' => 'Second Comment for First Plugin Article', - 'published' => 'Y', - 'created' => '2008-09-24 10:47:23', - 'updated' => '2008-09-24 10:49:31' - ), - array( - 'id' => 3, - 'article_id' => 1, - 'user_id' => 1, - 'comment' => 'Third Comment for First Plugin Article', - 'published' => 'Y', - 'created' => '2008-09-24 10:49:23', - 'updated' => '2008-09-24 10:51:31' - ), - array( - 'id' => 4, - 'article_id' => 1, - 'user_id' => 1, - 'comment' => 'Fourth Comment for First Plugin Article', - 'published' => 'N', - 'created' => '2008-09-24 10:51:23', - 'updated' => '2008-09-24 10:53:31' - ))), - array( - 'TestPluginArticle' => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Plugin Article', - 'body' => 'Second Plugin Article Body', - 'published' => 'Y', - 'created' => '2008-09-24 10:41:23', - 'updated' => '2008-09-24 10:43:31' - ), - 'User' => array( - 'id' => 3, - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ), - 'TestPluginComment' => array( - array( - 'id' => 5, - 'article_id' => 2, - 'user_id' => 1, - 'comment' => 'First Comment for Second Plugin Article', - 'published' => 'Y', - 'created' => '2008-09-24 10:53:23', - 'updated' => '2008-09-24 10:55:31' - ), - array( - 'id' => 6, - 'article_id' => 2, - 'user_id' => 2, - 'comment' => 'Second Comment for Second Plugin Article', - 'published' => 'Y', - 'created' => '2008-09-24 10:55:23', - 'updated' => '2008-09-24 10:57:31' - ))), - array( - 'TestPluginArticle' => array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Plugin Article', - 'body' => 'Third Plugin Article Body', - 'published' => 'Y', - 'created' => '2008-09-24 10:43:23', - 'updated' => '2008-09-24 10:45:31' - ), - 'User' => array( - 'id' => 1, - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'TestPluginComment' => array() - )); - - $this->assertEquals($expected, $result); - } - -/** - * Tests getAssociated method - * - * @return void - */ - public function testGetAssociated() { - $this->loadFixtures('Article', 'Tag'); - $Article = ClassRegistry::init('Article'); - - $assocTypes = array('hasMany', 'hasOne', 'belongsTo', 'hasAndBelongsToMany'); - foreach ($assocTypes as $type) { - $this->assertEquals($Article->getAssociated($type), array_keys($Article->{$type})); - } - - $Article->bindModel(array('hasMany' => array('Category'))); - $this->assertEquals(array('Comment', 'Category'), $Article->getAssociated('hasMany')); - - $results = $Article->getAssociated(); - $results = array_keys($results); - sort($results); - $this->assertEquals(array('Category', 'Comment', 'Tag', 'User'), $results); - - $Article->unbindModel(array('hasAndBelongsToMany' => array('Tag'))); - $this->assertEquals(array(), $Article->getAssociated('hasAndBelongsToMany')); - - $result = $Article->getAssociated('Category'); - $expected = array( - 'className' => 'Category', - 'foreignKey' => 'article_id', - 'conditions' => '', - 'fields' => '', - 'order' => '', - 'limit' => '', - 'offset' => '', - 'dependent' => '', - 'exclusive' => '', - 'finderQuery' => '', - 'counterQuery' => '', - 'association' => 'hasMany', - ); - $this->assertEquals($expected, $result); - } - -/** - * testAutoConstructAssociations method - * - * @return void - */ - public function testAutoConstructAssociations() { - $this->loadFixtures('User', 'ArticleFeatured', 'Featured', 'ArticleFeaturedsTags'); - $TestModel = new AssociationTest1(); - - $result = $TestModel->hasAndBelongsToMany; - $expected = array('AssociationTest2' => array( - 'unique' => false, - 'joinTable' => 'join_as_join_bs', - 'foreignKey' => false, - 'className' => 'AssociationTest2', - 'with' => 'JoinAsJoinB', - 'dynamicWith' => true, - 'associationForeignKey' => 'join_b_id', - 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', - 'finderQuery' => '' - )); - $this->assertEquals($expected, $result); - - $TestModel = new ArticleFeatured(); - $TestFakeModel = new ArticleFeatured(array('table' => false)); - - $expected = array( - 'User' => array( - 'className' => 'User', 'foreignKey' => 'user_id', - 'conditions' => '', 'fields' => '', 'order' => '', 'counterCache' => '' - ), - 'Category' => array( - 'className' => 'Category', 'foreignKey' => 'category_id', - 'conditions' => '', 'fields' => '', 'order' => '', 'counterCache' => '' - ) - ); - $this->assertSame($TestModel->belongsTo, $expected); - $this->assertSame($TestFakeModel->belongsTo, $expected); - - $this->assertEquals('User', $TestModel->User->name); - $this->assertEquals('User', $TestFakeModel->User->name); - $this->assertEquals('Category', $TestModel->Category->name); - $this->assertEquals('Category', $TestFakeModel->Category->name); - - $expected = array( - 'Featured' => array( - 'className' => 'Featured', - 'foreignKey' => 'article_featured_id', - 'conditions' => '', - 'fields' => '', - 'order' => '', - 'dependent' => '' - )); - - $this->assertSame($TestModel->hasOne, $expected); - $this->assertSame($TestFakeModel->hasOne, $expected); - - $this->assertEquals('Featured', $TestModel->Featured->name); - $this->assertEquals('Featured', $TestFakeModel->Featured->name); - - $expected = array( - 'Comment' => array( - 'className' => 'Comment', - 'dependent' => true, - 'foreignKey' => 'article_featured_id', - 'conditions' => '', - 'fields' => '', - 'order' => '', - 'limit' => '', - 'offset' => '', - 'exclusive' => '', - 'finderQuery' => '', - 'counterQuery' => '' - )); - - $this->assertSame($TestModel->hasMany, $expected); - $this->assertSame($TestFakeModel->hasMany, $expected); - - $this->assertEquals('Comment', $TestModel->Comment->name); - $this->assertEquals('Comment', $TestFakeModel->Comment->name); - - $expected = array( - 'Tag' => array( - 'className' => 'Tag', - 'joinTable' => 'article_featureds_tags', - 'with' => 'ArticleFeaturedsTag', - 'dynamicWith' => true, - 'foreignKey' => 'article_featured_id', - 'associationForeignKey' => 'tag_id', - 'conditions' => '', - 'fields' => '', - 'order' => '', - 'limit' => '', - 'offset' => '', - 'unique' => true, - 'finderQuery' => '', - )); - - $this->assertSame($TestModel->hasAndBelongsToMany, $expected); - $this->assertSame($TestFakeModel->hasAndBelongsToMany, $expected); - - $this->assertEquals('Tag', $TestModel->Tag->name); - $this->assertEquals('Tag', $TestFakeModel->Tag->name); - } - -/** - * test creating associations with plugins. Ensure a double alias isn't created - * - * @return void - */ - public function testAutoConstructPluginAssociations() { - $Comment = ClassRegistry::init('TestPluginComment'); - - $this->assertEquals(2, count($Comment->belongsTo), 'Too many associations'); - $this->assertFalse(isset($Comment->belongsTo['TestPlugin.User'])); - $this->assertTrue(isset($Comment->belongsTo['User']), 'Missing association'); - $this->assertTrue(isset($Comment->belongsTo['TestPluginArticle']), 'Missing association'); - } - -/** - * test Model::__construct - * - * ensure that $actsAS and $findMethods are merged. - * - * @return void - */ - public function testConstruct() { - $this->loadFixtures('Post'); - - $TestModel = ClassRegistry::init('MergeVarPluginPost'); - $this->assertEquals(array('Tree' => null), $TestModel->actsAs); - $this->assertTrue(isset($TestModel->Behaviors->Tree)); - } - -/** - * test Model::__construct - * - * ensure that $actsAS and $findMethods are merged. - * - * @return void - */ - public function testConstructWithAlternateDataSource() { - $TestModel = ClassRegistry::init(array( - 'class' => 'DoesntMatter', 'ds' => 'test', 'table' => false - )); - $this->assertEquals('test', $TestModel->useDbConfig); - - //deprecated but test it anyway - $NewVoid = new TheVoid(null, false, 'other'); - $this->assertEquals('other', $NewVoid->useDbConfig); - } - -/** - * testColumnTypeFetching method - * - * @return void - */ - public function testColumnTypeFetching() { - $model = new Test(); - $this->assertEquals('integer', $model->getColumnType('id')); - $this->assertEquals('text', $model->getColumnType('notes')); - $this->assertEquals('datetime', $model->getColumnType('updated')); - $this->assertEquals(null, $model->getColumnType('unknown')); - - $model = new Article(); - $this->assertEquals('datetime', $model->getColumnType('User.created')); - $this->assertEquals('integer', $model->getColumnType('Tag.id')); - $this->assertEquals('integer', $model->getColumnType('Article.id')); - } - -/** - * testHabtmUniqueKey method - * - * @return void - */ - public function testHabtmUniqueKey() { - $model = new Item(); - $this->assertFalse($model->hasAndBelongsToMany['Portfolio']['unique']); - } - -/** - * testIdentity method - * - * @return void - */ - public function testIdentity() { - $TestModel = new Test(); - $result = $TestModel->alias; - $expected = 'Test'; - $this->assertEquals($expected, $result); - - $TestModel = new TestAlias(); - $result = $TestModel->alias; - $expected = 'TestAlias'; - $this->assertEquals($expected, $result); - - $TestModel = new Test(array('alias' => 'AnotherTest')); - $result = $TestModel->alias; - $expected = 'AnotherTest'; - $this->assertEquals($expected, $result); - - $TestModel = ClassRegistry::init('Test'); - $expected = null; - $this->assertEquals($expected, $TestModel->plugin); - - $TestModel = ClassRegistry::init('TestPlugin.TestPluginComment'); - $expected = 'TestPlugin'; - $this->assertEquals($expected, $TestModel->plugin); - } - -/** - * testWithAssociation method - * - * @return void - */ - public function testWithAssociation() { - $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - $TestModel = new Something(); - $result = $TestModel->SomethingElse->find('all'); - - $expected = array( - array( - 'SomethingElse' => array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'Something' => array( - array( - 'id' => '3', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'JoinThing' => array( - 'id' => '3', - 'something_id' => '3', - 'something_else_id' => '1', - 'doomed' => true, - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'afterFind' => 'Successfully added by AfterFind' - )))), - array( - 'SomethingElse' => array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'Something' => array( - array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'JoinThing' => array( - 'id' => '1', - 'something_id' => '1', - 'something_else_id' => '2', - 'doomed' => true, - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'afterFind' => 'Successfully added by AfterFind' - )))), - array( - 'SomethingElse' => array( - 'id' => '3', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'Something' => array( - array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'JoinThing' => array( - 'id' => '2', - 'something_id' => '2', - 'something_else_id' => '3', - 'doomed' => false, - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'afterFind' => 'Successfully added by AfterFind' - ))))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all'); - $expected = array( - array( - 'Something' => array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'SomethingElse' => array( - array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'JoinThing' => array( - 'doomed' => true, - 'something_id' => '1', - 'something_else_id' => '2', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'afterFind' => 'Successfully added by AfterFind' - ))), - array( - 'Something' => array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'SomethingElse' => array( - array( - 'id' => '3', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'JoinThing' => array( - 'doomed' => false, - 'something_id' => '2', - 'something_else_id' => '3', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'afterFind' => 'Successfully added by AfterFind' - ))), - array( - 'Something' => array( - 'id' => '3', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'SomethingElse' => array( - array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'JoinThing' => array( - 'doomed' => true, - 'something_id' => '3', - 'something_else_id' => '1', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'afterFind' => 'Successfully added by AfterFind' - )))); - $this->assertEquals($expected, $result); - - $result = $TestModel->findById(1); - $expected = array( - 'Something' => array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'SomethingElse' => array( - array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'JoinThing' => array( - 'doomed' => true, - 'something_id' => '1', - 'something_else_id' => '2', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'afterFind' => 'Successfully added by AfterFind' - ))); - $this->assertEquals($expected, $result); - - $expected = $TestModel->findById(1); - $TestModel->set($expected); - $TestModel->save(); - $result = $TestModel->findById(1); - $this->assertEquals($expected, $result); - - $TestModel->hasAndBelongsToMany['SomethingElse']['unique'] = false; - $TestModel->create(array( - 'Something' => array('id' => 1), - 'SomethingElse' => array(3, array( - 'something_else_id' => 1, - 'doomed' => true - )))); - - $TestModel->save(); - - $TestModel->hasAndBelongsToMany['SomethingElse']['order'] = 'SomethingElse.id ASC'; - $result = $TestModel->findById(1); - $expected = array( - 'Something' => array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23' - ), - 'SomethingElse' => array( - array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'JoinThing' => array( - 'doomed' => true, - 'something_id' => '1', - 'something_else_id' => '1', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'afterFind' => 'Successfully added by AfterFind' - ), - array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'JoinThing' => array( - 'doomed' => true, - 'something_id' => '1', - 'something_else_id' => '2', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'afterFind' => 'Successfully added by AfterFind' - ), - array( - 'id' => '3', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'JoinThing' => array( - 'doomed' => false, - 'something_id' => '1', - 'something_else_id' => '3', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'afterFind' => 'Successfully added by AfterFind' - ) - ); - $this->assertEquals(static::date(), $result['Something']['updated']); - unset($result['Something']['updated']); - $this->assertEquals($expected, $result); - } - -/** - * testFindSelfAssociations method - * - * @return void - */ - public function testFindSelfAssociations() { - $this->loadFixtures('Person'); - - $TestModel = new Person(); - $TestModel->recursive = 2; - $result = $TestModel->read(null, 1); - $expected = array( - 'Person' => array( - 'id' => 1, - 'name' => 'person', - 'mother_id' => 2, - 'father_id' => 3 - ), - 'Mother' => array( - 'id' => 2, - 'name' => 'mother', - 'mother_id' => 4, - 'father_id' => 5, - 'Mother' => array( - 'id' => 4, - 'name' => 'mother - grand mother', - 'mother_id' => 0, - 'father_id' => 0 - ), - 'Father' => array( - 'id' => 5, - 'name' => 'mother - grand father', - 'mother_id' => 0, - 'father_id' => 0 - )), - 'Father' => array( - 'id' => 3, - 'name' => 'father', - 'mother_id' => 6, - 'father_id' => 7, - 'Father' => array( - 'id' => 7, - 'name' => 'father - grand father', - 'mother_id' => 0, - 'father_id' => 0 - ), - 'Mother' => array( - 'id' => 6, - 'name' => 'father - grand mother', - 'mother_id' => 0, - 'father_id' => 0 - ))); - - $this->assertEquals($expected, $result); - - $TestModel->recursive = 3; - $result = $TestModel->read(null, 1); - $expected = array( - 'Person' => array( - 'id' => 1, - 'name' => 'person', - 'mother_id' => 2, - 'father_id' => 3 - ), - 'Mother' => array( - 'id' => 2, - 'name' => 'mother', - 'mother_id' => 4, - 'father_id' => 5, - 'Mother' => array( - 'id' => 4, - 'name' => 'mother - grand mother', - 'mother_id' => 0, - 'father_id' => 0, - 'Mother' => array(), - 'Father' => array()), - 'Father' => array( - 'id' => 5, - 'name' => 'mother - grand father', - 'mother_id' => 0, - 'father_id' => 0, - 'Father' => array(), - 'Mother' => array() - )), - 'Father' => array( - 'id' => 3, - 'name' => 'father', - 'mother_id' => 6, - 'father_id' => 7, - 'Father' => array( - 'id' => 7, - 'name' => 'father - grand father', - 'mother_id' => 0, - 'father_id' => 0, - 'Father' => array(), - 'Mother' => array() - ), - 'Mother' => array( - 'id' => 6, - 'name' => 'father - grand mother', - 'mother_id' => 0, - 'father_id' => 0, - 'Mother' => array(), - 'Father' => array() - ))); - - $this->assertEquals($expected, $result); - } - -/** - * testDynamicAssociations method - * - * @return void - */ - public function testDynamicAssociations() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->hasOne = array(); - $TestModel->hasMany['Comment'] = array_merge($TestModel->hasMany['Comment'], array( - 'foreignKey' => false, - 'conditions' => array('Comment.user_id =' => '2') - )); - $result = $TestModel->find('all'); - $expected = array( - array( - 'Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - ))), - array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - ))), - array( - 'Article' => array( - 'id' => '3', - 'user_id' => '1', - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - )))); - - $this->assertEquals($expected, $result); - } - -/** - * testCreation method - * - * @return void - */ - public function testCreation() { - $this->loadFixtures('Article', 'ArticleFeaturedsTags', 'User', 'Featured'); - $TestModel = new Test(); - $result = $TestModel->create(); - $expected = array('Test' => array('notes' => 'write some notes here')); - $this->assertEquals($expected, $result); - $TestModel = new User(); - $result = $TestModel->schema(); - - if (isset($this->db->columns['primary_key']['length'])) { - $intLength = $this->db->columns['primary_key']['length']; - } elseif (isset($this->db->columns['integer']['length'])) { - $intLength = $this->db->columns['integer']['length']; - } else { - $intLength = 11; - } - foreach (array('collate', 'charset', 'comment', 'unsigned') as $type) { - foreach ($result as $i => $r) { - unset($result[$i][$type]); - } - } - - $expected = array( - 'id' => array( - 'type' => 'integer', - 'null' => false, - 'default' => null, - 'length' => $intLength, - 'key' => 'primary' - ), - 'user' => array( - 'type' => 'string', - 'null' => true, - 'default' => '', - 'length' => 255 - ), - 'password' => array( - 'type' => 'string', - 'null' => true, - 'default' => '', - 'length' => 255 - ), - 'created' => array( - 'type' => 'datetime', - 'null' => true, - 'default' => null, - 'length' => null - ), - 'updated' => array( - 'type' => 'datetime', - 'null' => true, - 'default' => null, - 'length' => null - )); - - $this->assertEquals($expected, $result); - - $TestModel = new Article(); - $result = $TestModel->create(); - $expected = array('Article' => array('published' => 'N')); - $this->assertEquals($expected, $result); - - $FeaturedModel = new Featured(); - $data = array( - 'article_featured_id' => 1, - 'category_id' => 1, - 'published_date' => array( - 'year' => 2008, - 'month' => 06, - 'day' => 11 - ), - 'end_date' => array( - 'year' => 2008, - 'month' => 06, - 'day' => 20 - )); - - $expected = array( - 'Featured' => array( - 'article_featured_id' => 1, - 'category_id' => 1, - 'published_date' => '2008-06-11 00:00:00', - 'end_date' => '2008-06-20 00:00:00' - )); - - $this->assertEquals($expected, $FeaturedModel->create($data)); - - $data = array( - 'published_date' => array( - 'year' => 2008, - 'month' => 06, - 'day' => 11 - ), - 'end_date' => array( - 'year' => 2008, - 'month' => 06, - 'day' => 20 - ), - 'article_featured_id' => 1, - 'category_id' => 1 - ); - - $expected = array( - 'Featured' => array( - 'published_date' => '2008-06-11 00:00:00', - 'end_date' => '2008-06-20 00:00:00', - 'article_featured_id' => 1, - 'category_id' => 1 - )); - - $this->assertEquals($expected, $FeaturedModel->create($data)); - } - -/** - * testEscapeField to prove it escapes the field well even when it has part of the alias on it - * - * @return void - */ - public function testEscapeField() { - $TestModel = new Test(); - $db = $TestModel->getDataSource(); - - $result = $TestModel->escapeField('test_field'); - $expected = $db->name('Test.test_field'); - $this->assertEquals($expected, $result); - - $result = $TestModel->escapeField('TestField'); - $expected = $db->name('Test.TestField'); - $this->assertEquals($expected, $result); - - $result = $TestModel->escapeField('DomainHandle', 'Domain'); - $expected = $db->name('Domain.DomainHandle'); - $this->assertEquals($expected, $result); - - ConnectionManager::create('mock', array('datasource' => 'DboMock')); - $TestModel->setDataSource('mock'); - $db = $TestModel->getDataSource(); - - $result = $TestModel->escapeField('DomainHandle', 'Domain'); - $expected = $db->name('Domain.DomainHandle'); - $this->assertEquals($expected, $result); - ConnectionManager::drop('mock'); - } - -/** - * testGetID - * - * @return void - */ - public function testGetID() { - $TestModel = new Test(); - - $result = $TestModel->getID(); - $this->assertFalse($result); - - $TestModel->id = 9; - $result = $TestModel->getID(); - $this->assertEquals(9, $result); - - $TestModel->id = array(10, 9, 8, 7); - $result = $TestModel->getID(2); - $this->assertEquals(8, $result); - - $TestModel->id = array(array(), 1, 2, 3); - $result = $TestModel->getID(); - $this->assertFalse($result); - } - -/** - * test that model->hasMethod checks self and behaviors. - * - * @return void - */ - public function testHasMethod() { - $Article = new Article(); - $Article->Behaviors = $this->getMock('BehaviorCollection'); - - $Article->Behaviors->expects($this->at(0)) - ->method('hasMethod') - ->will($this->returnValue(true)); - - $Article->Behaviors->expects($this->at(1)) - ->method('hasMethod') - ->will($this->returnValue(false)); - - $this->assertTrue($Article->hasMethod('find')); - - $this->assertTrue($Article->hasMethod('pass')); - $this->assertFalse($Article->hasMethod('fail')); - } - -/** - * testMultischemaFixture - * - * @return void - */ - public function testMultischemaFixture() { - $config = ConnectionManager::enumConnectionObjects(); - $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.'); - $this->skipIf(!isset($config['test']) || !isset($config['test2']), - 'Primary and secondary test databases not configured, skipping cross-database join tests. To run these tests define $test and $test2 in your database configuration.' - ); - - $this->loadFixtures('Player', 'Guild', 'GuildsPlayer'); - - $Player = ClassRegistry::init('Player'); - $this->assertEquals('test', $Player->useDbConfig); - $this->assertEquals('test', $Player->Guild->useDbConfig); - $this->assertEquals('test2', $Player->Guild->GuildsPlayer->useDbConfig); - $this->assertEquals('test2', $Player->GuildsPlayer->useDbConfig); - - $players = $Player->find('all', array('recursive' => -1)); - $guilds = $Player->Guild->find('all', array('recursive' => -1)); - $guildsPlayers = $Player->GuildsPlayer->find('all', array('recursive' => -1)); - - $this->assertEquals(true, count($players) > 1); - $this->assertEquals(true, count($guilds) > 1); - $this->assertEquals(true, count($guildsPlayers) > 1); - } - -/** - * testMultischemaFixtureWithThreeDatabases, three databases - * - * @return void - */ - public function testMultischemaFixtureWithThreeDatabases() { - $config = ConnectionManager::enumConnectionObjects(); - $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.'); - $this->skipIf( - !isset($config['test']) || !isset($config['test2']) || !isset($config['test_database_three']), - 'Primary, secondary, and tertiary test databases not configured, skipping test. To run this test define $test, $test2, and $test_database_three in your database configuration.' - ); - - $this->loadFixtures('Player', 'Guild', 'GuildsPlayer', 'Armor', 'ArmorsPlayer'); - - $Player = ClassRegistry::init('Player'); - $Player->bindModel(array( - 'hasAndBelongsToMany' => array( - 'Armor' => array( - 'with' => 'ArmorsPlayer', - ), - ), - ), false); - $this->assertEquals('test', $Player->useDbConfig); - $this->assertEquals('test', $Player->Guild->useDbConfig); - $this->assertEquals('test2', $Player->Guild->GuildsPlayer->useDbConfig); - $this->assertEquals('test2', $Player->GuildsPlayer->useDbConfig); - $this->assertEquals('test2', $Player->Armor->useDbConfig); - $this->assertEquals('test_database_three', $Player->Armor->ArmorsPlayer->useDbConfig); - $this->assertEquals('test', $Player->getDataSource()->configKeyName); - $this->assertEquals('test', $Player->Guild->getDataSource()->configKeyName); - $this->assertEquals('test2', $Player->GuildsPlayer->getDataSource()->configKeyName); - $this->assertEquals('test2', $Player->Armor->getDataSource()->configKeyName); - $this->assertEquals('test_database_three', $Player->Armor->ArmorsPlayer->getDataSource()->configKeyName); - - $players = $Player->find('all', array('recursive' => -1)); - $guilds = $Player->Guild->find('all', array('recursive' => -1)); - $guildsPlayers = $Player->GuildsPlayer->find('all', array('recursive' => -1)); - $armorsPlayers = $Player->ArmorsPlayer->find('all', array('recursive' => -1)); - - $this->assertEquals(true, count($players) > 1); - $this->assertEquals(true, count($guilds) > 1); - $this->assertEquals(true, count($guildsPlayers) > 1); - $this->assertEquals(true, count($armorsPlayers) > 1); - } - -/** - * Tests that calling schema() on a model that is not supposed to use a table - * does not trigger any calls on any datasource - * - * @return void - */ - public function testSchemaNoDB() { - $model = $this->getMock('Article', array('getDataSource')); - $model->useTable = false; - $model->expects($this->never())->method('getDataSource'); - $this->assertEmpty($model->schema()); - } -} diff --git a/Cake/Test/TestCase/Model/ModelReadTest.php b/Cake/Test/TestCase/Model/ModelReadTest.php deleted file mode 100644 index 95e52a72eb8..00000000000 --- a/Cake/Test/TestCase/Model/ModelReadTest.php +++ /dev/null @@ -1,8236 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Model\Datasource\DboSource; -use Cake\Model\Model; -use Cake\Model\ModelBehavior; -use Cake\TestSuite\TestCase; -use Cake\Test\TestCase\Model\ModelTestBase; - -/** - * ModelReadTest - * - */ -class ModelReadTest extends ModelTestBase { - -/** - * testExists function - * @return void - */ - public function testExists() { - $this->loadFixtures('User'); - $TestModel = new User(); - - $this->assertTrue($TestModel->exists(1)); - - $TestModel->id = 2; - $this->assertTrue($TestModel->exists()); - - $TestModel->delete(); - $this->assertFalse($TestModel->exists()); - - $this->assertFalse($TestModel->exists(2)); - } - -/** - * testFetchingNonUniqueFKJoinTableRecords() - * - * Tests if the results are properly returned in the case there are non-unique FK's - * in the join table but another fields value is different. For example: - * something_id | something_else_id | doomed = 1 - * something_id | something_else_id | doomed = 0 - * Should return both records and not just one. - * - * @return void - */ - public function testFetchingNonUniqueFKJoinTableRecords() { - $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - $Something = new Something(); - - $joinThingData = array( - 'JoinThing' => array( - 'something_id' => 1, - 'something_else_id' => 2, - 'doomed' => '0', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ) - ); - - $Something->JoinThing->create($joinThingData); - $Something->JoinThing->save(); - - $result = $Something->JoinThing->find('all', array('conditions' => array('something_else_id' => 2))); - - $this->assertEquals(true, $result[0]['JoinThing']['doomed']); - $this->assertEquals(false, $result[1]['JoinThing']['doomed']); - - $result = $Something->find('first'); - - $this->assertEquals(2, count($result['SomethingElse'])); - - $doomed = Hash::extract($result['SomethingElse'], '{n}.JoinThing.doomed'); - $this->assertTrue(in_array(true, $doomed)); - $this->assertTrue(in_array(false, $doomed)); - } - -/** - * testGroupBy method - * - * These tests will never pass with Postgres or Oracle as all fields in a select must be - * part of an aggregate function or in the GROUP BY statement. - * - * @return void - */ - public function testGroupBy() { - $isStrictGroupBy = $this->db instanceof Postgres || $this->db instanceof Sqlite || $this->db instanceof Oracle || $this->db instanceof Sqlserver; - $message = 'Postgres, Oracle, SQLite and SQL Server have strict GROUP BY and are incompatible with this test.'; - - $this->skipIf($isStrictGroupBy, $message); - - $this->loadFixtures('Project', 'Product', 'Thread', 'Message', 'Bid'); - $Thread = new Thread(); - $Product = new Product(); - - $result = $Thread->find('all', array( - 'group' => 'Thread.project_id', - 'order' => 'Thread.id ASC' - )); - - $expected = array( - array( - 'Thread' => array( - 'id' => 1, - 'project_id' => 1, - 'name' => 'Project 1, Thread 1' - ), - 'Project' => array( - 'id' => 1, - 'name' => 'Project 1' - ), - 'Message' => array( - array( - 'id' => 1, - 'thread_id' => 1, - 'name' => 'Thread 1, Message 1' - ))), - array( - 'Thread' => array( - 'id' => 3, - 'project_id' => 2, - 'name' => 'Project 2, Thread 1' - ), - 'Project' => array( - 'id' => 2, - 'name' => 'Project 2' - ), - 'Message' => array( - array( - 'id' => 3, - 'thread_id' => 3, - 'name' => 'Thread 3, Message 1' - )))); - $this->assertEquals($expected, $result); - - $rows = $Thread->find('all', array( - 'group' => 'Thread.project_id', - 'fields' => array('Thread.project_id', 'COUNT(*) AS total') - )); - $result = array(); - foreach ($rows as $row) { - $result[$row['Thread']['project_id']] = $row[0]['total']; - } - $expected = array( - 1 => 2, - 2 => 1 - ); - $this->assertEquals($expected, $result); - - $rows = $Thread->find('all', array( - 'group' => 'Thread.project_id', - 'fields' => array('Thread.project_id', 'COUNT(*) AS total'), - 'order' => 'Thread.project_id' - )); - $result = array(); - foreach ($rows as $row) { - $result[$row['Thread']['project_id']] = $row[0]['total']; - } - $expected = array( - 1 => 2, - 2 => 1 - ); - $this->assertEquals($expected, $result); - - $result = $Thread->find('all', array( - 'conditions' => array('Thread.project_id' => 1), - 'group' => 'Thread.project_id' - )); - $expected = array( - array( - 'Thread' => array( - 'id' => 1, - 'project_id' => 1, - 'name' => 'Project 1, Thread 1' - ), - 'Project' => array( - 'id' => 1, - 'name' => 'Project 1' - ), - 'Message' => array( - array( - 'id' => 1, - 'thread_id' => 1, - 'name' => 'Thread 1, Message 1' - )))); - $this->assertEquals($expected, $result); - - $result = $Thread->find('all', array( - 'conditions' => array('Thread.project_id' => 1), - 'group' => 'Thread.project_id, Project.id' - )); - $this->assertEquals($expected, $result); - - $result = $Thread->find('all', array( - 'conditions' => array('Thread.project_id' => 1), - 'group' => 'project_id' - )); - $this->assertEquals($expected, $result); - - $result = $Thread->find('all', array( - 'conditions' => array('Thread.project_id' => 1), - 'group' => array('project_id') - )); - $this->assertEquals($expected, $result); - - $result = $Thread->find('all', array( - 'conditions' => array('Thread.project_id' => 1), - 'group' => array('project_id', 'Project.id') - )); - $this->assertEquals($expected, $result); - - $result = $Thread->find('all', array( - 'conditions' => array('Thread.project_id' => 1), - 'group' => array('Thread.project_id', 'Project.id') - )); - $this->assertEquals($expected, $result); - - $expected = array( - array('Product' => array('type' => 'Clothing'), array('price' => 32)), - array('Product' => array('type' => 'Food'), array('price' => 9)), - array('Product' => array('type' => 'Music'), array('price' => 4)), - array('Product' => array('type' => 'Toy'), array('price' => 3)) - ); - $result = $Product->find('all', array( - 'fields' => array('Product.type', 'MIN(Product.price) as price'), - 'group' => 'Product.type', - 'order' => 'Product.type ASC' - )); - $this->assertEquals($expected, $result); - - $result = $Product->find('all', array( - 'fields' => array('Product.type', 'MIN(Product.price) as price'), - 'group' => array('Product.type'), - 'order' => 'Product.type ASC')); - $this->assertEquals($expected, $result); - } - -/** - * testOldQuery method - * - * @return void - */ - public function testOldQuery() { - $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag', 'Comment', 'Attachment'); - $Article = new Article(); - - $query = 'SELECT title FROM '; - $query .= $this->db->fullTableName('articles'); - $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.id IN (1,2)'; - - $results = $Article->query($query); - $this->assertTrue(is_array($results)); - $this->assertEquals(2, count($results)); - - $query = 'SELECT title, body FROM '; - $query .= $this->db->fullTableName('articles'); - $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.id = 1'; - - $results = $Article->query($query, false); - $this->assertFalse($this->db->getQueryCache($query)); - $this->assertTrue(is_array($results)); - - $query = 'SELECT title, id FROM '; - $query .= $this->db->fullTableName('articles'); - $query .= ' WHERE ' . $this->db->fullTableName('articles'); - $query .= '.published = ' . $this->db->value('Y'); - - $results = $Article->query($query, true); - $result = $this->db->getQueryCache($query); - $this->assertFalse(empty($result)); - $this->assertTrue(is_array($results)); - } - -/** - * testPreparedQuery method - * - * @return void - */ - public function testPreparedQuery() { - $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag'); - $Article = new Article(); - - $query = 'SELECT title, published FROM '; - $query .= $this->db->fullTableName('articles'); - $query .= ' WHERE ' . $this->db->fullTableName('articles'); - $query .= '.id = ? AND ' . $this->db->fullTableName('articles') . '.published = ?'; - - $params = array(1, 'Y'); - $result = $Article->query($query, $params); - $expected = array( - '0' => array( - $this->db->fullTableName('articles', false, false) => array( - 'title' => 'First Article', 'published' => 'Y') - )); - - if (isset($result[0][0])) { - $expected[0][0] = $expected[0][$this->db->fullTableName('articles', false, false)]; - unset($expected[0][$this->db->fullTableName('articles', false, false)]); - } - - $this->assertEquals($expected, $result); - $result = $this->db->getQueryCache($query, $params); - $this->assertFalse(empty($result)); - - $query = 'SELECT id, created FROM '; - $query .= $this->db->fullTableName('articles'); - $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.title = ?'; - - $params = array('First Article'); - $result = $Article->query($query, $params, false); - $this->assertTrue(is_array($result)); - $this->assertTrue( - isset($result[0][$this->db->fullTableName('articles', false, false)]) || - isset($result[0][0]) - ); - $result = $this->db->getQueryCache($query, $params); - $this->assertTrue(empty($result)); - - $query = 'SELECT title FROM '; - $query .= $this->db->fullTableName('articles'); - $query .= ' WHERE ' . $this->db->fullTableName('articles') . '.title LIKE ?'; - - $params = array('%First%'); - $result = $Article->query($query, $params); - $this->assertTrue(is_array($result)); - $this->assertTrue( - isset($result[0][$this->db->fullTableName('articles', false, false)]['title']) || - isset($result[0][0]['title']) - ); - - //related to ticket #5035 - $query = 'SELECT title FROM '; - $query .= $this->db->fullTableName('articles') . ' WHERE title = ? AND published = ?'; - $params = array('First? Article', 'Y'); - $Article->query($query, $params); - - $result = $this->db->getQueryCache($query, $params); - $this->assertFalse($result === false); - } - -/** - * testParameterMismatch method - * - * @expectedException PDOException - * @return void - */ - public function testParameterMismatch() { - $this->skipIf($this->db instanceof Sqlite, 'Sqlite does not accept real prepared statements, no way to check this'); - $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag'); - $Article = new Article(); - - $query = 'SELECT * FROM ' . $this->db->fullTableName('articles'); - $query .= ' WHERE ' . $this->db->fullTableName('articles'); - $query .= '.published = ? AND ' . $this->db->fullTableName('articles') . '.user_id = ?'; - $params = array('Y'); - - $Article->query($query, $params); - } - -/** - * testVeryStrangeUseCase method - * - * @expectedException PDOException - * @return void - */ - public function testVeryStrangeUseCase() { - $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag'); - $Article = new Article(); - - $query = 'SELECT * FROM ? WHERE ? = ? AND ? = ?'; - $param = array( - $this->db->fullTableName('articles'), - $this->db->fullTableName('articles') . '.user_id', '3', - $this->db->fullTableName('articles') . '.published', 'Y' - ); - - $Article->query($query, $param); - } - -/** - * testRecursiveUnbind method - * - * @return void - */ - public function testRecursiveUnbind() { - $this->skipIf($this->db instanceof Sqlserver, 'The test of testRecursiveUnbind test is not compatible with SQL Server, because it check for time columns.'); - - $this->loadFixtures('Apple', 'Sample'); - $TestModel = new Apple(); - $TestModel->recursive = 2; - - $result = $TestModel->find('all'); - $expected = array( - array( - 'Apple' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))))), - array( - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2', - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - )), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 1, - 'apple_id' => 3, - 'name' => 'sample1' - )), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3' - ), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ))))), - array( - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 1, - 'apple_id' => 3, - 'name' => 'sample1', - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - )), - 'Child' => array() - ), - array( - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', 'mytime' => '22:57:17'), - 'Sample' => array('id' => 2, 'apple_id' => 2, 'name' => 'sample2'), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3', - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - )), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ))))), - array( - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4' - ), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4', - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - )), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4' - ), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))))), - array( - 'Apple' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3' - ), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ), - 'Sample' => array() - ))), - array( - 'Apple' => array( - 'id' => 7, - 'apple_id' => 6, - 'color' => - 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ), - 'Child' => array())); - $this->assertEquals($expected, $result); - - $result = $TestModel->Parent->unbindModel(array('hasOne' => array('Sample'))); - $this->assertTrue($result); - - $result = $TestModel->find('all'); - $expected = array( - array( - 'Apple' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17'), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))))), - array( - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2', - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - )), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', 'modified' => - '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 1, - 'apple_id' => 3, - 'name' => 'sample1' - )), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3' - ), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ))))), - array( - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 1, - 'apple_id' => 3, - 'name' => 'sample1', - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - )), - 'Child' => array() - ), - array( - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3', - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - )), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ))))), - array( - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4', - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - )), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4' - ), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))))), - array( - 'Apple' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ), - 'Sample' => array() - ))), - array( - 'Apple' => array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ), - 'Child' => array() - )); - - $this->assertEquals($expected, $result); - - $result = $TestModel->Parent->unbindModel(array('hasOne' => array('Sample'))); - $this->assertTrue($result); - - $result = $TestModel->unbindModel(array('hasMany' => array('Child'))); - $this->assertTrue($result); - - $result = $TestModel->find('all'); - $expected = array( - array( - 'Apple' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - )), - array( - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2', - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 1, - 'apple_id' => 3, - 'name' => 'sample1', - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3', - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4', - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - )), - array( - 'Apple' => array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ))); - - $this->assertEquals($expected, $result); - - $result = $TestModel->unbindModel(array('hasMany' => 'Child')); - $this->assertTrue($result); - - $result = $TestModel->Sample->unbindModel(array('belongsTo' => 'Apple')); - $this->assertTrue($result); - - $result = $TestModel->find('all'); - $expected = array( - array( - 'Apple' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - )), - array( - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - )), - array( - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 1, - 'apple_id' => 3, - 'name' => 'sample1' - )), - array( - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3' - )), - array( - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4' - ), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4' - )), - array( - 'Apple' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3' - ), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - )), - array( - 'Apple' => array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17', - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->Parent->unbindModel(array('belongsTo' => array('Parent'))); - $this->assertTrue($result); - - $result = $TestModel->unbindModel(array('hasMany' => array('Child'))); - $this->assertTrue($result); - - $result = $TestModel->find('all'); - $expected = array( - array( - 'Apple' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - )), - array( - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17', - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2', - 'Apple' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 1, - 'apple_id' => 3, - 'name' => 'sample1', - 'Apple' => array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 2, - 'apple_id' => 1, - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17', - 'Sample' => array( - 'id' => 2, - 'apple_id' => 2, - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => 1, - 'apple_id' => 2, - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => 3, - 'apple_id' => 2, - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3', - 'Apple' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => - '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17', - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4' - ), - 'Child' => array( - array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => 4, - 'apple_id' => 5, - 'name' => 'sample4', - 'Apple' => array( - 'id' => 5, - 'apple_id' => 5, - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17'), - 'Parent' => array( - 'id' => 4, - 'apple_id' => 2, - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17', - 'Sample' => array( - 'id' => 3, - 'apple_id' => 4, - 'name' => 'sample3' - ), - 'Child' => array( - array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - )), - array( - 'Apple' => array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => 6, - 'apple_id' => 4, - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17', - 'Sample' => array(), - 'Child' => array( - array( - 'id' => 7, - 'apple_id' => 6, - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', 'modified' => - '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ))), - 'Sample' => array( - 'id' => '', - 'apple_id' => '', - 'name' => '' - ))); - $this->assertEquals($expected, $result); - } - -/** - * testSelfAssociationAfterFind method - * - * @return void - */ - public function testSelfAssociationAfterFind() { - $this->loadFixtures('Apple', 'Sample'); - $afterFindModel = new NodeAfterFind(); - $afterFindModel->recursive = 3; - $afterFindData = $afterFindModel->find('all'); - - $duplicateModel = new NodeAfterFind(); - $duplicateModel->recursive = 3; - - $noAfterFindModel = new NodeNoAfterFind(); - $noAfterFindModel->recursive = 3; - $noAfterFindData = $noAfterFindModel->find('all'); - - $this->assertFalse($afterFindModel == $noAfterFindModel); - $this->assertEquals($afterFindData, $noAfterFindData); - } - -/** - * Test that afterFind can completely unset data. - * - * @return void - */ - public function testAfterFindUnset() { - $this->loadFixtures('Article', 'Comment', 'User'); - $model = new CustomArticle(); - $model->bindModel(array( - 'hasMany' => array( - 'ModifiedComment' => array( - 'className' => 'ModifiedComment', - 'foreignKey' => 'article_id', - ) - ) - )); - $model->ModifiedComment->remove = true; - $result = $model->find('all'); - $this->assertTrue( - empty($result[0]['ModifiedComment']), - 'Zeroith row should be removed by afterFind' - ); - } - -/** - * testFindThreadedNoParent method - * - * @return void - */ - public function testFindThreadedNoParent() { - $this->loadFixtures('Apple', 'Sample'); - $Apple = new Apple(); - $result = $Apple->find('threaded'); - $result = Hash::extract($result, '{n}.children'); - $expected = array(array(), array(), array(), array(), array(), array(), array()); - $this->assertEquals($expected, $result); - } - -/** - * testFindThreaded method - * - * @return void - */ - public function testFindThreaded() { - $this->loadFixtures('Person'); - $Model = new Person(); - $Model->recursive = -1; - $result = $Model->find('threaded'); - $result = Hash::extract($result, '{n}.children'); - $expected = array(array(), array(), array(), array(), array(), array(), array()); - $this->assertEquals($expected, $result); - - $result = $Model->find('threaded', array('parent' => 'mother_id')); - $expected = array( - array( - 'Person' => array( - 'id' => '4', - 'name' => 'mother - grand mother', - 'mother_id' => '0', - 'father_id' => '0' - ), - 'children' => array( - array( - 'Person' => array( - 'id' => '2', - 'name' => 'mother', - 'mother_id' => '4', - 'father_id' => '5' - ), - 'children' => array( - array( - 'Person' => array( - 'id' => '1', - 'name' => 'person', - 'mother_id' => '2', - 'father_id' => '3' - ), - 'children' => array() - ) - ) - ) - ) - ), - array( - 'Person' => array( - 'id' => '5', - 'name' => 'mother - grand father', - 'mother_id' => '0', - 'father_id' => '0' - ), - 'children' => array() - ), - array( - 'Person' => array( - 'id' => '6', - 'name' => 'father - grand mother', - 'mother_id' => '0', - 'father_id' => '0' - ), - 'children' => array( - array( - 'Person' => array( - 'id' => '3', - 'name' => 'father', - 'mother_id' => '6', - 'father_id' => '7' - ), - 'children' => array() - ) - ) - ), - array( - 'Person' => array( - 'id' => '7', - 'name' => 'father - grand father', - 'mother_id' => '0', - 'father_id' => '0' - ), - 'children' => array() - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testFindAllThreaded method - * - * @return void - */ - public function testFindAllThreaded() { - $this->loadFixtures('Category'); - $TestModel = new Category(); - - $result = $TestModel->find('threaded'); - $expected = array( - array( - 'Category' => array( - 'id' => '1', - 'parent_id' => '0', - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => '2', - 'parent_id' => '1', - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array('Category' => array( - 'id' => '7', - 'parent_id' => '2', - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array()), - array('Category' => array( - 'id' => '8', - 'parent_id' => '2', - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array())) - ), - array( - 'Category' => array( - 'id' => '3', - 'parent_id' => '1', - 'name' => 'Category 1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array() - ) - ) - ), - array( - 'Category' => array( - 'id' => '4', - 'parent_id' => '0', - 'name' => 'Category 2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array() - ), - array( - 'Category' => array( - 'id' => '5', - 'parent_id' => '0', - 'name' => 'Category 3', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => '6', - 'parent_id' => '5', - 'name' => 'Category 3.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array() - ) - ) - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('threaded', array( - 'conditions' => array('Category.name LIKE' => 'Category 1%') - )); - - $expected = array( - array( - 'Category' => array( - 'id' => '1', - 'parent_id' => '0', - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => '2', - 'parent_id' => '1', - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array('Category' => array( - 'id' => '7', - 'parent_id' => '2', - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array()), - array('Category' => array( - 'id' => '8', - 'parent_id' => '2', - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array())) - ), - array( - 'Category' => array( - 'id' => '3', - 'parent_id' => '1', - 'name' => 'Category 1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array() - ) - ) - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('threaded', array( - 'fields' => 'id, parent_id, name' - )); - - $expected = array( - array( - 'Category' => array( - 'id' => '1', - 'parent_id' => '0', - 'name' => 'Category 1' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => '2', - 'parent_id' => '1', - 'name' => 'Category 1.1' - ), - 'children' => array( - array('Category' => array( - 'id' => '7', - 'parent_id' => '2', - 'name' => 'Category 1.1.1'), - 'children' => array()), - array('Category' => array( - 'id' => '8', - 'parent_id' => '2', - 'name' => 'Category 1.1.2'), - 'children' => array())) - ), - array( - 'Category' => array( - 'id' => '3', - 'parent_id' => '1', - 'name' => 'Category 1.2' - ), - 'children' => array() - ) - ) - ), - array( - 'Category' => array( - 'id' => '4', - 'parent_id' => '0', - 'name' => 'Category 2' - ), - 'children' => array() - ), - array( - 'Category' => array( - 'id' => '5', - 'parent_id' => '0', - 'name' => 'Category 3' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => '6', - 'parent_id' => '5', - 'name' => 'Category 3.1' - ), - 'children' => array() - ) - ) - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('threaded', array('order' => 'id DESC')); - - $expected = array( - array( - 'Category' => array( - 'id' => 5, - 'parent_id' => 0, - 'name' => 'Category 3', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => 6, - 'parent_id' => 5, - 'name' => 'Category 3.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array() - ) - ) - ), - array( - 'Category' => array( - 'id' => 4, - 'parent_id' => 0, - 'name' => 'Category 2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array() - ), - array( - 'Category' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => 3, - 'parent_id' => 1, - 'name' => 'Category 1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array() - ), - array( - 'Category' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array('Category' => array( - 'id' => '8', - 'parent_id' => '2', - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array()), - array('Category' => array( - 'id' => '7', - 'parent_id' => '2', - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array())) - ) - ) - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('threaded', array( - 'conditions' => array('Category.name LIKE' => 'Category 3%') - )); - $expected = array( - array( - 'Category' => array( - 'id' => '5', - 'parent_id' => '0', - 'name' => 'Category 3', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => '6', - 'parent_id' => '5', - 'name' => 'Category 3.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'children' => array() - ) - ) - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('threaded', array( - 'conditions' => array('Category.name LIKE' => 'Category 1.1%') - )); - $expected = array( - array('Category' => - array( - 'id' => '2', - 'parent_id' => '1', - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array( - array('Category' => array( - 'id' => '7', - 'parent_id' => '2', - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array()), - array('Category' => array( - 'id' => '8', - 'parent_id' => '2', - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31'), - 'children' => array())))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('threaded', array( - 'fields' => 'id, parent_id, name', - 'conditions' => array('Category.id !=' => 2) - )); - $expected = array( - array( - 'Category' => array( - 'id' => '1', - 'parent_id' => '0', - 'name' => 'Category 1' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => '3', - 'parent_id' => '1', - 'name' => 'Category 1.2' - ), - 'children' => array() - ) - ) - ), - array( - 'Category' => array( - 'id' => '4', - 'parent_id' => '0', - 'name' => 'Category 2' - ), - 'children' => array() - ), - array( - 'Category' => array( - 'id' => '5', - 'parent_id' => '0', - 'name' => 'Category 3' - ), - 'children' => array( - array( - 'Category' => array( - 'id' => '6', - 'parent_id' => '5', - 'name' => 'Category 3.1' - ), - 'children' => array() - ) - ) - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array( - 'fields' => 'id, name, parent_id', - 'conditions' => array('Category.id !=' => 1) - )); - $expected = array( - array('Category' => array( - 'id' => '2', - 'name' => 'Category 1.1', - 'parent_id' => '1' - )), - array('Category' => array( - 'id' => '3', - 'name' => 'Category 1.2', - 'parent_id' => '1' - )), - array('Category' => array( - 'id' => '4', - 'name' => 'Category 2', - 'parent_id' => '0' - )), - array('Category' => array( - 'id' => '5', - 'name' => 'Category 3', - 'parent_id' => '0' - )), - array('Category' => array( - 'id' => '6', - 'name' => 'Category 3.1', - 'parent_id' => '5' - )), - array('Category' => array( - 'id' => '7', - 'name' => 'Category 1.1.1', - 'parent_id' => '2' - )), - array('Category' => array( - 'id' => '8', - 'name' => 'Category 1.1.2', - 'parent_id' => '2' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('threaded', array( - 'fields' => 'id, parent_id, name', - 'conditions' => array('Category.id !=' => 1) - )); - $expected = array( - array( - 'Category' => array( - 'id' => '2', - 'parent_id' => '1', - 'name' => 'Category 1.1' - ), - 'children' => array( - array('Category' => array( - 'id' => '7', - 'parent_id' => '2', - 'name' => 'Category 1.1.1'), - 'children' => array()), - array('Category' => array( - 'id' => '8', - 'parent_id' => '2', - 'name' => 'Category 1.1.2'), - 'children' => array())) - ), - array( - 'Category' => array( - 'id' => '3', - 'parent_id' => '1', - 'name' => 'Category 1.2' - ), - 'children' => array() - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * test find('neighbors') - * - * @return void - */ - public function testFindNeighbors() { - $this->loadFixtures('User', 'Article', 'Comment', 'Tag', 'ArticlesTag', 'Attachment'); - $TestModel = new Article(); - - $TestModel->id = 1; - $result = $TestModel->find('neighbors', array('fields' => array('id'))); - - $this->assertNull($result['prev']); - $this->assertEquals(array('id' => 2), $result['next']['Article']); - $this->assertEquals(2, count($result['next']['Comment'])); - $this->assertEquals(2, count($result['next']['Tag'])); - - $TestModel->id = 2; - $TestModel->recursive = 0; - $result = $TestModel->find('neighbors', array( - 'fields' => array('id') - )); - - $expected = array( - 'prev' => array( - 'Article' => array( - 'id' => 1 - )), - 'next' => array( - 'Article' => array( - 'id' => 3 - ))); - $this->assertEquals($expected, $result); - - $TestModel->id = 3; - $TestModel->recursive = 1; - $result = $TestModel->find('neighbors', array('fields' => array('id'))); - - $this->assertNull($result['next']); - $this->assertEquals(array('id' => 2), $result['prev']['Article']); - $this->assertEquals(2, count($result['prev']['Comment'])); - $this->assertEquals(2, count($result['prev']['Tag'])); - - $TestModel->id = 1; - $result = $TestModel->find('neighbors', array('recursive' => -1)); - $expected = array( - 'prev' => null, - 'next' => array( - 'Article' => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ) - ) - ); - $this->assertEquals($expected, $result); - - $TestModel->id = 2; - $result = $TestModel->find('neighbors', array('recursive' => -1)); - $expected = array( - 'prev' => array( - 'Article' => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ) - ), - 'next' => array( - 'Article' => array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ) - ) - ); - $this->assertEquals($expected, $result); - - $TestModel->id = 3; - $result = $TestModel->find('neighbors', array('recursive' => -1)); - $expected = array( - 'prev' => array( - 'Article' => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ) - ), - 'next' => null - ); - $this->assertEquals($expected, $result); - - $TestModel->recursive = 0; - $TestModel->id = 1; - $one = $TestModel->read(); - $TestModel->id = 2; - $two = $TestModel->read(); - $TestModel->id = 3; - $three = $TestModel->read(); - - $TestModel->id = 1; - $result = $TestModel->find('neighbors'); - $expected = array('prev' => null, 'next' => $two); - $this->assertEquals($expected, $result); - - $TestModel->id = 2; - $result = $TestModel->find('neighbors'); - $expected = array('prev' => $one, 'next' => $three); - $this->assertEquals($expected, $result); - - $TestModel->id = 3; - $result = $TestModel->find('neighbors'); - $expected = array('prev' => $two, 'next' => null); - $this->assertEquals($expected, $result); - - $TestModel->recursive = 2; - $TestModel->id = 1; - $one = $TestModel->read(); - $TestModel->id = 2; - $two = $TestModel->read(); - $TestModel->id = 3; - $three = $TestModel->read(); - - $TestModel->id = 1; - $result = $TestModel->find('neighbors', array('recursive' => 2)); - $expected = array('prev' => null, 'next' => $two); - $this->assertEquals($expected, $result); - - $TestModel->id = 2; - $result = $TestModel->find('neighbors', array('recursive' => 2)); - $expected = array('prev' => $one, 'next' => $three); - $this->assertEquals($expected, $result); - - $TestModel->id = 3; - $result = $TestModel->find('neighbors', array('recursive' => 2)); - $expected = array('prev' => $two, 'next' => null); - $this->assertEquals($expected, $result); - } - -/** - * Test find(neighbors) with missing fields so no neighbors are found. - * - * @return void - */ - public function testFindNeighborsNoPrev() { - $this->loadFixtures('User', 'Article', 'Comment', 'Tag', 'ArticlesTag', 'Attachment'); - $Article = new Article(); - - $result = $Article->find('neighbors', array( - 'field' => 'Article.title', - 'value' => 'Second Article', - 'fields' => array('id'), - 'conditions' => array( - 'Article.title LIKE' => '%Article%' - ), - 'recursive' => 0, - )); - $expected = array( - 'prev' => null, - 'next' => null - ); - $this->assertEquals($expected, $result); - } - -/** - * testFindCombinedRelations method - * - * @return void - */ - public function testFindCombinedRelations() { - $this->skipIf($this->db instanceof Sqlserver, 'The test of testRecursiveUnbind test is not compatible with SQL Server, because it check for time columns.'); - - $this->loadFixtures('Apple', 'Sample'); - $TestModel = new Apple(); - - $result = $TestModel->find('all'); - - $expected = array( - array( - 'Apple' => array( - 'id' => '1', - 'apple_id' => '2', - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => '2', - 'apple_id' => '1', - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => null, - 'apple_id' => null, - 'name' => null - ), - 'Child' => array( - array( - 'id' => '2', - 'apple_id' => '1', - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => '2', - 'apple_id' => '1', - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => '1', - 'apple_id' => '2', - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => '2', - 'apple_id' => '2', - 'name' => 'sample2' - ), - 'Child' => array( - array( - 'id' => '1', - 'apple_id' => '2', - 'color' => 'Red 1', - 'name' => 'Red Apple 1', - 'created' => '2006-11-22 10:38:58', - 'date' => '1951-01-04', - 'modified' => '2006-12-01 13:31:26', - 'mytime' => '22:57:17' - ), - array( - 'id' => '3', - 'apple_id' => '2', - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - array( - 'id' => '4', - 'apple_id' => '2', - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => '3', - 'apple_id' => '2', - 'color' => 'blue green', - 'name' => 'green blue', - 'created' => '2006-12-25 05:13:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:24', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => '2', - 'apple_id' => '1', - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => '1', - 'apple_id' => '3', - 'name' => 'sample1' - ), - 'Child' => array() - ), - array( - 'Apple' => array( - 'id' => '4', - 'apple_id' => '2', - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => '2', - 'apple_id' => '1', - 'color' => 'Bright Red 1', - 'name' => 'Bright Red Apple', - 'created' => '2006-11-22 10:43:13', - 'date' => '2014-01-01', - 'modified' => '2006-11-30 18:38:10', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => '3', - 'apple_id' => '4', - 'name' => 'sample3' - ), - 'Child' => array( - array( - 'id' => '6', - 'apple_id' => '4', - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => '5', - 'apple_id' => '5', - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => '5', - 'apple_id' => '5', - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => '4', - 'apple_id' => '5', - 'name' => 'sample4' - ), - 'Child' => array( - array( - 'id' => '5', - 'apple_id' => '5', - 'color' => 'Green', - 'name' => 'Blue Green', - 'created' => '2006-12-25 05:24:06', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:16', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => '6', - 'apple_id' => '4', - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => '4', - 'apple_id' => '2', - 'color' => 'Blue Green', - 'name' => 'Test Name', - 'created' => '2006-12-25 05:23:36', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:23:36', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => null, - 'apple_id' => null, - 'name' => null - ), - 'Child' => array( - array( - 'id' => '7', - 'apple_id' => '6', - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ))), - array( - 'Apple' => array( - 'id' => '7', - 'apple_id' => '6', - 'color' => 'Some wierd color', - 'name' => 'Some odd color', - 'created' => '2006-12-25 05:34:21', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:34:21', - 'mytime' => '22:57:17' - ), - 'Parent' => array( - 'id' => '6', - 'apple_id' => '4', - 'color' => 'My new appleOrange', - 'name' => 'My new apple', - 'created' => '2006-12-25 05:29:39', - 'date' => '2006-12-25', - 'modified' => '2006-12-25 05:29:39', - 'mytime' => '22:57:17' - ), - 'Sample' => array( - 'id' => null, - 'apple_id' => null, - 'name' => null - ), - 'Child' => array() - )); - $this->assertEquals($expected, $result); - } - -/** - * testSaveEmpty method - * - * @return void - */ - public function testSaveEmpty() { - $this->loadFixtures('Thread'); - $TestModel = new Thread(); - $data = array(); - $expected = $TestModel->save($data); - $this->assertFalse($expected); - } - -/** - * testFindAllWithConditionInChildQuery - * - * @return void - */ - public function testFindAllWithConditionInChildQuery() { - $this->loadFixtures('Basket', 'FilmFile'); - - $TestModel = new Basket(); - $recursive = 3; - $result = $TestModel->find('all', compact('recursive')); - - $expected = array( - array( - 'Basket' => array( - 'id' => 1, - 'type' => 'nonfile', - 'name' => 'basket1', - 'object_id' => 1, - 'user_id' => 1, - ), - 'FilmFile' => array( - 'id' => '', - 'name' => '', - ) - ), - array( - 'Basket' => array( - 'id' => 2, - 'type' => 'file', - 'name' => 'basket2', - 'object_id' => 2, - 'user_id' => 1, - ), - 'FilmFile' => array( - 'id' => 2, - 'name' => 'two', - ) - ), - ); - $this->assertEquals($expected, $result); - } - -/** - * testFindAllWithConditionsHavingMixedDataTypes method - * - * @return void - */ - public function testFindAllWithConditionsHavingMixedDataTypes() { - $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag'); - $TestModel = new Article(); - $expected = array( - array( - 'Article' => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ) - ), - array( - 'Article' => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ) - ) - ); - $conditions = array('id' => array('1', 2)); - $recursive = -1; - $order = 'Article.id ASC'; - $result = $TestModel->find('all', compact('conditions', 'recursive', 'order')); - $this->assertEquals($expected, $result); - - $this->skipIf($this->db instanceof Postgres, 'The rest of testFindAllWithConditionsHavingMixedDataTypes test is not compatible with Postgres.'); - - $conditions = array('id' => array('1', 2, '3.0')); - $order = 'Article.id ASC'; - $result = $TestModel->find('all', compact('recursive', 'conditions', 'order')); - $expected = array( - array( - 'Article' => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ) - ), - array( - 'Article' => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ) - ), - array( - 'Article' => array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testBindUnbind method - * - * @return void - */ - public function testBindUnbind() { - $this->loadFixtures( - 'User', - 'Comment', - 'FeatureSet', - 'DeviceType', - 'DeviceTypeCategory', - 'ExteriorTypeCategory', - 'Device', - 'Document', - 'DocumentDirectory' - ); - $TestModel = new User(); - - $result = $TestModel->hasMany; - $expected = array(); - $this->assertEquals($expected, $result); - - $result = $TestModel->bindModel(array('hasMany' => array('Comment'))); - $this->assertTrue($result); - - $result = $TestModel->find('all', array( - 'fields' => 'User.id, User.user', - 'order' => array('User.id' => 'ASC'), - )); - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano' - ), - 'Comment' => array( - array( - 'id' => '3', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Third Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:49:23', - 'updated' => '2007-03-18 10:51:31' - ), - array( - 'id' => '4', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - ), - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ))), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - ))), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry' - ), - 'Comment' => array() - ), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett' - ), - 'Comment' => array( - array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - )))); - - $this->assertEquals($expected, $result); - - $TestModel->resetAssociations(); - $result = $TestModel->hasMany; - $this->assertSame(array(), $result); - - $result = $TestModel->bindModel(array('hasMany' => array('Comment')), false); - $this->assertTrue($result); - - $result = $TestModel->find('all', array( - 'fields' => 'User.id, User.user', - 'order' => array('User.id' => 'ASC'), - )); - - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano' - ), - 'Comment' => array( - array( - 'id' => '3', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Third Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:49:23', - 'updated' => '2007-03-18 10:51:31' - ), - array( - 'id' => '4', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - ), - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ))), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - ))), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry' - ), - 'Comment' => array() - ), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett' - ), - 'Comment' => array( - array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - )))); - - $this->assertEquals($expected, $result); - - $result = $TestModel->hasMany; - $expected = array( - 'Comment' => array( - 'className' => 'Comment', - 'foreignKey' => 'user_id', - 'conditions' => null, - 'fields' => null, - 'order' => null, - 'limit' => null, - 'offset' => null, - 'dependent' => null, - 'exclusive' => null, - 'finderQuery' => null, - 'counterQuery' => null - )); - $this->assertEquals($expected, $result); - - $result = $TestModel->unbindModel(array('hasMany' => array('Comment'))); - $this->assertTrue($result); - - $result = $TestModel->hasMany; - $expected = array(); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array( - 'fields' => 'User.id, User.user', - 'order' => array('User.id' => 'ASC'), - )); - $expected = array( - array('User' => array('id' => '1', 'user' => 'mariano')), - array('User' => array('id' => '2', 'user' => 'nate')), - array('User' => array('id' => '3', 'user' => 'larry')), - array('User' => array('id' => '4', 'user' => 'garrett'))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array( - 'fields' => 'User.id, User.user', - 'order' => array('User.id' => 'ASC'), - )); - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano' - ), - 'Comment' => array( - array( - 'id' => '3', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Third Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:49:23', - 'updated' => '2007-03-18 10:51:31' - ), - array( - 'id' => '4', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - ), - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ))), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - ))), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry' - ), - 'Comment' => array() - ), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett' - ), - 'Comment' => array( - array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => - 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - )))); - $this->assertEquals($expected, $result); - - $result = $TestModel->unbindModel(array('hasMany' => array('Comment')), false); - $this->assertTrue($result); - - $result = $TestModel->find('all', array( - 'fields' => 'User.id, User.user', - 'order' => array('User.id' => 'ASC'), - )); - $expected = array( - array('User' => array('id' => '1', 'user' => 'mariano')), - array('User' => array('id' => '2', 'user' => 'nate')), - array('User' => array('id' => '3', 'user' => 'larry')), - array('User' => array('id' => '4', 'user' => 'garrett'))); - $this->assertEquals($expected, $result); - - $result = $TestModel->hasMany; - $expected = array(); - $this->assertEquals($expected, $result); - - $result = $TestModel->bindModel(array('hasMany' => array( - 'Comment' => array('className' => 'Comment', 'conditions' => 'Comment.published = \'Y\'') - ))); - $this->assertTrue($result); - - $result = $TestModel->find('all', array( - 'fields' => 'User.id, User.user', - 'order' => array('User.id' => 'ASC'), - )); - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano' - ), - 'Comment' => array( - array( - 'id' => '3', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Third Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:49:23', - 'updated' => '2007-03-18 10:51:31' - ), - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ))), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - ))), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry' - ), - 'Comment' => array() - ), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett' - ), - 'Comment' => array( - array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - )))); - - $this->assertEquals($expected, $result); - - $TestModel2 = new DeviceType(); - - $expected = array( - 'className' => 'FeatureSet', - 'foreignKey' => 'feature_set_id', - 'conditions' => '', - 'fields' => '', - 'order' => '', - 'counterCache' => '' - ); - $this->assertEquals($expected, $TestModel2->belongsTo['FeatureSet']); - - $TestModel2->bindModel(array( - 'belongsTo' => array( - 'FeatureSet' => array( - 'className' => 'FeatureSet', - 'conditions' => array('active' => true) - ) - ) - )); - $expected['conditions'] = array('active' => true); - $this->assertEquals($expected, $TestModel2->belongsTo['FeatureSet']); - - $TestModel2->bindModel(array( - 'belongsTo' => array( - 'FeatureSet' => array( - 'className' => 'FeatureSet', - 'foreignKey' => false, - 'conditions' => array('Feature.name' => 'DeviceType.name') - ) - ) - )); - $expected['conditions'] = array('Feature.name' => 'DeviceType.name'); - $expected['foreignKey'] = false; - $this->assertEquals($expected, $TestModel2->belongsTo['FeatureSet']); - - $TestModel2->bindModel(array( - 'hasMany' => array( - 'NewFeatureSet' => array( - 'className' => 'FeatureSet', - 'conditions' => array('active' => true) - ) - ) - )); - - $expected = array( - 'className' => 'FeatureSet', - 'conditions' => array('active' => true), - 'foreignKey' => 'device_type_id', - 'fields' => '', - 'order' => '', - 'limit' => '', - 'offset' => '', - 'dependent' => '', - 'exclusive' => '', - 'finderQuery' => '', - 'counterQuery' => '' - ); - $this->assertEquals($expected, $TestModel2->hasMany['NewFeatureSet']); - $this->assertTrue(is_object($TestModel2->NewFeatureSet)); - } - -/** - * testBindMultipleTimes method - * - * @return void - */ - public function testBindMultipleTimes() { - $this->loadFixtures('User', 'Comment', 'Article', 'Tag', 'ArticlesTag'); - $TestModel = new User(); - - $result = $TestModel->hasMany; - $expected = array(); - $this->assertEquals($expected, $result); - - $result = $TestModel->bindModel(array( - 'hasMany' => array( - 'Items' => array('className' => 'Comment') - ))); - $this->assertTrue($result); - - $result = $TestModel->find('all', array( - 'fields' => 'User.id, User.user' - )); - - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano' - ), - 'Items' => array( - array( - 'id' => '3', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Third Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:49:23', - 'updated' => '2007-03-18 10:51:31' - ), - array( - 'id' => '4', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - ), - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ))), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate' - ), - 'Items' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - ))), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry' - ), - 'Items' => array() - ), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett' - ), - 'Items' => array( - array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - )))); - $this->assertEquals($expected, $result); - - $result = $TestModel->bindModel(array( - 'hasMany' => array( - 'Items' => array('className' => 'Article') - ))); - $this->assertTrue($result); - - $result = $TestModel->find('all', array( - 'fields' => 'User.id, User.user' - )); - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano' - ), - 'Items' => array( - array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ))), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate' - ), - 'Items' => array() - ), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry' - ), - 'Items' => array( - array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ))), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett' - ), - 'Items' => array() - )); - - $this->assertEquals($expected, $result); - } - -/** - * test that multiple reset = true calls to bindModel() result in the original associations. - * - * @return void - */ - public function testBindModelMultipleTimesResetCorrectly() { - $this->loadFixtures('User', 'Comment', 'Article'); - $TestModel = new User(); - - $TestModel->bindModel(array('hasMany' => array('Comment'))); - $TestModel->bindModel(array('hasMany' => array('Comment'))); - $TestModel->resetAssociations(); - - $this->assertFalse(isset($TestModel->hasMany['Comment']), 'Association left behind'); - } - -/** - * testBindMultipleTimes method with different reset settings - * - * @return void - */ - public function testBindMultipleTimesWithDifferentResetSettings() { - $this->loadFixtures('User', 'Comment', 'Article'); - $TestModel = new User(); - - $result = $TestModel->hasMany; - $expected = array(); - $this->assertEquals($expected, $result); - - $result = $TestModel->bindModel(array( - 'hasMany' => array('Comment') - )); - $this->assertTrue($result); - $result = $TestModel->bindModel( - array('hasMany' => array('Article')), - false - ); - $this->assertTrue($result); - - $result = array_keys($TestModel->hasMany); - $expected = array('Comment', 'Article'); - $this->assertEquals($expected, $result); - - $TestModel->resetAssociations(); - - $result = array_keys($TestModel->hasMany); - $expected = array('Article'); - $this->assertEquals($expected, $result); - } - -/** - * test that bindModel behaves with Custom primary Key associations - * - * @return void - */ - public function testBindWithCustomPrimaryKey() { - $this->loadFixtures('Story', 'StoriesTag', 'Tag'); - $Model = ClassRegistry::init('StoriesTag'); - $Model->bindModel(array( - 'belongsTo' => array( - 'Tag' => array( - 'className' => 'Tag', - 'foreignKey' => 'story' - )))); - - $result = $Model->find('all'); - $this->assertFalse(empty($result)); - } - -/** - * test that calling unbindModel() with reset == true multiple times - * leaves associations in the correct state. - * - * @return void - */ - public function testUnbindMultipleTimesResetCorrectly() { - $this->loadFixtures('User', 'Comment', 'Article'); - $TestModel = new Article10(); - - $TestModel->unbindModel(array('hasMany' => array('Comment'))); - $TestModel->unbindModel(array('hasMany' => array('Comment'))); - $TestModel->resetAssociations(); - - $this->assertTrue(isset($TestModel->hasMany['Comment']), 'Association permanently removed'); - } - -/** - * testBindMultipleTimes method with different reset settings - * - * @return void - */ - public function testUnBindMultipleTimesWithDifferentResetSettings() { - $this->loadFixtures('User', 'Comment', 'Article'); - $TestModel = new Comment(); - - $result = array_keys($TestModel->belongsTo); - $expected = array('Article', 'User'); - $this->assertEquals($expected, $result); - - $result = $TestModel->unbindModel(array( - 'belongsTo' => array('User') - )); - $this->assertTrue($result); - $result = $TestModel->unbindModel( - array('belongsTo' => array('Article')), - false - ); - $this->assertTrue($result); - - $result = array_keys($TestModel->belongsTo); - $expected = array(); - $this->assertEquals($expected, $result); - - $TestModel->resetAssociations(); - - $result = array_keys($TestModel->belongsTo); - $expected = array('User'); - $this->assertEquals($expected, $result); - } - -/** - * testAssociationAfterFind method - * - * @return void - */ - public function testAssociationAfterFind() { - $this->loadFixtures('Post', 'Author', 'Comment'); - $TestModel = new Post(); - $result = $TestModel->find('all', array( - 'order' => array('Post.id' => 'ASC') - )); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'Author' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31', - 'test' => 'working' - )), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '3', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'Author' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31', - 'test' => 'working' - )), - array( - 'Post' => array( - 'id' => '3', - 'author_id' => '1', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'Author' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31', - 'test' => 'working' - ))); - $this->assertEquals($expected, $result); - unset($TestModel); - - $Author = new Author(); - $Author->Post->bindModel(array( - 'hasMany' => array( - 'Comment' => array( - 'className' => 'ModifiedComment', - 'foreignKey' => 'article_id', - ) - ))); - $result = $Author->find('all', array( - 'conditions' => array('Author.id' => 1), - 'order' => array('Author.id' => 'ASC'), - 'recursive' => 2 - )); - $expected = array( - 'id' => 1, - 'article_id' => 1, - 'user_id' => 2, - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31', - 'callback' => 'Fire' - ); - $this->assertEquals($expected, $result[0]['Post'][0]['Comment'][0]); - } - -/** - * testDeeperAssociationAfterFind method - * - * @return void - */ - public function testDeeperAssociationAfterFind() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article'); - - $Post = new Post(); - $Post->bindModel(array( - 'hasMany' => array( - 'Comment' => array( - 'className' => 'ModifiedComment', - 'foreignKey' => 'article_id', - ) - ))); - $Post->Comment->bindModel(array( - 'hasOne' => array( - 'Attachment' => array( - 'className' => 'ModifiedAttachment', - ) - ))); - - $result = $Post->find('first', array( - 'conditions' => array('Post.id' => 2), - 'recursive' => 2 - )); - $this->assertTrue(isset($result['Comment'][0]['callback'])); - $this->assertEquals('Fire', $result['Comment'][0]['callback']); - $this->assertTrue(isset($result['Comment'][0]['Attachment']['callback'])); - $this->assertEquals('Fired', $result['Comment'][0]['Attachment']['callback']); - } - -/** - * Tests that callbacks can be properly disabled - * - * @return void - */ - public function testCallbackDisabling() { - $this->loadFixtures('Author'); - $TestModel = new ModifiedAuthor(); - - $result = Hash::extract($TestModel->find('all'), '{n}.Author.user'); - $expected = array('mariano (CakePHP)', 'nate (CakePHP)', 'larry (CakePHP)', 'garrett (CakePHP)'); - $this->assertEquals($expected, $result); - - $result = Hash::extract($TestModel->find('all', array('callbacks' => 'after')), '{n}.Author.user'); - $expected = array('mariano (CakePHP)', 'nate (CakePHP)', 'larry (CakePHP)', 'garrett (CakePHP)'); - $this->assertEquals($expected, $result); - - $result = Hash::extract($TestModel->find('all', array('callbacks' => 'before')), '{n}.Author.user'); - $expected = array('mariano', 'nate', 'larry', 'garrett'); - $this->assertEquals($expected, $result); - - $result = Hash::extract($TestModel->find('all', array('callbacks' => false)), '{n}.Author.user'); - $expected = array('mariano', 'nate', 'larry', 'garrett'); - $this->assertEquals($expected, $result); - } - -/** - * testAssociationAfterFindCallbacksDisabled method - * - * @return void - */ - public function testAssociationAfterFindCalbacksDisabled() { - $this->loadFixtures('Post', 'Author', 'Comment'); - $TestModel = new Post(); - $result = $TestModel->find('all', array( - 'callbacks' => false, - 'order' => array('Post.id' => 'ASC'), - )); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'Author' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - )), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '3', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'Author' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - )), - array( - 'Post' => array( - 'id' => '3', - 'author_id' => '1', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'Author' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ))); - $this->assertEquals($expected, $result); - unset($TestModel); - - $Author = new Author(); - $Author->Post->bindModel(array( - 'hasMany' => array( - 'Comment' => array( - 'className' => 'ModifiedComment', - 'foreignKey' => 'article_id', - ) - ))); - $result = $Author->find('all', array( - 'conditions' => array('Author.id' => 1), - 'recursive' => 2, - 'order' => array('Author.id' => 'ASC'), - 'callbacks' => false - )); - $expected = array( - 'id' => 1, - 'article_id' => 1, - 'user_id' => 2, - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ); - $this->assertEquals($expected, $result[0]['Post'][0]['Comment'][0]); - } - -/** - * Tests that the database configuration assigned to the model can be changed using - * (before|after)Find callbacks - * - * @return void - */ - public function testCallbackSourceChange() { - $this->loadFixtures('Post'); - $TestModel = new Post(); - $this->assertEquals(3, count($TestModel->find('all'))); - } - -/** - * testCallbackSourceChangeUnknownDatasource method - * - * @expectedException MissingDatasourceConfigException - * @return void - */ - public function testCallbackSourceChangeUnknownDatasource() { - $this->loadFixtures('Post', 'Author'); - $TestModel = new Post(); - $this->assertFalse($TestModel->find('all', array('connection' => 'foo'))); - } - -/** - * testMultipleBelongsToWithSameClass method - * - * @return void - */ - public function testMultipleBelongsToWithSameClass() { - $this->loadFixtures( - 'DeviceType', - 'DeviceTypeCategory', - 'FeatureSet', - 'ExteriorTypeCategory', - 'Document', - 'Device', - 'DocumentDirectory' - ); - - $DeviceType = new DeviceType(); - - $DeviceType->recursive = 2; - $result = $DeviceType->read(null, 1); - - $expected = array( - 'DeviceType' => array( - 'id' => 1, - 'device_type_category_id' => 1, - 'feature_set_id' => 1, - 'exterior_type_category_id' => 1, - 'image_id' => 1, - 'extra1_id' => 1, - 'extra2_id' => 1, - 'name' => 'DeviceType 1', - 'order' => 0 - ), - 'Image' => array( - 'id' => 1, - 'document_directory_id' => 1, - 'name' => 'Document 1', - 'DocumentDirectory' => array( - 'id' => 1, - 'name' => 'DocumentDirectory 1' - )), - 'Extra1' => array( - 'id' => 1, - 'document_directory_id' => 1, - 'name' => 'Document 1', - 'DocumentDirectory' => array( - 'id' => 1, - 'name' => 'DocumentDirectory 1' - )), - 'Extra2' => array( - 'id' => 1, - 'document_directory_id' => 1, - 'name' => 'Document 1', - 'DocumentDirectory' => array( - 'id' => 1, - 'name' => 'DocumentDirectory 1' - )), - 'DeviceTypeCategory' => array( - 'id' => 1, - 'name' => 'DeviceTypeCategory 1' - ), - 'FeatureSet' => array( - 'id' => 1, - 'name' => 'FeatureSet 1' - ), - 'ExteriorTypeCategory' => array( - 'id' => 1, - 'image_id' => 1, - 'name' => 'ExteriorTypeCategory 1', - 'Image' => array( - 'id' => 1, - 'device_type_id' => 1, - 'name' => 'Device 1', - 'typ' => 1 - )), - 'Device' => array( - array( - 'id' => 1, - 'device_type_id' => 1, - 'name' => 'Device 1', - 'typ' => 1 - ), - array( - 'id' => 2, - 'device_type_id' => 1, - 'name' => 'Device 2', - 'typ' => 1 - ), - array( - 'id' => 3, - 'device_type_id' => 1, - 'name' => 'Device 3', - 'typ' => 2 - ))); - - $this->assertEquals($expected, $result); - } - -/** - * testHabtmRecursiveBelongsTo method - * - * @return void - */ - public function testHabtmRecursiveBelongsTo() { - $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio', 'Syfile', 'Image'); - $Portfolio = new Portfolio(); - - $result = $Portfolio->find('first', array('conditions' => array('id' => 2), 'recursive' => 3)); - $expected = array( - 'Portfolio' => array( - 'id' => 2, - 'seller_id' => 1, - 'name' => 'Portfolio 2' - ), - 'Item' => array( - array( - 'id' => 2, - 'syfile_id' => 2, - 'published' => false, - 'name' => 'Item 2', - 'ItemsPortfolio' => array( - 'id' => 2, - 'item_id' => 2, - 'portfolio_id' => 2 - ), - 'Syfile' => array( - 'id' => 2, - 'image_id' => 2, - 'name' => 'Syfile 2', - 'item_count' => null, - 'Image' => array( - 'id' => 2, - 'name' => 'Image 2' - ) - )), - array( - 'id' => 6, - 'syfile_id' => 6, - 'published' => false, - 'name' => 'Item 6', - 'ItemsPortfolio' => array( - 'id' => 6, - 'item_id' => 6, - 'portfolio_id' => 2 - ), - 'Syfile' => array( - 'id' => 6, - 'image_id' => null, - 'name' => 'Syfile 6', - 'item_count' => null, - 'Image' => array() - )))); - - $this->assertEquals($expected, $result); - } - -/** - * testNonNumericHabtmJoinKey method - * - * @return void - */ - public function testNonNumericHabtmJoinKey() { - $this->loadFixtures('Post', 'Tag', 'PostsTag', 'Author'); - $Post = new Post(); - $Post->bindModel(array( - 'hasAndBelongsToMany' => array('Tag') - )); - $Post->Tag->primaryKey = 'tag'; - - $result = $Post->find('all', array( - 'order' => 'Post.id ASC', - )); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'Author' => array( - 'id' => 1, - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31', - 'test' => 'working' - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ))), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '3', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'Author' => array( - 'id' => 3, - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31', - 'test' => 'working' - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))), - array( - 'Post' => array( - 'id' => '3', - 'author_id' => '1', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'Author' => array( - 'id' => 1, - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31', - 'test' => 'working' - ), - 'Tag' => array() - )); - $this->assertEquals($expected, $result); - } - -/** - * testHabtmFinderQuery method - * - * @return void - */ - public function testHabtmFinderQuery() { - $this->loadFixtures('Article', 'Tag', 'ArticlesTag'); - $Article = new Article(); - - $sql = $this->db->buildStatement( - array( - 'fields' => $this->db->fields($Article->Tag, null, array( - 'Tag.id', 'Tag.tag', 'ArticlesTag.article_id', 'ArticlesTag.tag_id' - )), - 'table' => $this->db->fullTableName('tags'), - 'alias' => 'Tag', - 'limit' => null, - 'offset' => null, - 'group' => null, - 'joins' => array(array( - 'alias' => 'ArticlesTag', - 'table' => 'articles_tags', - 'conditions' => array( - array("ArticlesTag.article_id" => '{$__cakeID__$}'), - array("ArticlesTag.tag_id" => $this->db->identifier('Tag.id')) - ) - )), - 'conditions' => array(), - 'order' => null - ), - $Article - ); - - $Article->hasAndBelongsToMany['Tag']['finderQuery'] = $sql; - $result = $Article->find('first'); - $expected = array( - array( - 'id' => '1', - 'tag' => 'tag1' - ), - array( - 'id' => '2', - 'tag' => 'tag2' - )); - - $this->assertEquals($expected, $result['Tag']); - } - -/** - * testHabtmLimitOptimization method - * - * @return void - */ - public function testHabtmLimitOptimization() { - $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); - $TestModel = new Article(); - - $TestModel->hasAndBelongsToMany['Tag']['limit'] = 2; - $result = $TestModel->read(null, 2); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ), - 'Comment' => array( - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - )), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))); - - $this->assertEquals($expected, $result); - - $TestModel->hasAndBelongsToMany['Tag']['limit'] = 1; - $result = $TestModel->read(null, 2); - unset($expected['Tag'][1]); - - $this->assertEquals($expected, $result); - } - -/** - * testHasManyLimitOptimization method - * - * @return void - */ - public function testHasManyLimitOptimization() { - $this->loadFixtures('Project', 'Thread', 'Message', 'Bid'); - $Project = new Project(); - $Project->recursive = 3; - - $result = $Project->find('all', array( - 'order' => 'Project.id ASC', - )); - $expected = array( - array( - 'Project' => array( - 'id' => 1, - 'name' => 'Project 1' - ), - 'Thread' => array( - array( - 'id' => 1, - 'project_id' => 1, - 'name' => 'Project 1, Thread 1', - 'Project' => array( - 'id' => 1, - 'name' => 'Project 1', - 'Thread' => array( - array( - 'id' => 1, - 'project_id' => 1, - 'name' => 'Project 1, Thread 1' - ), - array( - 'id' => 2, - 'project_id' => 1, - 'name' => 'Project 1, Thread 2' - ))), - 'Message' => array( - array( - 'id' => 1, - 'thread_id' => 1, - 'name' => 'Thread 1, Message 1', - 'Bid' => array( - 'id' => 1, - 'message_id' => 1, - 'name' => 'Bid 1.1' - )))), - array( - 'id' => 2, - 'project_id' => 1, - 'name' => 'Project 1, Thread 2', - 'Project' => array( - 'id' => 1, - 'name' => 'Project 1', - 'Thread' => array( - array( - 'id' => 1, - 'project_id' => 1, - 'name' => 'Project 1, Thread 1' - ), - array( - 'id' => 2, - 'project_id' => 1, - 'name' => 'Project 1, Thread 2' - ))), - 'Message' => array( - array( - 'id' => 2, - 'thread_id' => 2, - 'name' => 'Thread 2, Message 1', - 'Bid' => array( - 'id' => 4, - 'message_id' => 2, - 'name' => 'Bid 2.1' - )))))), - array( - 'Project' => array( - 'id' => 2, - 'name' => 'Project 2' - ), - 'Thread' => array( - array( - 'id' => 3, - 'project_id' => 2, - 'name' => 'Project 2, Thread 1', - 'Project' => array( - 'id' => 2, - 'name' => 'Project 2', - 'Thread' => array( - array( - 'id' => 3, - 'project_id' => 2, - 'name' => 'Project 2, Thread 1' - ))), - 'Message' => array( - array( - 'id' => 3, - 'thread_id' => 3, - 'name' => 'Thread 3, Message 1', - 'Bid' => array( - 'id' => 3, - 'message_id' => 3, - 'name' => 'Bid 3.1' - )))))), - array( - 'Project' => array( - 'id' => 3, - 'name' => 'Project 3' - ), - 'Thread' => array() - )); - - $this->assertEquals($expected, $result); - } - -/** - * testFindAllRecursiveSelfJoin method - * - * @return void - */ - public function testFindAllRecursiveSelfJoin() { - $this->loadFixtures('Home', 'AnotherArticle', 'Advertisement'); - $TestModel = new Home(); - $TestModel->recursive = 2; - - $result = $TestModel->find('all', array( - 'order' => 'Home.id ASC', - )); - $expected = array( - array( - 'Home' => array( - 'id' => '1', - 'another_article_id' => '1', - 'advertisement_id' => '1', - 'title' => 'First Home', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'AnotherArticle' => array( - 'id' => '1', - 'title' => 'First Article', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'Home' => array( - array( - 'id' => '1', - 'another_article_id' => '1', - 'advertisement_id' => '1', - 'title' => 'First Home', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ))), - 'Advertisement' => array( - 'id' => '1', - 'title' => 'First Ad', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'Home' => array( - array( - 'id' => '1', - 'another_article_id' => '1', - 'advertisement_id' => '1', - 'title' => 'First Home', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - array( - 'id' => '2', - 'another_article_id' => '3', - 'advertisement_id' => '1', - 'title' => 'Second Home', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - )))), - array( - 'Home' => array( - 'id' => '2', - 'another_article_id' => '3', - 'advertisement_id' => '1', - 'title' => 'Second Home', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'AnotherArticle' => array( - 'id' => '3', - 'title' => 'Third Article', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'Home' => array( - array( - 'id' => '2', - 'another_article_id' => '3', - 'advertisement_id' => '1', - 'title' => 'Second Home', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ))), - 'Advertisement' => array( - 'id' => '1', - 'title' => 'First Ad', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'Home' => array( - array( - 'id' => '1', - 'another_article_id' => '1', - 'advertisement_id' => '1', - 'title' => 'First Home', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - array( - 'id' => '2', - 'another_article_id' => '3', - 'advertisement_id' => '1', - 'title' => 'Second Home', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ))))); - - $this->assertEquals($expected, $result); - } - -/** - * testFindAllRecursiveWithHabtm method - * - * @return void - */ - public function testFindAllRecursiveWithHabtm() { - $this->loadFixtures( - 'MyCategoriesMyUsers', - 'MyCategoriesMyProducts', - 'MyCategory', - 'MyUser', - 'MyProduct' - ); - - $MyUser = new MyUser(); - $MyUser->recursive = 2; - - $result = $MyUser->find('all', array( - 'order' => 'MyUser.id ASC' - )); - $expected = array( - array( - 'MyUser' => array('id' => '1', 'firstname' => 'userA'), - 'MyCategory' => array( - array( - 'id' => '1', - 'name' => 'A', - 'MyProduct' => array( - array( - 'id' => '1', - 'name' => 'book' - ))), - array( - 'id' => '3', - 'name' => 'C', - 'MyProduct' => array( - array( - 'id' => '2', - 'name' => 'computer' - ))))), - array( - 'MyUser' => array( - 'id' => '2', - 'firstname' => 'userB' - ), - 'MyCategory' => array( - array( - 'id' => '1', - 'name' => 'A', - 'MyProduct' => array( - array( - 'id' => '1', - 'name' => 'book' - ))), - array( - 'id' => '2', - 'name' => 'B', - 'MyProduct' => array( - array( - 'id' => '1', - 'name' => 'book' - ), - array( - 'id' => '2', - 'name' => 'computer' - )))))); - - $this->assertEquals($expected, $result); - } - -/** - * testReadFakeThread method - * - * @return void - */ - public function testReadFakeThread() { - $this->loadFixtures('CategoryThread'); - $TestModel = new CategoryThread(); - - $fullDebug = $this->db->fullDebug; - $this->db->fullDebug = true; - $TestModel->recursive = 6; - $TestModel->id = 7; - $result = $TestModel->read(); - $expected = array( - 'CategoryThread' => array( - 'id' => 7, - 'parent_id' => 6, - 'name' => 'Category 2.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => 6, - 'parent_id' => 5, - 'name' => 'Category 2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 5, - 'parent_id' => 4, - 'name' => 'Category 1.1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 4, - 'parent_id' => 3, - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 3, - 'parent_id' => 2, - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ))))))); - - $this->db->fullDebug = $fullDebug; - $this->assertEquals($expected, $result); - } - -/** - * testFindFakeThread method - * - * @return void - */ - public function testFindFakeThread() { - $this->loadFixtures('CategoryThread'); - $TestModel = new CategoryThread(); - - $fullDebug = $this->db->fullDebug; - $this->db->fullDebug = true; - $TestModel->recursive = 6; - $result = $TestModel->find('first', array('conditions' => array('CategoryThread.id' => 7))); - - $expected = array( - 'CategoryThread' => array( - 'id' => 7, - 'parent_id' => 6, - 'name' => 'Category 2.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => 6, - 'parent_id' => 5, - 'name' => 'Category 2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 5, - 'parent_id' => 4, - 'name' => 'Category 1.1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 4, - 'parent_id' => 3, - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 3, - 'parent_id' => 2, - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ))))))); - - $this->db->fullDebug = $fullDebug; - $this->assertEquals($expected, $result); - } - -/** - * testFindAllFakeThread method - * - * @return void - */ - public function testFindAllFakeThread() { - $this->loadFixtures('CategoryThread'); - $TestModel = new CategoryThread(); - - $fullDebug = $this->db->fullDebug; - $this->db->fullDebug = true; - $TestModel->recursive = 6; - $result = $TestModel->find('all'); - $expected = array( - array( - 'CategoryThread' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => null, - 'parent_id' => null, - 'name' => null, - 'created' => null, - 'updated' => null, - 'ParentCategory' => array() - )), - array( - 'CategoryThread' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array() - )), - array( - 'CategoryThread' => array( - 'id' => 3, - 'parent_id' => 2, - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array() - ))), - array( - 'CategoryThread' => array( - 'id' => 4, - 'parent_id' => 3, - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => 3, - 'parent_id' => 2, - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array() - )))), - array( - 'CategoryThread' => array( - 'id' => 5, - 'parent_id' => 4, - 'name' => 'Category 1.1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => 4, - 'parent_id' => 3, - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 3, - 'parent_id' => 2, - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array() - ))))), - array( - 'CategoryThread' => array( - 'id' => 6, - 'parent_id' => 5, - 'name' => 'Category 2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => 5, - 'parent_id' => 4, - 'name' => 'Category 1.1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 4, - 'parent_id' => 3, - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 3, - 'parent_id' => 2, - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array() - )))))), - array( - 'CategoryThread' => array( - 'id' => 7, - 'parent_id' => 6, - 'name' => 'Category 2.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ), - 'ParentCategory' => array( - 'id' => 6, - 'parent_id' => 5, - 'name' => 'Category 2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 5, - 'parent_id' => 4, - 'name' => 'Category 1.1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 4, - 'parent_id' => 3, - 'name' => 'Category 1.1.2', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 3, - 'parent_id' => 2, - 'name' => 'Category 1.1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 2, - 'parent_id' => 1, - 'name' => 'Category 1.1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31', - 'ParentCategory' => array( - 'id' => 1, - 'parent_id' => 0, - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - )))))))); - - $this->db->fullDebug = $fullDebug; - $this->assertEquals($expected, $result); - } - -/** - * testConditionalNumerics method - * - * @return void - */ - public function testConditionalNumerics() { - $this->loadFixtures('NumericArticle'); - $NumericArticle = new NumericArticle(); - $data = array('conditions' => array('title' => '12345abcde')); - $result = $NumericArticle->find('first', $data); - $this->assertTrue(!empty($result)); - - $data = array('conditions' => array('title' => '12345')); - $result = $NumericArticle->find('first', $data); - $this->assertTrue(empty($result)); - } - -/** - * test buildQuery() - * - * @return void - */ - public function testBuildQuery() { - $this->loadFixtures('User'); - $TestModel = new User(); - $TestModel->cacheQueries = false; - $TestModel->order = null; - $expected = array( - 'conditions' => array( - 'user' => 'larry' - ), - 'fields' => null, - 'joins' => array(), - 'limit' => null, - 'offset' => null, - 'order' => array( - 0 => null - ), - 'page' => 1, - 'group' => null, - 'callbacks' => true, - 'returnQuery' => true - ); - $result = $TestModel->buildQuery('all', array('returnQuery' => true, 'conditions' => array('user' => 'larry'))); - $this->assertEquals($expected, $result); - } - -/** - * test find('all') method - * - * @return void - */ - public function testFindAll() { - $this->loadFixtures('User'); - $TestModel = new User(); - $TestModel->cacheQueries = false; - - $result = $TestModel->find('all'); - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - )), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - )), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - )), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:22:23', - 'updated' => '2007-03-17 01:24:31' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('conditions' => 'User.id > 2')); - $expected = array( - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - )), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:22:23', - 'updated' => '2007-03-17 01:24:31' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array( - 'conditions' => array('User.id !=' => '0', 'User.user LIKE' => '%arr%') - )); - $expected = array( - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - )), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:22:23', - 'updated' => '2007-03-17 01:24:31' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('conditions' => array('User.id' => '0'))); - $expected = array(); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array( - 'conditions' => array('or' => array('User.id' => '0', 'User.user LIKE' => '%a%') - ))); - - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - )), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - )), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - )), - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:22:23', - 'updated' => '2007-03-17 01:24:31' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('fields' => 'User.id, User.user')); - $expected = array( - array('User' => array('id' => '1', 'user' => 'mariano')), - array('User' => array('id' => '2', 'user' => 'nate')), - array('User' => array('id' => '3', 'user' => 'larry')), - array('User' => array('id' => '4', 'user' => 'garrett'))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('fields' => 'User.user', 'order' => 'User.user ASC')); - $expected = array( - array('User' => array('user' => 'garrett')), - array('User' => array('user' => 'larry')), - array('User' => array('user' => 'mariano')), - array('User' => array('user' => 'nate'))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('fields' => 'User.user', 'order' => 'User.user DESC')); - $expected = array( - array('User' => array('user' => 'nate')), - array('User' => array('user' => 'mariano')), - array('User' => array('user' => 'larry')), - array('User' => array('user' => 'garrett'))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('limit' => 3, 'page' => 1)); - - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - )), - array( - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - )), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ))); - $this->assertEquals($expected, $result); - - $ids = array(4 => 1, 5 => 3); - $result = $TestModel->find('all', array( - 'conditions' => array('User.id' => $ids), - 'order' => 'User.id' - )); - $expected = array( - array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - )), - array( - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ))); - $this->assertEquals($expected, $result); - - // These tests are expected to fail on SQL Server since the LIMIT/OFFSET - // hack can't handle small record counts. - if (!($this->db instanceof Sqlserver)) { - $result = $TestModel->find('all', array('limit' => 3, 'page' => 2)); - $expected = array( - array( - 'User' => array( - 'id' => '4', - 'user' => 'garrett', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:22:23', - 'updated' => '2007-03-17 01:24:31' - ))); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array('limit' => 3, 'page' => 3)); - $expected = array(); - $this->assertEquals($expected, $result); - } - } - -/** - * test find('list') method - * - * @return void - */ - public function testGenerateFindList() { - $this->loadFixtures('Article', 'Apple', 'Post', 'Author', 'User', 'Comment'); - - $TestModel = new Article(); - $TestModel->displayField = 'title'; - - $result = $TestModel->find('list', array( - 'order' => 'Article.title ASC' - )); - - $expected = array( - 1 => 'First Article', - 2 => 'Second Article', - 3 => 'Third Article' - ); - $this->assertEquals($expected, $result); - - $db = ConnectionManager::getDataSource('test'); - if ($db instanceof Mysql) { - $result = $TestModel->find('list', array( - 'order' => array('FIELD(Article.id, 3, 2) ASC', 'Article.title ASC') - )); - $expected = array( - 1 => 'First Article', - 3 => 'Third Article', - 2 => 'Second Article' - ); - $this->assertEquals($expected, $result); - } - - $result = Hash::combine( - $TestModel->find('all', array( - 'order' => 'Article.title ASC', - 'fields' => array('id', 'title') - )), - '{n}.Article.id', '{n}.Article.title' - ); - $expected = array( - 1 => 'First Article', - 2 => 'Second Article', - 3 => 'Third Article' - ); - $this->assertEquals($expected, $result); - - $result = Hash::combine( - $TestModel->find('all', array( - 'order' => 'Article.title ASC' - )), - '{n}.Article.id', '{n}.Article' - ); - $expected = array( - 1 => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 2 => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 3 => array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - )); - - $this->assertEquals($expected, $result); - - $result = Hash::combine( - $TestModel->find('all', array( - 'order' => 'Article.title ASC' - )), - '{n}.Article.id', '{n}.Article', '{n}.Article.user_id' - ); - $expected = array( - 1 => array( - 1 => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 3 => array( - 'id' => 3, - 'user_id' => 1, - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - )), - 3 => array( - 2 => array( - 'id' => 2, - 'user_id' => 3, - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ))); - - $this->assertEquals($expected, $result); - - $result = Hash::combine( - $TestModel->find('all', array( - 'order' => 'Article.title ASC', - 'fields' => array('id', 'title', 'user_id') - )), - '{n}.Article.id', '{n}.Article.title', '{n}.Article.user_id' - ); - - $expected = array( - 1 => array( - 1 => 'First Article', - 3 => 'Third Article' - ), - 3 => array( - 2 => 'Second Article' - )); - $this->assertEquals($expected, $result); - - $TestModel = new Apple(); - $expected = array( - 1 => 'Red Apple 1', - 2 => 'Bright Red Apple', - 3 => 'green blue', - 4 => 'Test Name', - 5 => 'Blue Green', - 6 => 'My new apple', - 7 => 'Some odd color' - ); - - $this->assertEquals($expected, $TestModel->find('list')); - $this->assertEquals($expected, $TestModel->Parent->find('list')); - - $TestModel = new Post(); - $result = $TestModel->find('list', array( - 'fields' => 'Post.title' - )); - $expected = array( - 1 => 'First Post', - 2 => 'Second Post', - 3 => 'Third Post' - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('list', array( - 'fields' => 'title' - )); - $expected = array( - 1 => 'First Post', - 2 => 'Second Post', - 3 => 'Third Post' - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('list', array( - 'fields' => array('title', 'id') - )); - $expected = array( - 'First Post' => '1', - 'Second Post' => '2', - 'Third Post' => '3' - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('list', array( - 'fields' => array('title', 'id', 'created') - )); - $expected = array( - '2007-03-18 10:39:23' => array( - 'First Post' => '1' - ), - '2007-03-18 10:41:23' => array( - 'Second Post' => '2' - ), - '2007-03-18 10:43:23' => array( - 'Third Post' => '3' - ), - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('list', array( - 'fields' => array('Post.body') - )); - $expected = array( - 1 => 'First Post Body', - 2 => 'Second Post Body', - 3 => 'Third Post Body' - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('list', array( - 'fields' => array('Post.title', 'Post.body') - )); - $expected = array( - 'First Post' => 'First Post Body', - 'Second Post' => 'Second Post Body', - 'Third Post' => 'Third Post Body' - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('list', array( - 'fields' => array('Post.id', 'Post.title', 'Author.user'), - 'recursive' => 1 - )); - $expected = array( - 'mariano' => array( - 1 => 'First Post', - 3 => 'Third Post' - ), - 'larry' => array( - 2 => 'Second Post' - )); - $this->assertEquals($expected, $result); - - $TestModel = new User(); - $result = $TestModel->find('list', array( - 'fields' => array('User.user', 'User.password') - )); - $expected = array( - 'mariano' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'nate' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'larry' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'garrett' => '5f4dcc3b5aa765d61d8327deb882cf99' - ); - $this->assertEquals($expected, $result); - - $TestModel = new ModifiedAuthor(); - $result = $TestModel->find('list', array( - 'fields' => array('Author.id', 'Author.user') - )); - $expected = array( - 1 => 'mariano (CakePHP)', - 2 => 'nate (CakePHP)', - 3 => 'larry (CakePHP)', - 4 => 'garrett (CakePHP)' - ); - $this->assertEquals($expected, $result); - - $TestModel = new Article(); - $TestModel->displayField = 'title'; - $result = $TestModel->find('list', array( - 'conditions' => array('User.user' => 'mariano'), - 'recursive' => 0 - )); - $expected = array( - 1 => 'First Article', - 3 => 'Third Article' - ); - $this->assertEquals($expected, $result); - } - -/** - * testFindField method - * - * @return void - */ - public function testFindField() { - $this->loadFixtures('User'); - $TestModel = new User(); - - $TestModel->id = 1; - $result = $TestModel->field('user'); - $this->assertEquals('mariano', $result); - - $result = $TestModel->field('User.user'); - $this->assertEquals('mariano', $result); - - $TestModel->id = false; - $result = $TestModel->field('user', array( - 'user' => 'mariano' - )); - $this->assertEquals('mariano', $result); - $TestModel->order = null; - $result = $TestModel->field('COUNT(*) AS count', true); - $this->assertEquals(4, $result); - - $result = $TestModel->field('COUNT(*)', true); - $this->assertEquals(4, $result); - } - -/** - * testFindUnique method - * - * @return void - */ - public function testFindUnique() { - $this->loadFixtures('User'); - $TestModel = new User(); - - $this->assertFalse($TestModel->isUnique(array( - 'user' => 'nate' - ))); - $TestModel->id = 2; - $this->assertTrue($TestModel->isUnique(array( - 'user' => 'nate' - ))); - $this->assertFalse($TestModel->isUnique(array( - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99' - ))); - } - -/** - * test find('count') method - * - * @return void - */ - public function testFindCount() { - $this->loadFixtures('User', 'Article', 'Comment', 'Tag', 'ArticlesTag'); - - $TestModel = new User(); - $this->db->getLog(false, true); - $result = $TestModel->find('count'); - $this->assertEquals(4, $result); - - $this->db->getLog(false, true); - $fullDebug = $this->db->fullDebug; - $this->db->fullDebug = true; - $TestModel->order = 'User.id'; - $result = $TestModel->find('count'); - $this->db->fullDebug = $fullDebug; - $this->assertEquals(4, $result); - - $log = $this->db->getLog(); - $this->assertTrue(isset($log['log'][0]['query'])); - $this->assertNotRegExp('/ORDER\s+BY/', $log['log'][0]['query']); - - $Article = new Article(); - $Article->order = null; - $Article->recursive = -1; - $expected = count($Article->find('all', array( - 'fields' => array('Article.user_id'), - 'group' => 'Article.user_id') - )); - $result = $Article->find('count', array('group' => array('Article.user_id'))); - $this->assertEquals($expected, $result); - - $expected = count($Article->find('all', array( - 'fields' => array('Article.user_id'), - 'conditions' => array('Article.user_id' => 1), - 'group' => 'Article.user_id') - )); - $result = $Article->find('count', array( - 'conditions' => array('Article.user_id' => 1), - 'group' => array('Article.user_id'), - )); - $this->assertEquals($expected, $result); - } - -/** - * Test that find('first') does not use the id set to the object. - * - * @return void - */ - public function testFindFirstNoIdUsed() { - $this->loadFixtures('Project'); - - $Project = new Project(); - $Project->id = 3; - $result = $Project->find('first'); - - $this->assertEquals('Project 1', $result['Project']['name'], 'Wrong record retrieved'); - } - -/** - * test find with COUNT(DISTINCT field) - * - * @return void - */ - public function testFindCountDistinct() { - $this->skipIf($this->db instanceof Sqlite, 'SELECT COUNT(DISTINCT field) is not compatible with SQLite.'); - $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); - - $this->loadFixtures('Project', 'Thread'); - $TestModel = new Project(); - $TestModel->create(array('name' => 'project')) && $TestModel->save(); - $TestModel->create(array('name' => 'project')) && $TestModel->save(); - $TestModel->create(array('name' => 'project')) && $TestModel->save(); - - $result = $TestModel->find('count', array('fields' => 'DISTINCT name')); - $this->assertEquals(4, $result); - } - -/** - * Test find(count) with Db::expression - * - * @return void - */ - public function testFindCountWithDbExpressions() { - $this->skipIf($this->db instanceof Postgres, 'testFindCountWithDbExpressions is not compatible with Postgres.'); - - $this->loadFixtures('Project', 'Thread'); - $db = ConnectionManager::getDataSource('test'); - $TestModel = new Project(); - - $result = $TestModel->find('count', array('conditions' => array( - $db->expression('Project.name = \'Project 3\'') - ))); - $this->assertEquals(1, $result); - - $result = $TestModel->find('count', array('conditions' => array( - 'Project.name' => $db->expression('\'Project 3\'') - ))); - $this->assertEquals(1, $result); - } - -/** - * testFindMagic method - * - * @return void - */ - public function testFindMagic() { - $this->loadFixtures('User'); - $TestModel = new User(); - - $result = $TestModel->findByUser('mariano'); - $expected = array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - )); - $this->assertEquals($expected, $result); - - $result = $TestModel->findByPassword('5f4dcc3b5aa765d61d8327deb882cf99'); - $expected = array('User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - )); - $this->assertEquals($expected, $result); - } - -/** - * testRead method - * - * @return void - */ - public function testRead() { - $this->loadFixtures('User', 'Article'); - $TestModel = new User(); - - $result = $TestModel->read(); - $this->assertFalse($result); - - $TestModel->id = 2; - $result = $TestModel->read(); - $expected = array( - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - )); - $this->assertEquals($expected, $result); - - $result = $TestModel->read(null, 2); - $expected = array( - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - )); - $this->assertEquals($expected, $result); - - $TestModel->id = 2; - $result = $TestModel->read(array('id', 'user')); - $expected = array('User' => array('id' => '2', 'user' => 'nate')); - $this->assertEquals($expected, $result); - - $result = $TestModel->read('id, user', 2); - $expected = array( - 'User' => array( - 'id' => '2', - 'user' => 'nate' - )); - $this->assertEquals($expected, $result); - - $result = $TestModel->bindModel(array('hasMany' => array('Article'))); - $this->assertTrue($result); - - $TestModel->id = 1; - $result = $TestModel->read('id, user'); - $expected = array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano' - ), - 'Article' => array( - array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - array( - 'id' => '3', - 'user_id' => '1', - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ))); - $this->assertEquals($expected, $result); - } - -/** - * testRecursiveRead method - * - * @return void - */ - public function testRecursiveRead() { - $this->loadFixtures( - 'User', - 'Article', - 'Comment', - 'Tag', - 'ArticlesTag', - 'Featured', - 'ArticleFeatured' - ); - $TestModel = new User(); - - $result = $TestModel->bindModel(array('hasMany' => array('Article')), false); - $this->assertTrue($result); - - $TestModel->recursive = 0; - $result = $TestModel->read('id, user', 1); - $expected = array( - 'User' => array('id' => '1', 'user' => 'mariano'), - ); - $this->assertEquals($expected, $result); - - $TestModel->recursive = 1; - $result = $TestModel->read('id, user', 1); - $expected = array( - 'User' => array( - 'id' => '1', - 'user' => 'mariano' - ), - 'Article' => array( - array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - array( - 'id' => '3', - 'user_id' => '1', - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ))); - $this->assertEquals($expected, $result); - - $TestModel->recursive = 2; - $result = $TestModel->read('id, user', 3); - $expected = array( - 'User' => array( - 'id' => '3', - 'user' => 'larry' - ), - 'Article' => array( - array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ), - 'Comment' => array( - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - )), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))))); - $this->assertEquals($expected, $result); - } - - public function testRecursiveFindAll() { - $this->loadFixtures( - 'User', - 'Article', - 'Comment', - 'Tag', - 'ArticlesTag', - 'Attachment', - 'ArticleFeatured', - 'ArticleFeaturedsTags', - 'Featured', - 'Category' - ); - $TestModel = new Article(); - - $result = $TestModel->find('all', array('conditions' => array('Article.user_id' => 1))); - $expected = array( - array( - 'Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - ), - array( - 'id' => '3', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Third Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:49:23', - 'updated' => '2007-03-18 10:51:31' - ), - array( - 'id' => '4', - 'article_id' => '1', - 'user_id' => '1', - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - ) - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ))), - array( - 'Article' => array( - 'id' => '3', - 'user_id' => '1', - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Comment' => array(), - 'Tag' => array() - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->find('all', array( - 'conditions' => array('Article.user_id' => 3), - 'limit' => 1, - 'recursive' => 2 - )); - - $expected = array( - array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ), - 'Comment' => array( - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31', - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Attachment' => array( - 'id' => '1', - 'comment_id' => 5, - 'attachment' => 'attachment.zip', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - ) - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31', - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - ), - 'Attachment' => array() - ) - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - )))); - - $this->assertEquals($expected, $result); - - $Featured = new Featured(); - - $Featured->recursive = 2; - $Featured->bindModel(array( - 'belongsTo' => array( - 'ArticleFeatured' => array( - 'conditions' => "ArticleFeatured.published = 'Y'", - 'fields' => 'id, title, user_id, published' - ) - ) - )); - - $Featured->ArticleFeatured->unbindModel(array( - 'hasMany' => array('Attachment', 'Comment'), - 'hasAndBelongsToMany' => array('Tag')) - ); - - $orderBy = 'ArticleFeatured.id ASC'; - $result = $Featured->find('all', array( - 'order' => $orderBy, 'limit' => 3 - )); - - $expected = array( - array( - 'Featured' => array( - 'id' => '1', - 'article_featured_id' => '1', - 'category_id' => '1', - 'published_date' => '2007-03-31 10:39:23', - 'end_date' => '2007-05-15 10:39:23', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'ArticleFeatured' => array( - 'id' => '1', - 'title' => 'First Article', - 'user_id' => '1', - 'published' => 'Y', - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Category' => array(), - 'Featured' => array( - 'id' => '1', - 'article_featured_id' => '1', - 'category_id' => '1', - 'published_date' => '2007-03-31 10:39:23', - 'end_date' => '2007-05-15 10:39:23', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - 'Category' => array( - 'id' => '1', - 'parent_id' => '0', - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - )), - array( - 'Featured' => array( - 'id' => '2', - 'article_featured_id' => '2', - 'category_id' => '1', - 'published_date' => '2007-03-31 10:39:23', - 'end_date' => '2007-05-15 10:39:23', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'ArticleFeatured' => array( - 'id' => '2', - 'title' => 'Second Article', - 'user_id' => '3', - 'published' => 'Y', - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ), - 'Category' => array(), - 'Featured' => array( - 'id' => '2', - 'article_featured_id' => '2', - 'category_id' => '1', - 'published_date' => '2007-03-31 10:39:23', - 'end_date' => '2007-05-15 10:39:23', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - 'Category' => array( - 'id' => '1', - 'parent_id' => '0', - 'name' => 'Category 1', - 'created' => '2007-03-18 15:30:23', - 'updated' => '2007-03-18 15:32:31' - ))); - $this->assertEquals($expected, $result); - } - -/** - * testRecursiveFindAllWithLimit method - * - * @return void - */ - public function testRecursiveFindAllWithLimit() { - $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag', 'Comment', 'Attachment'); - $TestModel = new Article(); - - $TestModel->hasMany['Comment']['limit'] = 2; - - $result = $TestModel->find('all', array( - 'conditions' => array('Article.user_id' => 1) - )); - $expected = array( - array( - 'Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Comment' => array( - array( - 'id' => '1', - 'article_id' => '1', - 'user_id' => '2', - 'comment' => 'First Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:45:23', - 'updated' => '2007-03-18 10:47:31' - ), - array( - 'id' => '2', - 'article_id' => '1', - 'user_id' => '4', - 'comment' => 'Second Comment for First Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:47:23', - 'updated' => '2007-03-18 10:49:31' - ), - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ))), - array( - 'Article' => array( - 'id' => '3', - 'user_id' => '1', - 'title' => 'Third Article', - 'body' => 'Third Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Comment' => array(), - 'Tag' => array() - ) - ); - $this->assertEquals($expected, $result); - - $TestModel->hasMany['Comment']['limit'] = 1; - - $result = $TestModel->find('all', array( - 'conditions' => array('Article.user_id' => 3), - 'limit' => 1, - 'recursive' => 2 - )); - $expected = array( - array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ), - 'Comment' => array( - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31', - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Attachment' => array( - 'id' => '1', - 'comment_id' => 5, - 'attachment' => 'attachment.zip', - 'created' => '2007-03-18 10:51:23', - 'updated' => '2007-03-18 10:53:31' - ) - ) - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ) - ) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * Testing availability of $this->findQueryType in Model callbacks - * - * @return void - */ - public function testFindQueryTypeInCallbacks() { - $this->loadFixtures('Comment'); - $Comment = new AgainModifiedComment(); - $comments = $Comment->find('all'); - $this->assertEquals('all', $comments[0]['Comment']['querytype']); - $comments = $Comment->find('first'); - $this->assertEquals('first', $comments['Comment']['querytype']); - } - -/** - * testVirtualFields() - * - * Test correct fetching of virtual fields - * currently is not possible to do Relation.virtualField - * - * @return void - */ - public function testVirtualFields() { - $this->loadFixtures('Post', 'Author'); - $Post = ClassRegistry::init('Post'); - $Post->virtualFields = array('two' => "1 + 1"); - $result = $Post->find('first'); - $this->assertEquals(2, $result['Post']['two']); - - // SQL Server does not support operators in expressions - if (!($this->db instanceof Sqlserver)) { - $Post->Author->virtualFields = array('false' => '1 = 2'); - $result = $Post->find('first'); - $this->assertEquals(2, $result['Post']['two']); - $this->assertFalse((bool)$result['Author']['false']); - } - - $result = $Post->find('first', array('fields' => array('author_id'))); - $this->assertFalse(isset($result['Post']['two'])); - $this->assertFalse(isset($result['Author']['false'])); - - $result = $Post->find('first', array('fields' => array('author_id', 'two'))); - $this->assertEquals(2, $result['Post']['two']); - $this->assertFalse(isset($result['Author']['false'])); - - $result = $Post->find('first', array('fields' => array('two'))); - $this->assertEquals(2, $result['Post']['two']); - - $Post->id = 1; - $result = $Post->field('two'); - $this->assertEquals(2, $result); - - $result = $Post->find('first', array( - 'conditions' => array('two' => 2), - 'limit' => 1 - )); - $this->assertEquals(2, $result['Post']['two']); - - $result = $Post->find('first', array( - 'conditions' => array('two <' => 3), - 'limit' => 1 - )); - $this->assertEquals(2, $result['Post']['two']); - - $result = $Post->find('first', array( - 'conditions' => array('NOT' => array('two >' => 3)), - 'limit' => 1 - )); - $this->assertEquals(2, $result['Post']['two']); - - $dbo = $Post->getDataSource(); - $Post->virtualFields = array('other_field' => 'Post.id + 1'); - $result = $Post->find('first', array( - 'conditions' => array('other_field' => 3), - 'limit' => 1 - )); - $this->assertEquals(2, $result['Post']['id']); - $Post->order = null; - - $Post->virtualFields = array('other_field' => 'Post.id + 1'); - $result = $Post->find('all', array( - 'fields' => array($dbo->calculate($Post, 'max', array('other_field'))) - )); - $this->assertEquals(4, $result[0][0]['other_field']); - - ClassRegistry::flush(); - $Writing = ClassRegistry::init(array('class' => 'Post', 'alias' => 'Writing')); - $Writing->virtualFields = array('two' => "1 + 1"); - $result = $Writing->find('first'); - $this->assertEquals(2, $result['Writing']['two']); - - $Post->create(); - $Post->virtualFields = array('other_field' => 'COUNT(Post.id) + 1'); - $result = $Post->field('other_field'); - $this->assertEquals(4, $result); - } - -/** - * testVirtualFieldsOrder() - * - * Test correct order on virtual fields - * - * @return void - */ - public function testVirtualFieldsOrder() { - $this->loadFixtures('Post', 'Author'); - $Post = ClassRegistry::init('Post'); - $Post->virtualFields = array('other_field' => '10 - Post.id'); - $result = $Post->find('list', array('order' => array('Post.other_field' => 'ASC'))); - $expected = array( - '3' => 'Third Post', - '2' => 'Second Post', - '1' => 'First Post' - ); - $this->assertEquals($expected, $result); - - $result = $Post->find('list', array('order' => array('Post.other_field' => 'DESC'))); - $expected = array( - '1' => 'First Post', - '2' => 'Second Post', - '3' => 'Third Post' - ); - $this->assertEquals($expected, $result); - - $Post->Author->virtualFields = array('joined' => 'Post.id * Author.id'); - $result = $Post->find('all', array( - 'order' => array('Post.id' => 'ASC') - )); - $result = Hash::extract($result, '{n}.Author.joined'); - $expected = array(1, 6, 3); - $this->assertEquals($expected, $result); - - $result = $Post->find('all', array('order' => array('Author.joined' => 'ASC'))); - $result = Hash::extract($result, '{n}.Author.joined'); - $expected = array(1, 3, 6); - $this->assertEquals($expected, $result); - - $result = $Post->find('all', array('order' => array('Author.joined' => 'DESC'))); - $result = Hash::extract($result, '{n}.Author.joined'); - $expected = array(6, 3, 1); - $this->assertEquals($expected, $result); - } - -/** - * testVirtualFieldsMysql() - * - * Test correct fetching of virtual fields - * currently is not possible to do Relation.virtualField - * - */ - public function testVirtualFieldsMysql() { - $this->skipIf(!($this->db instanceof Mysql), 'The rest of virtualFields test only compatible with Mysql.'); - - $this->loadFixtures('Post', 'Author'); - $Post = ClassRegistry::init('Post'); - - $Post->create(); - $Post->virtualFields = array( - 'low_title' => 'lower(Post.title)', - 'unique_test_field' => 'COUNT(Post.id)' - ); - - $expectation = array( - 'Post' => array( - 'low_title' => 'first post', - 'unique_test_field' => 1 - ) - ); - - $result = $Post->find('first', array( - 'fields' => array_keys($Post->virtualFields), - 'group' => array('low_title') - )); - - $this->assertEquals($expectation, $result); - - $Author = ClassRegistry::init('Author'); - $Author->virtualFields = array( - 'full_name' => 'CONCAT(Author.user, " ", Author.id)' - ); - - $result = $Author->find('first', array( - 'conditions' => array('Author.user' => 'mariano'), - 'fields' => array('Author.password', 'Author.full_name'), - 'recursive' => -1 - )); - $this->assertTrue(isset($result['Author']['full_name'])); - - $result = $Author->find('first', array( - 'conditions' => array('Author.user' => 'mariano'), - 'fields' => array('Author.full_name', 'Author.password'), - 'recursive' => -1 - )); - $this->assertTrue(isset($result['Author']['full_name'])); - } - -/** - * test that virtual fields work when they don't contain functions. - * - * @return void - */ - public function testVirtualFieldAsAString() { - $this->loadFixtures('Post', 'Author'); - $Post = new Post(); - $Post->virtualFields = array( - 'writer' => 'Author.user' - ); - $result = $Post->find('first'); - $this->assertTrue(isset($result['Post']['writer']), 'virtual field not fetched %s'); - } - -/** - * test that isVirtualField will accept both aliased and non aliased fieldnames - * - * @return void - */ - public function testIsVirtualField() { - $this->loadFixtures('Post'); - $Post = ClassRegistry::init('Post'); - $Post->virtualFields = array('other_field' => 'COUNT(Post.id) + 1'); - - $this->assertTrue($Post->isVirtualField('other_field')); - $this->assertTrue($Post->isVirtualField('Post.other_field')); - $this->assertFalse($Post->isVirtualField('Comment.other_field'), 'Other models should not match.'); - $this->assertFalse($Post->isVirtualField('id')); - $this->assertFalse($Post->isVirtualField('Post.id')); - $this->assertFalse($Post->isVirtualField(array())); - } - -/** - * test that getting virtual fields works with and without model alias attached - * - * @return void - */ - public function testGetVirtualField() { - $this->loadFixtures('Post'); - $Post = ClassRegistry::init('Post'); - $Post->virtualFields = array('other_field' => 'COUNT(Post.id) + 1'); - - $this->assertEquals($Post->getVirtualField('other_field'), $Post->virtualFields['other_field']); - $this->assertEquals($Post->getVirtualField('Post.other_field'), $Post->virtualFields['other_field']); - } - -/** - * test that checks for error when NOT condition passed in key and a 1 element array value - * - * @return void - */ - public function testNotInArrayWithOneValue() { - $this->loadFixtures('Article'); - $Article = new Article(); - $Article->recursive = -1; - - $result = $Article->find( - 'all', - array( - 'conditions' => array( - 'Article.id NOT' => array(1) - ) - ) - ); - $this->assertTrue(is_array($result) && !empty($result)); - } - -/** - * test to assert that != in key together with a single element array will work - * - * @return void - */ - public function testNotEqualsInArrayWithOneValue() { - $this->loadFixtures('Article'); - $Article = new Article(); - $Article->recursive = -1; - - $result = $Article->find( - 'all', - array( - 'conditions' => array( - 'Article.id !=' => array(1) - ) - ) - ); - $this->assertTrue(is_array($result) && !empty($result)); - } - -/** - * test custom find method - * - * @return void - */ - public function testfindCustom() { - $this->loadFixtures('Article'); - $Article = new CustomArticle(); - $data = array('user_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N'); - $Article->create($data); - $Article->save(null, false); - $this->assertEquals(4, $Article->id); - - $result = $Article->find('published'); - $this->assertEquals(3, count($result)); - - $result = $Article->find('unPublished'); - $this->assertEquals(1, count($result)); - } - -/** - * test after find callback on related model - * - * @return void - */ - public function testRelatedAfterFindCallback() { - $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - $Something = new Something(); - - $Something->bindModel(array( - 'hasMany' => array( - 'HasMany' => array( - 'className' => 'JoinThing', - 'foreignKey' => 'something_id' - ) - ), - 'hasOne' => array( - 'HasOne' => array( - 'className' => 'JoinThing', - 'foreignKey' => 'something_id' - ) - ) - )); - - $results = $Something->find('all'); - - $expected = array( - array( - 'Something' => array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - ), - 'HasOne' => array( - 'id' => '1', - 'something_id' => '1', - 'something_else_id' => '2', - 'doomed' => true, - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'HasMany' => array( - array( - 'id' => '1', - 'something_id' => '1', - 'something_else_id' => '2', - 'doomed' => true, - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'afterFind' => 'Successfully added by AfterFind' - ) - ), - 'SomethingElse' => array( - array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'afterFind' => 'Successfully added by AfterFind', - 'JoinThing' => array( - 'doomed' => true, - 'something_id' => '1', - 'something_else_id' => '2', - 'afterFind' => 'Successfully added by AfterFind' - ) - ) - ) - ), - array( - 'Something' => array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'HasOne' => array( - 'id' => '2', - 'something_id' => '2', - 'something_else_id' => '3', - 'doomed' => false, - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'HasMany' => array( - array( - 'id' => '2', - 'something_id' => '2', - 'something_else_id' => '3', - 'doomed' => false, - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'afterFind' => 'Successfully added by AfterFind' - ) - ), - 'SomethingElse' => array( - array( - 'id' => '3', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'afterFind' => 'Successfully added by AfterFind', - 'JoinThing' => array( - 'doomed' => false, - 'something_id' => '2', - 'something_else_id' => '3', - 'afterFind' => 'Successfully added by AfterFind' - ) - ) - ) - ), - array( - 'Something' => array( - 'id' => '3', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ), - 'HasOne' => array( - 'id' => '3', - 'something_id' => '3', - 'something_else_id' => '1', - 'doomed' => true, - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'HasMany' => array( - array( - 'id' => '3', - 'something_id' => '3', - 'something_else_id' => '1', - 'doomed' => true, - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'afterFind' => 'Successfully added by AfterFind' - ) - ), - 'SomethingElse' => array( - array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'afterFind' => 'Successfully added by AfterFind', - 'JoinThing' => array( - 'doomed' => true, - 'something_id' => '3', - 'something_else_id' => '1', - 'afterFind' => 'Successfully added by AfterFind' - ) - ) - ) - ) - ); - $this->assertEquals($expected, $results, 'Model related with has* afterFind callback fails'); - - $JoinThing = new JoinThing(); - $JoinThing->unbindModel(array( - 'belongsTo' => array( - 'Something' - ) - )); - $results = $JoinThing->find('all'); - - $expected = array( - array( - 'JoinThing' => array( - 'id' => '1', - 'something_id' => '1', - 'something_else_id' => '2', - 'doomed' => true, - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'SomethingElse' => array( - 'id' => '2', - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'afterFind' => 'Successfully added by AfterFind' - ) - ), - array( - 'JoinThing' => array( - 'id' => '2', - 'something_id' => '2', - 'something_else_id' => '3', - 'doomed' => false, - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'SomethingElse' => array( - 'id' => '3', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'afterFind' => 'Successfully added by AfterFind' - ) - ), - array( - 'JoinThing' => array( - 'id' => '3', - 'something_id' => '3', - 'something_else_id' => '1', - 'doomed' => true, - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31', - 'afterFind' => 'Successfully added by AfterFind' - ), - 'SomethingElse' => array( - 'id' => '1', - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31', - 'afterFind' => 'Successfully added by AfterFind' - ) - ) - ); - $this->assertEquals($expected, $results, 'Model related with belongsTo afterFind callback fails'); - } -} diff --git a/Cake/Test/TestCase/Model/ModelTest.php b/Cake/Test/TestCase/Model/ModelTest.php deleted file mode 100644 index e8762de0fff..00000000000 --- a/Cake/Test/TestCase/Model/ModelTest.php +++ /dev/null @@ -1,44 +0,0 @@ -addTestFile(CORE_TEST_CASES . DS . 'Model/Validator/ValidationSetTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/Validator/ValidationRuleTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/ModelReadTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/ModelWriteTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/ModelDeleteTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/ModelValidationTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/ModelIntegrationTest.php'); - $suite->addTestFile(CORE_TEST_CASES . DS . 'Model/ModelCrossSchemaHabtmTest.php'); - return $suite; - } -} diff --git a/Cake/Test/TestCase/Model/ModelTestBase.php b/Cake/Test/TestCase/Model/ModelTestBase.php deleted file mode 100644 index 11770cdbf5d..00000000000 --- a/Cake/Test/TestCase/Model/ModelTestBase.php +++ /dev/null @@ -1,98 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Core\App; -use Cake\Model\Model; -use Cake\Model\ModelBehavior; -use Cake\TestSuite\TestCase; - -require_once __DIR__ . DS . 'models.php'; - -/** - * ModelBaseTest - * - */ -abstract class ModelTestBase extends TestCase { - -/** - * autoFixtures property - * - * @var boolean - */ - public $autoFixtures = false; - -/** - * Whether backup global state for each test method or not - * - * @var boolean - */ - public $backupGlobals = false; - -/** - * fixtures property - * - * @var array - */ - public $fixtures = array( - 'core.category', 'core.category_thread', 'core.user', 'core.my_category', 'core.my_product', - 'core.my_user', 'core.my_categories_my_users', 'core.my_categories_my_products', - 'core.article', 'core.featured', 'core.article_featureds_tags', 'core.article_featured', - 'core.numeric_article', 'core.tag', 'core.articles_tag', 'core.comment', - 'core.attachment', 'core.apple', 'core.sample', 'core.another_article', 'core.item', - 'core.advertisement', 'core.home', 'core.post', 'core.author', 'core.bid', 'core.portfolio', - 'core.product', 'core.project', 'core.thread', 'core.message', 'core.items_portfolio', - 'core.syfile', 'core.image', 'core.device_type', 'core.device_type_category', - 'core.feature_set', 'core.exterior_type_category', 'core.document', 'core.device', - 'core.document_directory', 'core.primary_model', 'core.secondary_model', 'core.something', - 'core.something_else', 'core.join_thing', 'core.join_a', 'core.join_b', 'core.join_c', - 'core.join_a_b', 'core.join_a_c', 'core.uuid', 'core.data_test', 'core.posts_tag', - 'core.the_paper_monkies', 'core.person', 'core.underscore_field', 'core.node', - 'core.dependency', 'core.story', 'core.stories_tag', 'core.cd', 'core.book', 'core.basket', - 'core.overall_favorite', 'core.account', 'core.content', 'core.content_account', - 'core.film_file', 'core.test_plugin_article', 'core.test_plugin_comment', 'core.uuiditem', - 'core.counter_cache_user', 'core.counter_cache_post', - 'core.counter_cache_user_nonstandard_primary_key', - 'core.counter_cache_post_nonstandard_primary_key', 'core.uuidportfolio', - 'core.uuiditems_uuidportfolio', 'core.uuiditems_uuidportfolio_numericid', 'core.fruit', - 'core.fruits_uuid_tag', 'core.uuid_tag', 'core.product_update_all', 'core.group_update_all', - 'core.player', 'core.guild', 'core.guilds_player', 'core.armor', 'core.armors_player', - 'core.bidding', 'core.bidding_message', 'core.site', 'core.domain', 'core.domains_site', - ); - -/** - * setUp method - * - * @return void - */ - public function setUp() { - $this->markTestIncomplete('Model layer is not working at this time.'); - parent::setUp(); - $this->debug = Configure::read('debug'); - } - -/** - * tearDown method - * - * @return void - */ - public function tearDown() { - parent::tearDown(); - Configure::write('debug', $this->debug); - ClassRegistry::flush(); - } -} diff --git a/Cake/Test/TestCase/Model/ModelValidationTest.php b/Cake/Test/TestCase/Model/ModelValidationTest.php deleted file mode 100644 index 5af331f47e6..00000000000 --- a/Cake/Test/TestCase/Model/ModelValidationTest.php +++ /dev/null @@ -1,2431 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Model\Datasource\DboSource; -use Cake\Model\Model; -use Cake\Model\ModelBehavior; -use Cake\TestSuite\TestCase; -use Cake\Test\TestCase\Model\ModelTestBase; - -/** - * ModelValidationTest - * - */ -class ModelValidationTest extends ModelTestBase { - -/** - * override locale to the default (eng). - * - * @return void - */ - public function setUp() { - parent::setUp(); - Configure::write('Config.language', 'eng'); - } - -/** - * Tests validation parameter order in custom validation methods - * - * @return void - */ - public function testValidationParams() { - $TestModel = new ValidationTest1(); - $TestModel->validate['title'] = array( - 'rule' => 'customValidatorWithParams', - 'required' => true - ); - $TestModel->create(array('title' => 'foo')); - $TestModel->invalidFields(); - - $expected = array( - 'data' => array( - 'title' => 'foo' - ), - 'validator' => array( - 'rule' => 'customValidatorWithParams', - 'on' => null, - 'last' => true, - 'allowEmpty' => false, - 'required' => true, - 'message' => null - ), - 'or' => true, - 'ignoreOnSame' => 'id' - ); - $this->assertEquals($expected, $TestModel->validatorParams); - - $TestModel->validate['title'] = array( - 'rule' => 'customValidatorWithMessage', - 'required' => true - ); - $expected = array( - 'title' => array('This field will *never* validate! Muhahaha!') - ); - - $this->assertEquals($expected, $TestModel->invalidFields()); - - $TestModel->validate['title'] = array( - 'rule' => array('customValidatorWithSixParams', 'one', 'two', null, 'four'), - 'required' => true - ); - $TestModel->create(array('title' => 'foo')); - $TestModel->invalidFields(); - $expected = array( - 'data' => array( - 'title' => 'foo' - ), - 'one' => 'one', - 'two' => 'two', - 'three' => null, - 'four' => 'four', - 'five' => array( - 'rule' => array(1 => 'one', 2 => 'two', 3 => null, 4 => 'four'), - 'on' => null, - 'last' => true, - 'allowEmpty' => false, - 'required' => true, - 'message' => null - ), - 'six' => 6 - ); - $this->assertEquals($expected, $TestModel->validatorParams); - - $TestModel->validate['title'] = array( - 'rule' => array('customValidatorWithSixParams', 'one', array('two'), null, 'four', array('five' => 5)), - 'required' => true - ); - $TestModel->create(array('title' => 'foo')); - $TestModel->invalidFields(); - $expected = array( - 'data' => array( - 'title' => 'foo' - ), - 'one' => 'one', - 'two' => array('two'), - 'three' => null, - 'four' => 'four', - 'five' => array('five' => 5), - 'six' => array( - 'rule' => array(1 => 'one', 2 => array('two'), 3 => null, 4 => 'four', 5 => array('five' => 5)), - 'on' => null, - 'last' => true, - 'allowEmpty' => false, - 'required' => true, - 'message' => null - ) - ); - $this->assertEquals($expected, $TestModel->validatorParams); - } - -/** - * Tests validation parameter fieldList in invalidFields - * - * @return void - */ - public function testInvalidFieldsWithFieldListParams() { - $TestModel = new ValidationTest1(); - $TestModel->validate = $validate = array( - 'title' => array( - 'rule' => 'alphaNumeric', - 'required' => true - ), - 'name' => array( - 'rule' => 'alphaNumeric', - 'required' => true - )); - $TestModel->set(array('title' => '$$', 'name' => '##')); - $TestModel->invalidFields(array('fieldList' => array('title'))); - $expected = array( - 'title' => array('The provided value is invalid') - ); - $this->assertEquals($expected, $TestModel->validationErrors); - $TestModel->validationErrors = array(); - - $TestModel->invalidFields(array('fieldList' => array('name'))); - $expected = array( - 'name' => array('The provided value is invalid') - ); - $this->assertEquals($expected, $TestModel->validationErrors); - $TestModel->validationErrors = array(); - - $TestModel->invalidFields(array('fieldList' => array('name', 'title'))); - $expected = array( - 'name' => array('The provided value is invalid'), - 'title' => array('The provided value is invalid') - ); - $this->assertEquals($expected, $TestModel->validationErrors); - $TestModel->validationErrors = array(); - - $TestModel->whitelist = array('name'); - $TestModel->invalidFields(); - $expected = array('name' => array('The provided value is invalid')); - $this->assertEquals($expected, $TestModel->validationErrors); - - $this->assertEquals($TestModel->validate, $validate); - } - -/** - * Test that invalidFields() integrates well with save(). And that fieldList can be an empty type. - * - * @return void - */ - public function testInvalidFieldsWhitelist() { - $TestModel = new ValidationTest1(); - $TestModel->validate = array( - 'title' => array( - 'rule' => 'alphaNumeric', - 'required' => true - ), - 'name' => array( - 'rule' => 'alphaNumeric', - 'required' => true - )); - - $TestModel->whitelist = array('name'); - $TestModel->save(array('name' => '#$$#', 'title' => '$$$$')); - - $expected = array('name' => array('The provided value is invalid')); - $this->assertEquals($expected, $TestModel->validationErrors); - } - -/** - * testValidates method - * - * @return void - */ - public function testValidates() { - $TestModel = new TestValidate(); - - $TestModel->validate = array( - 'user_id' => 'numeric', - 'title' => array('allowEmpty' => false, 'rule' => 'notEmpty'), - 'body' => 'notEmpty' - ); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => '', - 'body' => 'body' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 'title', - 'body' => 'body' - )); - $result = $TestModel->create($data) && $TestModel->validates(); - $this->assertTrue($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => '0', - 'body' => 'body' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $TestModel->validate['modified'] = array('allowEmpty' => true, 'rule' => 'date'); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body', - 'modified' => '' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body', - 'modified' => '2007-05-01' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body', - 'modified' => 'invalid-date-here' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body', - 'modified' => 0 - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body', - 'modified' => '0' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $TestModel->validate['modified'] = array('allowEmpty' => false, 'rule' => 'date'); - - $data = array('TestValidate' => array('modified' => null)); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array('modified' => false)); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array('modified' => '')); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'modified' => '2007-05-01' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $TestModel->validate['slug'] = array('allowEmpty' => false, 'rule' => array('maxLength', 45)); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body', - 'slug' => '' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body', - 'slug' => 'slug-right-here' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $data = array('TestValidate' => array( - 'user_id' => '1', - 'title' => 0, - 'body' => 'body', - 'slug' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $TestModel->validate = array( - 'number' => array( - 'rule' => 'validateNumber', - 'min' => 3, - 'max' => 5 - ), - 'title' => array( - 'allowEmpty' => false, - 'rule' => 'notEmpty' - )); - - $data = array('TestValidate' => array( - 'title' => 'title', - 'number' => '0' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'title' => 'title', - 'number' => 0 - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'title' => 'title', - 'number' => '3' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $data = array('TestValidate' => array( - 'title' => 'title', - 'number' => 3 - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $TestModel->validate = array( - 'number' => array( - 'rule' => 'validateNumber', - 'min' => 5, - 'max' => 10 - ), - 'title' => array( - 'allowEmpty' => false, - 'rule' => 'notEmpty' - )); - - $data = array('TestValidate' => array( - 'title' => 'title', - 'number' => '3' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'title' => 'title', - 'number' => 3 - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $TestModel->validate = array( - 'title' => array( - 'allowEmpty' => false, - 'rule' => 'validateTitle' - )); - - $data = array('TestValidate' => array('title' => '')); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array('title' => 'new title')); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array('title' => 'title-new')); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $TestModel->validate = array('title' => array( - 'allowEmpty' => true, - 'rule' => 'validateTitle' - )); - $data = array('TestValidate' => array('title' => '')); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $TestModel->validate = array( - 'title' => array( - 'length' => array( - 'allowEmpty' => true, - 'rule' => array('maxLength', 10) - ))); - $data = array('TestValidate' => array('title' => '')); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $TestModel->validate = array( - 'title' => array( - 'rule' => array('userDefined', 'Article', 'titleDuplicate') - )); - $data = array('TestValidate' => array('title' => 'My Article Title')); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertFalse($result); - - $data = array('TestValidate' => array( - 'title' => 'My Article With a Different Title' - )); - $result = $TestModel->create($data); - $this->assertEquals($data, $result); - $result = $TestModel->validates(); - $this->assertTrue($result); - - $TestModel->validate = array( - 'title' => array( - 'tooShort' => array('rule' => array('minLength', 50)), - 'onlyLetters' => array('rule' => '/^[a-z]+$/i') - ), - ); - $data = array('TestValidate' => array( - 'title' => 'I am a short string' - )); - $TestModel->create($data); - $result = $TestModel->validates(); - $this->assertFalse($result); - $result = $TestModel->validationErrors; - $expected = array( - 'title' => array('tooShort') - ); - $this->assertEquals($expected, $result); - - $TestModel->validate = array( - 'title' => array( - 'tooShort' => array( - 'rule' => array('minLength', 50), - 'last' => false - ), - 'onlyLetters' => array('rule' => '/^[a-z]+$/i') - ), - ); - $data = array('TestValidate' => array( - 'title' => 'I am a short string' - )); - $TestModel->create($data); - $result = $TestModel->validates(); - $this->assertFalse($result); - $result = $TestModel->validationErrors; - $expected = array( - 'title' => array('tooShort', 'onlyLetters') - ); - $this->assertEquals($expected, $result); - $result = $TestModel->validationErrors; - $this->assertEquals($expected, $result); - } - -/** - * test that validates() checks all the 'with' associations as well for validation - * as this can cause partial/wrong data insertion. - * - * @return void - */ - public function testValidatesWithAssociations() { - $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - $data = array( - 'Something' => array( - 'id' => 5, - 'title' => 'Extra Fields', - 'body' => 'Extra Fields Body', - 'published' => '1' - ), - 'SomethingElse' => array( - array('something_else_id' => 1, 'doomed' => '') - ) - ); - - $Something = new Something(); - $JoinThing = $Something->JoinThing; - - $JoinThing->validate = array('doomed' => array('rule' => 'notEmpty')); - - $expectedError = array('doomed' => array('The provided value is invalid')); - - $Something->create(); - $result = $Something->save($data); - $this->assertFalse($result, 'Save occurred even when with models failed. %s'); - $this->assertEquals($expectedError, $JoinThing->validationErrors); - $count = $Something->find('count', array('conditions' => array('Something.id' => $data['Something']['id']))); - $this->assertSame(0, $count); - - $data = array( - 'Something' => array( - 'id' => 5, - 'title' => 'Extra Fields', - 'body' => 'Extra Fields Body', - 'published' => '1' - ), - 'SomethingElse' => array( - array('something_else_id' => 1, 'doomed' => 1), - array('something_else_id' => 1, 'doomed' => '') - ) - ); - $Something->create(); - $result = $Something->save($data); - $this->assertFalse($result, 'Save occurred even when with models failed. %s'); - - $joinRecords = $JoinThing->find('count', array( - 'conditions' => array('JoinThing.something_id' => $data['Something']['id']) - )); - $this->assertEquals(0, $joinRecords, 'Records were saved on the join table. %s'); - } - -/** - * Test that if a behavior modifies the model's whitelist validation gets triggered - * properly for those fields. - * - * @return void - */ - public function testValidateWithFieldListAndBehavior() { - $TestModel = new ValidationTest1(); - $TestModel->validate = array( - 'title' => array( - 'rule' => 'notEmpty', - ), - 'name' => array( - 'rule' => 'notEmpty', - )); - $TestModel->Behaviors->attach('ValidationRule', array('fields' => array('name'))); - - $data = array( - 'title' => '', - 'name' => '', - ); - $result = $TestModel->save($data, array('fieldList' => array('title'))); - $this->assertFalse($result); - - $expected = array('title' => array('This field cannot be left blank'), 'name' => array('This field cannot be left blank')); - $this->assertEquals($expected, $TestModel->validationErrors); - } - -/** - * test that saveAll and with models with validation interact well - * - * @return void - */ - public function testValidatesWithModelsAndSaveAll() { - $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - $data = array( - 'Something' => array( - 'id' => 5, - 'title' => 'Extra Fields', - 'body' => 'Extra Fields Body', - 'published' => '1' - ), - 'SomethingElse' => array( - array('something_else_id' => 1, 'doomed' => '') - ) - ); - $Something = new Something(); - $JoinThing = $Something->JoinThing; - - $JoinThing->validate = array('doomed' => array('rule' => 'notEmpty')); - $expectedError = array('doomed' => array('The provided value is invalid')); - - $Something->create(); - $result = $Something->saveAll($data, array('validate' => 'only')); - $this->assertFalse($result); - $result = $Something->validateAssociated($data); - $this->assertFalse($result); - $this->assertEquals($expectedError, $JoinThing->validationErrors); - $result = $Something->validator()->validateAssociated($data); - $this->assertFalse($result); - - $Something->create(); - $result = $Something->saveAll($data, array('validate' => 'first')); - $this->assertFalse($result); - $this->assertEquals($expectedError, $JoinThing->validationErrors); - - $count = $Something->find('count', array('conditions' => array('Something.id' => $data['Something']['id']))); - $this->assertSame(0, $count); - - $joinRecords = $JoinThing->find('count', array( - 'conditions' => array('JoinThing.something_id' => $data['Something']['id']) - )); - $this->assertEquals(0, $joinRecords, 'Records were saved on the join table. %s'); - } - -/** - * test that saveAll and with models at initial insert (no id has set yet) - * with validation interact well - * - * @return void - */ - public function testValidatesWithModelsAndSaveAllWithoutId() { - $this->loadFixtures('Post', 'Author'); - - $data = array( - 'Author' => array( - 'name' => 'Foo Bar', - ), - 'Post' => array( - array('title' => 'Hello'), - array('title' => 'World'), - ) - ); - $Author = new Author(); - $Post = $Author->Post; - - $Post->validate = array('author_id' => array('rule' => 'numeric')); - - $Author->create(); - $result = $Author->saveAll($data, array('validate' => 'only')); - $this->assertTrue($result); - $result = $Author->validateAssociated($data); - $this->assertTrue($result); - $this->assertTrue($result); - - $Author->create(); - $result = $Author->saveAll($data, array('validate' => 'first')); - $this->assertTrue($result); - $this->assertNotNull($Author->id); - - $id = $Author->id; - $count = $Author->find('count', array('conditions' => array('Author.id' => $id))); - $this->assertSame(1, $count); - - $count = $Post->find('count', array( - 'conditions' => array('Post.author_id' => $id) - )); - $this->assertEquals($count, count($data['Post'])); - } - -/** - * Test that missing validation methods trigger errors in development mode. - * Helps to make development easier. - * - * @expectedException PHPUnit_Framework_Error - * @return void - */ - public function testMissingValidationErrorTriggering() { - Configure::write('debug', 2); - - $TestModel = new ValidationTest1(); - $TestModel->create(array('title' => 'foo')); - $TestModel->validate = array( - 'title' => array( - 'rule' => array('thisOneBringsThePain'), - 'required' => true - ) - ); - $TestModel->invalidFields(array('fieldList' => array('title'))); - } - -/** - * Test placeholder replacement when validation message is an array - * - * @return void - */ - public function testValidationMessageAsArray() { - $TestModel = new ValidationTest1(); - $TestModel->validate = array( - 'title' => array( - 'minLength' => array( - 'rule' => array('minLength', 6), - 'required' => true, - 'message' => 'Minimum length allowed is %d chars', - 'last' => false - ), - 'between' => array( - 'rule' => array('between', 5, 15), - 'message' => array('You may enter up to %s chars (minimum is %s chars)', 14, 6) - ) - ) - ); - - $TestModel->create(); - $expected = array( - 'title' => array( - 'Minimum length allowed is 6 chars', - ) - ); - $TestModel->invalidFields(); - $this->assertEquals($expected, $TestModel->validationErrors); - - $TestModel->create(array('title' => 'foo')); - $expected = array( - 'title' => array( - 'Minimum length allowed is 6 chars', - 'You may enter up to 14 chars (minimum is 6 chars)' - ) - ); - $TestModel->invalidFields(); - $this->assertEquals($expected, $TestModel->validationErrors); - } - -/** - * Test validation message translation - * - * @return void - */ - public function testValidationMessageTranslation() { - $lang = Configure::read('Config.language'); - Configure::write('Config.language', 'en'); - - $TestModel = new ValidationTest1(); - $TestModel->validationDomain = 'validation_messages'; - $TestModel->validate = array( - 'title' => array( - array( - 'rule' => array('customValidationMethod', 'arg1'), - 'required' => true, - 'message' => 'Validation failed: %s' - ) - ) - ); - - $TestModel->create(); - $expected = array( - 'title' => array( - 'Translated validation failed: Translated arg1', - ) - ); - $TestModel->invalidFields(); - $this->assertEquals($expected, $TestModel->validationErrors); - - $TestModel->validationDomain = 'default'; - Configure::write('Config.language', $lang); - } - -/** - * Test for 'on' => [create|update] in validation rules. - * - * @return void - */ - public function testStateValidation() { - $this->loadFixtures('Article'); - $Article = new Article(); - - $data = array( - 'Article' => array( - 'title' => '', - 'body' => 'Extra Fields Body', - 'published' => '1' - ) - ); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'on' => 'create' - ) - ) - ); - - $Article->create($data); - $this->assertFalse($Article->validates()); - - $Article->save(null, array('validate' => false)); - $data['Article']['id'] = $Article->id; - $Article->set($data); - $this->assertTrue($Article->validates()); - - unset($data['Article']['id']); - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'on' => 'update' - ) - ) - ); - - $Article->create($data); - $this->assertTrue($Article->validates()); - - $Article->save(null, array('validate' => false)); - $data['Article']['id'] = $Article->id; - $Article->set($data); - $this->assertFalse($Article->validates()); - } - -/** - * Test for 'required' => [create|update] in validation rules. - * - * @return void - */ - public function testStateRequiredValidation() { - $this->loadFixtures('Article'); - $Article = new Article(); - - // no title field present - $data = array( - 'Article' => array( - 'body' => 'Extra Fields Body', - 'published' => '1' - ) - ); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'create' - ) - ) - ); - - $Article->create($data); - $this->assertFalse($Article->validates()); - - $Article->save(null, array('validate' => false)); - $data['Article']['id'] = $Article->id; - $Article->set($data); - $this->assertTrue($Article->validates()); - - unset($data['Article']['id']); - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'update' - ) - ) - ); - - $Article->create($data); - $this->assertTrue($Article->validates()); - - $Article->save(null, array('validate' => false)); - $data['Article']['id'] = $Article->id; - $Article->set($data); - $this->assertFalse($Article->validates()); - } - -/** - * Test that 'required' and 'on' are not conflicting - * - * @return void - */ - public function testOnRequiredConflictValidation() { - $this->loadFixtures('Article'); - $Article = new Article(); - - // no title field present - $data = array( - 'Article' => array( - 'body' => 'Extra Fields Body', - 'published' => '1' - ) - ); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'create', - 'on' => 'create' - ) - ) - ); - - $Article->create($data); - $this->assertFalse($Article->validates()); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'update', - 'on' => 'create' - ) - ) - ); - - $Article->create($data); - $this->assertTrue($Article->validates()); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'create', - 'on' => 'update' - ) - ) - ); - - $Article->create($data); - $this->assertTrue($Article->validates()); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'update', - 'on' => 'update' - ) - ) - ); - - $Article->create($data); - $this->assertTrue($Article->validates()); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'create', - 'on' => 'create' - ) - ) - ); - - $Article->save(null, array('validate' => false)); - $data['Article']['id'] = $Article->id; - $Article->set($data); - $this->assertTrue($Article->validates()); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'update', - 'on' => 'create' - ) - ) - ); - - $Article->set($data); - $this->assertTrue($Article->validates()); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'create', - 'on' => 'update' - ) - ) - ); - - $Article->set($data); - $this->assertTrue($Article->validates()); - - $Article->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => 'update', - 'on' => 'update' - ) - ) - ); - - $Article->set($data); - $this->assertFalse($Article->validates()); - } - -/** - * testSaveAllDeepValidateOnly - * tests the validate methods with deeper recursive data - * - * @return void - */ - public function testSaveAllDeepValidateOnly() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->Attachment->validate['attachment'] = 'notEmpty'; - $TestModel->Comment->validate['comment'] = 'notEmpty'; - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertTrue($result); - $result = $TestModel->validateAssociated($data, array('deep' => true)); - $this->assertTrue($result); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - $result = $TestModel->validateAssociated($data, array('deep' => true)); - $this->assertFalse($result); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - true - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - false, - true - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsaved')) - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertTrue($result); - $result = $TestModel->validateAssociated($data, array('deep' => true)); - $this->assertTrue($result); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - $result = $TestModel->validateAssociated($data, array('deep' => true)); - $this->assertFalse($result); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsave')) - ) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - true - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) - ) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - false - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - - $expected = array( - 'Comment' => array( - 1 => array( - 'Attachment' => array( - 'attachment' => array('The provided value is invalid') - ) - ) - ) - ); - $result = $TestModel->validationErrors; - $this->assertSame($expected, $result); - - $data = array( - 'Attachment' => array( - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - 'user_id' => 5, - 'Article' => array( - 'title' => 'First Article deepsave insert', - 'body' => 'First Article Body deepsave insert', - 'User' => array( - 'user' => 'deepsave', - 'password' => 'magic' - ), - ), - ) - ); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertTrue($result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); - $this->assertTrue($result); - - $expected = array( - 'Attachment' => true, - 'Comment' => true - ); - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertSame($expected, $result); - - $data = array( - 'Attachment' => array( - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - 'user_id' => 5, - 'Article' => array( - 'title' => 'First Article deepsave insert', - 'body' => 'First Article Body deepsave insert', - 'User' => array( - 'user' => '', - 'password' => 'magic' - ), - ), - ) - ); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); - $this->assertFalse($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array( - 'Comment' => array( - 'Article' => array( - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ); - $this->assertSame($expected, $result); - - $expected = array( - 'Attachment' => true, - 'Comment' => false - ); - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertEquals($expected, $result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertEquals($expected, $result); - - $data['Comment']['Article']['body'] = ''; - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); - $this->assertFalse($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array( - 'Comment' => array( - 'Article' => array( - 'body' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ); - $this->assertSame($expected, $result); - - $expected = array( - 'Attachment' => true, - 'Comment' => false - ); - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertEquals($expected, $result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertEquals($expected, $result); - - $data['Comment']['comment'] = ''; - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); - $this->assertFalse($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array( - 'Comment' => array( - 'comment' => array('The provided value is invalid'), - 'Article' => array( - 'body' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ); - $this->assertSame($expected, $result); - - $expected = array( - 'Attachment' => true, - 'Comment' => false - ); - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertEquals($expected, $result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertEquals($expected, $result); - - $data['Attachment']['attachment'] = ''; - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => true)); - $this->assertFalse($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array( - 'attachment' => array('The provided value is invalid'), - 'Comment' => array( - 'comment' => array('The provided value is invalid'), - 'Article' => array( - 'body' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->Comment->validationErrors; - $expected = array( - 'comment' => array('The provided value is invalid'), - 'Article' => array( - 'body' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ); - $this->assertSame($expected, $result); - - $expected = array( - 'Attachment' => false, - 'Comment' => false - ); - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $this->assertEquals($expected, $result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllNotDeepValidateOnly - * tests the validate methods to not validate deeper recursive data - * - * @return void - */ - public function testSaveAllNotDeepValidateOnly() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->Attachment->validate['attachment'] = 'notEmpty'; - $TestModel->Comment->validate['comment'] = 'notEmpty'; - - $data = array( - 'Article' => array('id' => 2, 'body' => ''), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => false)); - $this->assertFalse($result); - $result = $TestModel->validateAssociated($data, array('deep' => false)); - $this->assertFalse($result); - - $expected = array('body' => array('The provided value is invalid')); - $result = $TestModel->validationErrors; - $this->assertSame($expected, $result); - - $data = array( - 'Article' => array('id' => 2, 'body' => 'Ignore invalid user data'), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => false)); - $this->assertTrue($result); - $result = $TestModel->validateAssociated($data, array('deep' => false)); - $this->assertTrue($result); - - $data = array( - 'Article' => array('id' => 2, 'body' => 'Ignore invalid user data'), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - true - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); - $this->assertSame($expected, $result); - $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => false)); - $this->assertSame($expected, $result); - - $data = array( - 'Article' => array('id' => 2, 'body' => 'Ignore invalid attachment data'), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'deep' => false)); - $this->assertTrue($result); - $result = $TestModel->validateAssociated($data, array('deep' => false)); - $this->assertTrue($result); - - $data = array( - 'Article' => array('id' => 2, 'body' => 'Ignore invalid attachment data'), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) - ) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - true - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); - $this->assertSame($expected, $result); - $result = $TestModel->validateAssociated($data, array('atomic' => false, 'deep' => false)); - $this->assertSame($expected, $result); - - $expected = array(); - $result = $TestModel->validationErrors; - $this->assertSame($expected, $result); - - $data = array( - 'Attachment' => array( - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - 'user_id' => 5, - 'Article' => array( - 'title' => 'First Article deepsave insert ignored', - 'body' => 'First Article Body deepsave insert', - 'User' => array( - 'user' => '', - 'password' => 'magic' - ), - ), - ) - ); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => false)); - $this->assertTrue($result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => false)); - $this->assertTrue($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array(); - $this->assertSame($expected, $result); - - $expected = array( - 'Attachment' => true, - 'Comment' => true - ); - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); - $this->assertEquals($expected, $result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => false)); - $this->assertEquals($expected, $result); - - $data['Comment']['Article']['body'] = ''; - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => false)); - $this->assertTrue($result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('deep' => false)); - $this->assertTrue($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array(); - $this->assertSame($expected, $result); - - $expected = array( - 'Attachment' => true, - 'Comment' => true - ); - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); - $this->assertEquals($expected, $result); - $result = $TestModel->Comment->Attachment->validateAssociated($data, array('atomic' => false, 'deep' => false)); - $this->assertEquals($expected, $result); - } - -/** - * testValidateAssociated method - * - * @return void - */ - public function testValidateAssociated() { - $this->loadFixtures('Comment', 'Attachment', 'Article', 'User'); - $TestModel = new Comment(); - $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); - - $data = array( - 'Comment' => array( - 'comment' => 'This is the comment' - ), - 'Attachment' => array( - 'attachment' => '' - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'only')); - $this->assertFalse($result); - $result = $TestModel->validateAssociated($data); - $this->assertFalse($result); - - $fieldList = array( - 'Attachment' => array('comment_id') - ); - $result = $TestModel->saveAll($data, array( - 'fieldList' => $fieldList, 'validate' => 'only' - )); - $this->assertTrue($result); - $this->assertEmpty($TestModel->validationErrors); - $result = $TestModel->validateAssociated($data, array('fieldList' => $fieldList)); - $this->assertTrue($result); - $this->assertEmpty($TestModel->validationErrors); - - $TestModel->validate = array('comment' => 'notEmpty'); - $record = array( - 'Comment' => array( - 'user_id' => 1, - 'article_id' => 1, - 'comment' => '', - ), - 'Attachment' => array( - 'attachment' => '' - ) - ); - $result = $TestModel->saveAll($record, array('validate' => 'only')); - $this->assertFalse($result); - $result = $TestModel->validateAssociated($record); - $this->assertFalse($result); - - $fieldList = array( - 'Comment' => array('id', 'article_id', 'user_id'), - 'Attachment' => array('comment_id') - ); - $result = $TestModel->saveAll($record, array( - 'fieldList' => $fieldList, 'validate' => 'only' - )); - $this->assertTrue($result); - $this->assertEmpty($TestModel->validationErrors); - $result = $TestModel->validateAssociated($record, array('fieldList' => $fieldList)); - $this->assertTrue($result); - $this->assertEmpty($TestModel->validationErrors); - - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->validate = array('comment' => 'notEmpty'); - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'id' => 1, - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1, - ), - array( - 'id' => 2, - 'comment' => - 'comment', - 'published' => 'Y', - 'user_id' => 1 - ), - array( - 'id' => 3, - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1 - ))); - $result = $TestModel->saveAll($data, array('validate' => 'only')); - $this->assertFalse($result); - $result = $TestModel->validateAssociated($data); - $this->assertFalse($result); - - $expected = array( - 'Article' => true, - 'Comment' => array(false, true, false) - ); - $result = $TestModel->saveAll($data, array('atomic' => false, 'validate' => 'only')); - $this->assertSame($expected, $result); - $result = $TestModel->validateAssociated($data, array('atomic' => false)); - $this->assertSame($expected, $result); - - $expected = array('Comment' => array( - 0 => array('comment' => array('The provided value is invalid')), - 2 => array('comment' => array('The provided value is invalid')) - )); - $this->assertEquals($expected['Comment'], $TestModel->Comment->validationErrors); - - $model = new Comment(); - $model->deleteAll(true); - $model->validate = array('comment' => 'notEmpty'); - $model->Attachment->validate = array('attachment' => 'notEmpty'); - $model->Attachment->bindModel(array('belongsTo' => array('Comment'))); - $expected = array( - 'comment' => array('The provided value is invalid'), - 'Attachment' => array( - 'attachment' => array('The provided value is invalid') - ) - ); - - $data = array( - 'Comment' => array('comment' => '', 'article_id' => 1, 'user_id' => 1), - 'Attachment' => array('attachment' => '') - ); - $result = $model->saveAll($data, array('validate' => 'only')); - $this->assertFalse($result); - $result = $model->validateAssociated($data); - $this->assertFalse($result); - $this->assertEquals($expected, $model->validationErrors); - $this->assertEquals($expected['Attachment'], $model->Attachment->validationErrors); - } - -/** - * testValidateMany method - * - * @return void - */ - public function testValidateMany() { - $TestModel = new Article(); - $TestModel->validate = array('title' => 'notEmpty'); - $data = array( - 0 => array('title' => ''), - 1 => array('title' => 'title 1'), - 2 => array('title' => 'title 2'), - ); - $expected = array( - 0 => array('title' => array('The provided value is invalid')), - ); - - $result = $TestModel->saveAll($data, array('validate' => 'only')); - $this->assertFalse($result); - $this->assertEquals($expected, $TestModel->validationErrors); - $result = $TestModel->validateMany($data); - $this->assertFalse($result); - $this->assertEquals($expected, $TestModel->validationErrors); - - $data = array( - 0 => array('title' => 'title 0'), - 1 => array('title' => ''), - 2 => array('title' => 'title 2'), - ); - $expected = array( - 1 => array('title' => array('The provided value is invalid')), - ); - $result = $TestModel->saveAll($data, array('validate' => 'only')); - $this->assertFalse($result); - $this->assertEquals($expected, $TestModel->validationErrors); - $result = $TestModel->validateMany($data); - $this->assertFalse($result); - $this->assertEquals($expected, $TestModel->validationErrors); - } - -/** - * testGetMethods method - * - * @return void - */ - public function testGetMethods() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $result = $Validator->getMethods(); - - $expected = array_map('strtolower', get_class_methods('Article')); - $this->assertEquals($expected, array_keys($result)); - } - -/** - * Tests that methods are refreshed when the list of behaviors change - * - * @return void - */ - public function testGetMethodsRefresh() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $result = $Validator->getMethods(); - - $expected = array_map('strtolower', get_class_methods('Article')); - $this->assertEquals($expected, array_keys($result)); - - $TestModel->Behaviors->load('Tree'); - $newList = array( - 'childcount', - 'children', - 'generatetreelist', - 'getparentnode', - 'getpath', - 'movedown', - 'moveup', - 'recover', - 'reorder', - 'removefromtree', - 'verify', - ); - $this->assertEquals(array_merge($expected, $newList), array_keys($Validator->getMethods())); - - $TestModel->Behaviors->unload('Tree'); - $this->assertEquals($expected, array_keys($Validator->getMethods())); - } - -/** - * testSetValidationDomain method - * - * @return void - */ - public function testSetValidationDomain() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $result = $Validator->setValidationDomain('default'); - $this->assertEquals('default', $TestModel->validationDomain); - - $result = $Validator->setValidationDomain('other'); - $this->assertEquals('other', $TestModel->validationDomain); - } - -/** - * testGetModel method - * - * @return void - */ - public function testGetModel() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $result = $Validator->getModel(); - $this->assertInstanceOf('Article', $result); - } - -/** - * Tests it is possible to get validation sets for a field using an array inteface - * - * @return void - */ - public function testArrayAccessGet() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $titleValidator = $Validator['title']; - $this->assertEquals('title', $titleValidator->field); - $this->assertCount(1, $titleValidator->getRules()); - $rule = current($titleValidator->getRules()); - $this->assertEquals('notEmpty', $rule->rule); - - $titleValidator = $Validator['body']; - $this->assertEquals('body', $titleValidator->field); - $this->assertCount(1, $titleValidator->getRules()); - $rule = current($titleValidator->getRules()); - $this->assertEquals('notEmpty', $rule->rule); - - $titleValidator = $Validator['user_id']; - $this->assertEquals('user_id', $titleValidator->field); - $this->assertCount(1, $titleValidator->getRules()); - $rule = current($titleValidator->getRules()); - $this->assertEquals('numeric', $rule->rule); - } - -/** - * Tests it is possible to check for validation sets for a field using an array inteface - * - * @return void - */ - public function testArrayAccessExists() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $this->assertTrue(isset($Validator['title'])); - $this->assertTrue(isset($Validator['body'])); - $this->assertTrue(isset($Validator['user_id'])); - $this->assertFalse(isset($Validator['other'])); - } - -/** - * Tests it is possible to set validation rules for a field using an array inteface - * - * @return void - */ - public function testArrayAccessSet() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $set = array( - 'numeric' => array('rule' => 'numeric', 'allowEmpty' => false), - 'range' => array('rule' => array('between', 1, 5), 'allowEmpty' => false), - ); - $Validator['other'] = $set; - $rules = $Validator['other']; - $this->assertEquals('other', $rules->field); - - $validators = $rules->getRules(); - $this->assertCount(2, $validators); - $this->assertEquals('numeric', $validators['numeric']->rule); - $this->assertEquals(array('between', 1, 5), $validators['range']->rule); - - $Validator['new'] = new CakeValidationSet('new', $set, array()); - $rules = $Validator['new']; - $this->assertEquals('new', $rules->field); - - $validators = $rules->getRules(); - $this->assertCount(2, $validators); - $this->assertEquals('numeric', $validators['numeric']->rule); - $this->assertEquals(array('between', 1, 5), $validators['range']->rule); - } - -/** - * Tests it is possible to unset validation rules - * - * @return void - */ - public function testArrayAccessUset() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $this->assertTrue(isset($Validator['title'])); - unset($Validator['title']); - $this->assertFalse(isset($Validator['title'])); - } - -/** - * Tests it is possible to iterate a validation object - * - * @return void - */ - public function testIterator() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $i = 0; - foreach ($Validator as $field => $rules) { - if ($i === 0) { - $this->assertEquals('user_id', $field); - } - if ($i === 1) { - $this->assertEquals('title', $field); - } - if ($i === 2) { - $this->assertEquals('body', $field); - } - $this->assertInstanceOf('CakeValidationSet', $rules); - $i++; - } - $this->assertEquals(3, $i); - } - -/** - * Tests countable interface in ModelValidator - * - * @return void - */ - public function testCount() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - $this->assertCount(3, $Validator); - - $set = array( - 'numeric' => array('rule' => 'numeric', 'allowEmpty' => false), - 'range' => array('rule' => array('between', 1, 5), 'allowEmpty' => false), - ); - $Validator['other'] = $set; - $this->assertCount(4, $Validator); - - unset($Validator['title']); - $this->assertCount(3, $Validator); - unset($Validator['body']); - $this->assertCount(2, $Validator); - } - -/** - * Tests it is possible to add validation rules - * - * @return void - */ - public function testAddRule() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $Validator->add('other', 'numeric', array('rule' => 'numeric', 'allowEmpty' => false)); - $Validator->add('other', 'range', array('rule' => array('between', 1, 5), 'allowEmpty' => false)); - $rules = $Validator['other']; - $this->assertEquals('other', $rules->field); - - $validators = $rules->getRules(); - $this->assertCount(2, $validators); - $this->assertEquals('numeric', $validators['numeric']->rule); - $this->assertEquals(array('between', 1, 5), $validators['range']->rule); - } - -/** - * Tests it is possible to remove validation rules - * - * @return void - */ - public function testRemoveRule() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $this->assertTrue(isset($Validator['title'])); - $Validator->remove('title'); - $this->assertFalse(isset($Validator['title'])); - - $Validator->add('other', 'numeric', array('rule' => 'numeric', 'allowEmpty' => false)); - $Validator->add('other', 'range', array('rule' => array('between', 1, 5), 'allowEmpty' => false)); - $this->assertTrue(isset($Validator['other'])); - - $Validator->remove('other', 'numeric'); - $this->assertTrue(isset($Validator['other'])); - $this->assertFalse(isset($Validator['other']['numeric'])); - $this->assertTrue(isset($Validator['other']['range'])); - } - -/** - * Tests validation callbacks are triggered - * - * @return void - */ - public function testValidateCallbacks() { - $TestModel = $this->getMock('Article', array('beforeValidate', 'afterValidate')); - $TestModel->expects($this->once())->method('beforeValidate'); - $TestModel->expects($this->once())->method('afterValidate'); - - $TestModel->set(array('title' => '', 'body' => 'body')); - $TestModel->validates(); - } - -/** - * Tests that altering data in a beforeValidate callback will lead to saving those - * values in database - * - * @return void - */ - public function testValidateFirstWithBeforeValidate() { - $this->loadFixtures('Article', 'User'); - $model = new CustomArticle(); - $model->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => true, - 'allowEmpty' => false - ) - ) - ); - $data = array( - 'CustomArticle' => array( - 'body' => 'foo0' - ) - ); - $result = $model->saveAll($data, array('validate' => 'first')); - $this->assertTrue($result); - - $this->assertFalse($model->findMethods['unPublished'], 'beforeValidate was run twice'); - - $model->findMethods['unPublished'] = true; - $data = array( - 'CustomArticle' => array( - 'body' => 'foo1' - ) - ); - $result = $model->saveAll($data, array('validate' => 'first', 'deep' => true)); - $this->assertTrue($result); - $title = $model->field('title', array('body' => 'foo1')); - $this->assertEquals('foo', $title); - $this->assertFalse($model->findMethods['unPublished'], 'beforeValidate was run twice'); - - $data = array( - array('body' => 'foo2'), - array('body' => 'foo3'), - array('body' => 'foo4') - ); - - $result = $model->saveAll($data, array('validate' => 'first', 'deep' => true)); - $this->assertTrue($result); - - $this->assertEquals('foo', $model->field('title', array('body' => 'foo2'))); - $this->assertEquals('foo', $model->field('title', array('body' => 'foo3'))); - $this->assertEquals('foo', $model->field('title', array('body' => 'foo4'))); - } - -/** - * Tests that altering data in a beforeValidate callback will lead to saving those - * values in database - * - * @return void - */ - public function testValidateFirstAssociatedWithBeforeValidate() { - $this->loadFixtures('Article', 'User'); - $model = new CustomArticle(); - $model->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => true - ) - ) - ); - $articles = array( - array('body' => 'foo1'), - array('body' => 'foo2'), - array('body' => 'foo3') - ); - $user = new User(); - $user->bindModel(array('hasMany' => array('CustomArticle'))); - $data = array( - 'User' => array('user' => 'foo', 'password' => 'bar'), - 'CustomArticle' => $articles - ); - $result = $user->saveAll($data, array('validate' => 'first')); - $this->assertTrue($result); - - $this->assertEquals('foo', $model->field('title', array('body' => 'foo1'))); - $this->assertEquals('foo', $model->field('title', array('body' => 'foo2'))); - $this->assertEquals('foo', $model->field('title', array('body' => 'foo3'))); - } - -/** - * testValidateFirstWithDefaults method - * - * return @void - */ - public function testFirstWithDefaults() { - $this->loadFixtures('Article', 'Tag', 'Comment', 'User', 'ArticlesTag'); - $TestModel = new Article(); - - $result = $TestModel->find('first', array( - 'conditions' => array('Article.id' => 1) - )); - $expected = array( - 'Article' => array( - 'id' => 1, - 'user_id' => 1, - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23' - ), - ); - unset($result['Article']['updated']); - $this->assertEquals($expected['Article'], $result['Article']); - - $data = array( - 'Article' => array( - 'id' => 1, - 'title' => 'First Article (modified)' - ), - 'Comment' => array( - array('comment' => 'Article comment', 'user_id' => 1) - ) - ); - $result = $TestModel->saveAll($data, array('validate' => 'first')); - $this->assertTrue($result); - - $result = $TestModel->find('first', array( - 'conditions' => array('Article.id' => 1) - )); - $expected['Article']['title'] = 'First Article (modified)'; - unset($result['Article']['updated']); - $this->assertEquals($expected['Article'], $result['Article']); - } - - public function testAddMultipleRules() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $set = array( - 'numeric' => array('rule' => 'numeric', 'allowEmpty' => false), - 'range' => array('rule' => array('between', 1, 5), 'allowEmpty' => false), - ); - - $Validator->add('other', $set); - $rules = $Validator['other']; - $this->assertEquals('other', $rules->field); - - $validators = $rules->getRules(); - $this->assertCount(2, $validators); - $this->assertEquals('numeric', $validators['numeric']->rule); - $this->assertEquals(array('between', 1, 5), $validators['range']->rule); - - $set = new CakeValidationSet('other', array( - 'a' => array('rule' => 'numeric', 'allowEmpty' => false), - 'b' => array('rule' => array('between', 1, 5), 'allowEmpty' => false), - )); - - $Validator->add('other', $set); - $this->assertSame($set, $Validator->getField('other')); - } - -/** - * Test that rules are parsed correctly when calling getField() - * - * @return void - */ - public function testValidator() { - $TestModel = new Article(); - $Validator = $TestModel->validator(); - - $result = $Validator->getField(); - $expected = array('user_id', 'title', 'body'); - $this->assertEquals($expected, array_keys($result)); - $this->assertTrue($result['user_id'] instanceof CakeValidationSet); - - $result = $TestModel->validator()->getField('title'); - $this->assertTrue($result instanceof CakeValidationSet); - } - -/** - * Test that validator override works as expected - * - * @return void - */ - public function testValidatorOverride() { - $TestModel = new Article(); - $ValidatorA = new ModelValidator($TestModel); - $ValidatorB = new ModelValidator($TestModel); - - $TestModel->validator($ValidatorA); - $TestModel->validator($ValidatorB); - - $this->assertSame($ValidatorB, $TestModel->validator()); - $this->assertNotSame($ValidatorA, $TestModel->validator()); - } - -/** - * Test that type hint exception is thrown - * - * @expectedException PHPUnit_Framework_Error - * @return void - */ - public function testValidatorTypehintException() { - new ModelValidator('asdasds'); - } - -/** - * Tests that altering data in a beforeValidate callback will lead to saving those - * values in database, this time with belongsTo associations - * - * @return void - */ - public function testValidateFirstAssociatedWithBeforeValidate2() { - $this->loadFixtures('Article', 'User'); - $model = new CustomArticle(); - $model->validate = array( - 'title' => array( - 'notempty' => array( - 'rule' => 'notEmpty', - 'required' => true - ) - ) - ); - - $data = array( - 'User' => array('user' => 'foo', 'password' => 'bar'), - 'CustomArticle' => array( - 'body' => 'a test' - ) - ); - $result = $model->saveAll($data, array('validate' => 'first')); - $this->assertTrue($result); - - $this->assertEquals('foo', $model->field('title', array('body' => 'a test'))); - } - -/** - * Testing you can dynamically add rules to a field, added this to dispel doubts - * after a presentation made to show off this new feature - * - * @return void - */ - public function testDynamicValidationRuleBuilding() { - $model = new Article; - $validator = $model->validator(); - $validator->add('body', 'isSpecial', array('rule' => 'special')); - $rules = $validator['body']->getRules(); - $this->assertCount(2, $rules); - $this->assertEquals('special', $rules['isSpecial']->rule); - $validator['body']->setRule('isAwesome', array('rule' => 'awesome')); - $rules = $validator['body']->getRules(); - $this->assertCount(3, $rules); - $this->assertEquals('awesome', $rules['isAwesome']->rule); - } - -/** - * Test to ensure custom validation methods work with CakeValidationSet - * - * @return void - */ - public function testCustomMethodsWithCakeValidationSet() { - $TestModel = new TestValidate(); - $Validator = $TestModel->validator(); - - $Validator->add('title', 'validateTitle', array( - 'rule' => 'validateTitle', - 'message' => 'That aint right', - )); - $data = array('title' => 'notatitle'); - $result = $Validator->getField('title')->validate($data); - $expected = array(0 => 'That aint right'); - $this->assertEquals($expected, $result); - - $data = array('title' => 'title-is-good'); - $result = $Validator->getField('title')->validate($data); - $expected = array(); - $this->assertEquals($expected, $result); - } - - public function testCustomMethodWithEmptyValue() { - $this->loadFixtures('Article'); - - $model = $this->getMock('Article', array('isLegit')); - $model->validate = array( - 'title' => array( - 'custom' => array( - 'rule' => array('isLegit'), - 'message' => 'is no good' - ) - ) - ); - $model->expects($this->once()) - ->method('isLegit') - ->will($this->returnValue(false)); - - $model->set(array('title' => '')); - $this->assertFalse($model->validates()); - } - -/** - * Test validateAssociated with atomic=false & deep=true - * - * @return void - */ - public function testValidateAssociatedAtomicFalseDeepTrueWithErrors() { - $this->loadFixtures('Comment', 'Article', 'User', 'Attachment'); - $Attachment = ClassRegistry::init('Attachment'); - $Attachment->Comment->validator()->add('comment', array( - array('rule' => 'notEmpty') - )); - $Attachment->Comment->User->bindModel(array( - 'hasMany' => array( - 'Article', - 'Comment' - )), - false - ); - - $data = array( - 'Attachment' => array( - 'attachment' => 'text', - 'Comment' => array( - 'comment' => '', - 'published' => 'N', - 'User' => array( - 'user' => 'Foo', - 'password' => 'mypassword', - 'Comment' => array( - array( - 'comment' => '' - ) - ) - ) - ) - ) - ); - $result = $Attachment->validateAssociated($data, array('atomic' => false, 'deep' => true)); - - $result = $Attachment->validationErrors; - $expected = array( - 'Comment' => array( - 'comment' => array( - 0 => 'The provided value is invalid', - ), - 'User' => array( - 'Comment' => array( - 0 => array( - 'comment' => array( - 0 => 'The provided value is invalid', - ), - ), - ), - ), - ), - ); - $this->assertEquals($expected, $result); - } - -/** - * Test validateMany with atomic=false & deep=true - * - * @return void - */ - public function testValidateManyAtomicFalseDeepTrueWithErrors() { - $this->loadFixtures('Comment', 'Article', 'User'); - $Article = ClassRegistry::init('Article'); - $Article->Comment->validator()->add('comment', array( - array('rule' => 'notEmpty') - )); - - $data = array( - array( - 'Article' => array( - 'user_id' => 1, - 'title' => 'Foo', - 'body' => 'text', - 'published' => 'N' - ), - 'Comment' => array( - array( - 'user_id' => 1, - 'comment' => 'Baz', - 'published' => 'N', - ) - ), - ), - array( - 'Article' => array( - 'user_id' => 1, - 'title' => 'Bar', - 'body' => 'text', - 'published' => 'N' - ), - 'Comment' => array( - array( - 'user_id' => 1, - 'comment' => '', - 'published' => 'N', - ) - ), - ), - ); - $Article->validateMany($data, array('atomic' => false, 'deep' => true)); - - $result = $Article->validationErrors; - $expected = array( - 1 => array( - 'Comment' => array( - 0 => array( - 'comment' => array( - 0 => 'The provided value is invalid', - ), - ), - ), - ), - ); - $this->assertEquals($expected, $result); - } - -} - -/** - * Behavior for testing validation rules. - */ -class ValidationRuleBehavior extends ModelBehavior { - - public function setup(Model $Model, $config = array()) { - $this->settings[$Model->alias] = $config; - } - - public function beforeValidate(Model $Model, $options = array()) { - $fields = $this->settings[$Model->alias]['fields']; - foreach ($fields as $field) { - $Model->whitelist[] = $field; - } - } - -} diff --git a/Cake/Test/TestCase/Model/ModelWriteTest.php b/Cake/Test/TestCase/Model/ModelWriteTest.php deleted file mode 100644 index 065194adeef..00000000000 --- a/Cake/Test/TestCase/Model/ModelWriteTest.php +++ /dev/null @@ -1,7200 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Model\Datasource\DboSource; -use Cake\Model\Model; -use Cake\Model\ModelBehavior; -use Cake\TestSuite\TestCase; -use Cake\Test\TestCase\Model\ModelTestBase; - -/** - * ModelWriteTest - * - */ -class ModelWriteTest extends ModelTestBase { - -/** - * override locale to the default (eng). - * - * @return void - */ - public function setUp() { - parent::setUp(); - Configure::write('Config.language', 'eng'); - } - -/** - * Test save() failing when there is no data. - * - * @return void - */ - public function testInsertNoData() { - $this->loadFixtures('Bid'); - $Bid = ClassRegistry::init('Bid'); - - $this->assertFalse($Bid->save()); - - $result = $Bid->save(array('Bid' => array())); - $this->assertFalse($result); - - $result = $Bid->save(array('Bid' => array('not in schema' => 1))); - $this->assertFalse($result); - } - -/** - * testInsertAnotherHabtmRecordWithSameForeignKey method - * - * @return void - */ - public function testInsertAnotherHabtmRecordWithSameForeignKey() { - $this->loadFixtures('JoinA', 'JoinB', 'JoinAB', 'JoinC', 'JoinAC'); - $TestModel = new JoinA(); - - $result = $TestModel->JoinAsJoinB->findById(1); - $expected = array( - 'JoinAsJoinB' => array( - 'id' => 1, - 'join_a_id' => 1, - 'join_b_id' => 2, - 'other' => 'Data for Join A 1 Join B 2', - 'created' => '2008-01-03 10:56:33', - 'updated' => '2008-01-03 10:56:33' - )); - $this->assertEquals($expected, $result); - - $TestModel->JoinAsJoinB->create(); - $data = array( - 'join_a_id' => 1, - 'join_b_id' => 1, - 'other' => 'Data for Join A 1 Join B 1', - 'created' => '2008-01-03 10:56:44', - 'updated' => '2008-01-03 10:56:44' - ); - $result = $TestModel->JoinAsJoinB->save($data); - $lastInsertId = $TestModel->JoinAsJoinB->getLastInsertID(); - $data['id'] = $lastInsertId; - $this->assertEquals(array('JoinAsJoinB' => $data), $result); - $this->assertTrue($lastInsertId > 0); - - $result = $TestModel->JoinAsJoinB->findById(1); - $expected = array( - 'JoinAsJoinB' => array( - 'id' => 1, - 'join_a_id' => 1, - 'join_b_id' => 2, - 'other' => 'Data for Join A 1 Join B 2', - 'created' => '2008-01-03 10:56:33', - 'updated' => '2008-01-03 10:56:33' - )); - $this->assertEquals($expected, $result); - - $updatedValue = 'UPDATED Data for Join A 1 Join B 2'; - $TestModel->JoinAsJoinB->id = 1; - $result = $TestModel->JoinAsJoinB->saveField('other', $updatedValue, false); - $this->assertFalse(empty($result)); - - $result = $TestModel->JoinAsJoinB->findById(1); - $this->assertEquals($updatedValue, $result['JoinAsJoinB']['other']); - } - -/** - * testSaveDateAsFirstEntry method - * - * @return void - */ - public function testSaveDateAsFirstEntry() { - $this->loadFixtures('Article', 'User', 'Comment', 'Attachment', 'Tag', 'ArticlesTag'); - - $Article = new Article(); - - $data = array( - 'Article' => array( - 'created' => array( - 'day' => '1', - 'month' => '1', - 'year' => '2008' - ), - 'title' => 'Test Title', - 'user_id' => 1 - )); - $Article->create(); - $result = $Article->save($data); - $this->assertFalse(empty($result)); - - $testResult = $Article->find('first', array('conditions' => array('Article.title' => 'Test Title'))); - - $this->assertEquals($data['Article']['title'], $testResult['Article']['title']); - $this->assertEquals('2008-01-01 00:00:00', $testResult['Article']['created']); - } - -/** - * testUnderscoreFieldSave method - * - * @return void - */ - public function testUnderscoreFieldSave() { - $this->loadFixtures('UnderscoreField'); - $UnderscoreField = new UnderscoreField(); - - $currentCount = $UnderscoreField->find('count'); - $this->assertEquals(3, $currentCount); - $data = array('UnderscoreField' => array( - 'user_id' => '1', - 'my_model_has_a_field' => 'Content here', - 'body' => 'Body', - 'published' => 'Y', - 'another_field' => 4 - )); - $ret = $UnderscoreField->save($data); - $this->assertFalse(empty($ret)); - - $currentCount = $UnderscoreField->find('count'); - $this->assertEquals(4, $currentCount); - } - -/** - * testAutoSaveUuid method - * - * @return void - */ - public function testAutoSaveUuid() { - // SQLite does not support non-integer primary keys - $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with SQLite.'); - - $this->loadFixtures('Uuid'); - $TestModel = new Uuid(); - - $TestModel->save(array('title' => 'Test record')); - $result = $TestModel->findByTitle('Test record'); - $this->assertEquals( - array('id', 'title', 'count', 'created', 'updated'), - array_keys($result['Uuid']) - ); - $this->assertEquals(36, strlen($result['Uuid']['id'])); - } - -/** - * Ensure that if the id key is null but present the save doesn't fail (with an - * x sql error: "Column id specified twice") - * - * @return void - */ - public function testSaveUuidNull() { - // SQLite does not support non-integer primary keys - $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with SQLite.'); - - $this->loadFixtures('Uuid'); - $TestModel = new Uuid(); - - $TestModel->save(array('title' => 'Test record', 'id' => null)); - $result = $TestModel->findByTitle('Test record'); - $this->assertEquals( - array('id', 'title', 'count', 'created', 'updated'), - array_keys($result['Uuid']) - ); - $this->assertEquals(36, strlen($result['Uuid']['id'])); - } - -/** - * testZeroDefaultFieldValue method - * - * @return void - */ - public function testZeroDefaultFieldValue() { - $this->skipIf($this->db instanceof Sqlite, 'SQLite uses loose typing, this operation is unsupported.'); - - $this->loadFixtures('DataTest'); - $TestModel = new DataTest(); - - $TestModel->create(array()); - $TestModel->save(); - $result = $TestModel->findById($TestModel->id); - $this->assertEquals(0, $result['DataTest']['count']); - $this->assertEquals(0, $result['DataTest']['float']); - } - -/** - * Tests validation parameter order in custom validation methods - * - * @return void - */ - public function testAllowSimulatedFields() { - $TestModel = new ValidationTest1(); - - $TestModel->create(array( - 'title' => 'foo', - 'bar' => 'baz' - )); - $expected = array( - 'ValidationTest1' => array( - 'title' => 'foo', - 'bar' => 'baz' - )); - $this->assertEquals($expected, $TestModel->data); - } - -/** - * test that Caches are getting cleared on save(). - * ensure that both inflections of controller names are getting cleared - * as URL for controller could be either overallFavorites/index or overall_favorites/index - * - * @return void - */ - public function testCacheClearOnSave() { - Configure::write('Cache.check', true); - Cache::enable(); - - $this->loadFixtures('OverallFavorite'); - $OverallFavorite = new OverallFavorite(); - - touch(CACHE . 'views/some_dir_overallfavorites_index.php'); - touch(CACHE . 'views/some_dir_overall_favorites_index.php'); - - $data = array( - 'OverallFavorite' => array( - 'id' => 22, - 'model_type' => '8-track', - 'model_id' => '3', - 'priority' => '1' - ) - ); - $OverallFavorite->create($data); - $OverallFavorite->save(); - - $this->assertFalse(file_exists(CACHE . 'views/some_dir_overallfavorites_index.php')); - $this->assertFalse(file_exists(CACHE . 'views/some_dir_overall_favorites_index.php')); - } - -/** - * test that save() resets whitelist on failed save - */ - public function testSaveFieldListResetsWhitelistOnFailedSave() { - $this->loadFixtures('Bidding'); - $model = new Bidding(); - $whitelist = array('title'); - $model->whitelist = $whitelist; - $result = $model->save( - array(), - array('fieldList' => array('body')) - ); - $this->assertFalse($result); - $this->assertEquals($whitelist, $model->whitelist); - } - -/** - * testSaveWithCounterCache method - * - * @return void - */ - public function testSaveWithCounterCache() { - $this->loadFixtures('Syfile', 'Item', 'Image', 'Portfolio', 'ItemsPortfolio'); - $TestModel = new Syfile(); - $TestModel2 = new Item(); - - $result = $TestModel->findById(1); - $this->assertNull($result['Syfile']['item_count']); - - $TestModel2->save(array( - 'name' => 'Item 7', - 'syfile_id' => 1, - 'published' => false - )); - - $result = $TestModel->findById(1); - $this->assertEquals(2, $result['Syfile']['item_count']); - - $TestModel2->delete(1); - $result = $TestModel->findById(1); - $this->assertEquals(1, $result['Syfile']['item_count']); - - $TestModel2->id = 2; - $TestModel2->saveField('syfile_id', 1); - - $result = $TestModel->findById(1); - $this->assertEquals(2, $result['Syfile']['item_count']); - - $result = $TestModel->findById(2); - $this->assertEquals(0, $result['Syfile']['item_count']); - } - -/** - * Tests that counter caches are updated when records are added - * - * @return void - */ - public function testCounterCacheIncrease() { - $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); - $User = new CounterCacheUser(); - $Post = new CounterCachePost(); - $data = array('Post' => array( - 'id' => 22, - 'title' => 'New Post', - 'user_id' => 66 - )); - - $Post->save($data); - $user = $User->find('first', array( - 'conditions' => array('id' => 66), - 'recursive' => -1 - )); - - $result = $user[$User->alias]['post_count']; - $expected = 3; - $this->assertEquals($expected, $result); - } - -/** - * Tests that counter caches are updated when records are deleted - * - * @return void - */ - public function testCounterCacheDecrease() { - $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); - $User = new CounterCacheUser(); - $Post = new CounterCachePost(); - - $Post->delete(2); - $user = $User->find('first', array( - 'conditions' => array('id' => 66), - 'recursive' => -1 - )); - - $result = $user[$User->alias]['post_count']; - $expected = 1; - $this->assertEquals($expected, $result); - } - -/** - * Tests that counter caches are updated when foreign keys of counted records change - * - * @return void - */ - public function testCounterCacheUpdated() { - $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); - $User = new CounterCacheUser(); - $Post = new CounterCachePost(); - - $data = $Post->find('first', array( - 'conditions' => array('id' => 1), - 'recursive' => -1 - )); - $data[$Post->alias]['user_id'] = 301; - $Post->save($data); - - $users = $User->find('all', array('order' => 'User.id')); - $this->assertEquals(1, $users[0]['User']['post_count']); - $this->assertEquals(2, $users[1]['User']['post_count']); - } - -/** - * Test counter cache with models that use a non-standard (i.e. not using 'id') - * as their primary key. - * - * @return void - */ - public function testCounterCacheWithNonstandardPrimaryKey() { - $this->loadFixtures( - 'CounterCacheUserNonstandardPrimaryKey', - 'CounterCachePostNonstandardPrimaryKey' - ); - - $User = new CounterCacheUserNonstandardPrimaryKey(); - $Post = new CounterCachePostNonstandardPrimaryKey(); - - $data = $Post->find('first', array( - 'conditions' => array('pid' => 1), - 'recursive' => -1 - )); - $data[$Post->alias]['uid'] = 301; - $Post->save($data); - - $users = $User->find('all', array('order' => 'User.uid')); - $this->assertEquals(1, $users[0]['User']['post_count']); - $this->assertEquals(2, $users[1]['User']['post_count']); - } - -/** - * test Counter Cache With Self Joining table - * - * @return void - */ - public function testCounterCacheWithSelfJoin() { - $this->skipIf($this->db instanceof Sqlite, 'SQLite 2.x does not support ALTER TABLE ADD COLUMN'); - - $this->loadFixtures('CategoryThread'); - $column = 'COLUMN '; - if ($this->db instanceof Sqlserver) { - $column = ''; - } - $column .= $this->db->buildColumn(array('name' => 'child_count', 'type' => 'integer')); - $this->db->query('ALTER TABLE ' . $this->db->fullTableName('category_threads') . ' ADD ' . $column); - $this->db->flushMethodCache(); - $Category = new CategoryThread(); - $result = $Category->updateAll(array('CategoryThread.name' => "'updated'"), array('CategoryThread.parent_id' => 5)); - $this->assertFalse(empty($result)); - - $Category = new CategoryThread(); - $Category->belongsTo['ParentCategory']['counterCache'] = 'child_count'; - $Category->updateCounterCache(array('parent_id' => 5)); - $result = Hash::extract($Category->find('all', array('conditions' => array('CategoryThread.id' => 5))), '{n}.CategoryThread.child_count'); - $expected = array(1); - $this->assertEquals($expected, $result); - } - -/** - * testSaveWithCounterCacheScope method - * - * @return void - */ - public function testSaveWithCounterCacheScope() { - $this->loadFixtures('Syfile', 'Item', 'Image', 'ItemsPortfolio', 'Portfolio'); - $TestModel = new Syfile(); - $TestModel2 = new Item(); - $TestModel2->belongsTo['Syfile']['counterCache'] = true; - $TestModel2->belongsTo['Syfile']['counterScope'] = array('published' => true); - - $result = $TestModel->findById(1); - $this->assertNull($result['Syfile']['item_count']); - - $TestModel2->save(array( - 'name' => 'Item 7', - 'syfile_id' => 1, - 'published' => true - )); - - $result = $TestModel->findById(1); - - $this->assertEquals(1, $result['Syfile']['item_count']); - - $TestModel2->id = 1; - $TestModel2->saveField('published', true); - $result = $TestModel->findById(1); - $this->assertEquals(2, $result['Syfile']['item_count']); - - $TestModel2->save(array( - 'id' => 1, - 'syfile_id' => 1, - 'published' => false - )); - - $result = $TestModel->findById(1); - $this->assertEquals(1, $result['Syfile']['item_count']); - } - -/** - * Tests having multiple counter caches for an associated model - * - * @return void - */ - public function testCounterCacheMultipleCaches() { - $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); - $User = new CounterCacheUser(); - $Post = new CounterCachePost(); - $Post->unbindModel(array('belongsTo' => array('User')), false); - $Post->bindModel(array( - 'belongsTo' => array( - 'User' => array( - 'className' => 'CounterCacheUser', - 'foreignKey' => 'user_id', - 'counterCache' => array( - true, - 'posts_published' => array('Post.published' => true) - ) - ) - ) - ), false); - - // Count Increase - $data = array('Post' => array( - 'id' => 22, - 'title' => 'New Post', - 'user_id' => 66, - 'published' => true - )); - $Post->save($data); - $result = $User->find('first', array( - 'conditions' => array('id' => 66), - 'recursive' => -1 - )); - $this->assertEquals(3, $result[$User->alias]['post_count']); - $this->assertEquals(2, $result[$User->alias]['posts_published']); - - // Count decrease - $Post->delete(1); - $result = $User->find('first', array( - 'conditions' => array('id' => 66), - 'recursive' => -1 - )); - $this->assertEquals(2, $result[$User->alias]['post_count']); - $this->assertEquals(2, $result[$User->alias]['posts_published']); - - // Count update - $data = $Post->find('first', array( - 'conditions' => array('id' => 1), - 'recursive' => -1 - )); - $data[$Post->alias]['user_id'] = 301; - $Post->save($data); - $result = $User->find('all', array('order' => 'User.id')); - $this->assertEquals(2, $result[0]['User']['post_count']); - $this->assertEquals(1, $result[1]['User']['posts_published']); - } - -/** - * Tests that counter caches are unchanged when using 'counterCache' => false - * - * @return void - */ - public function testCounterCacheSkip() { - $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); - $User = new CounterCacheUser(); - $Post = new CounterCachePost(); - - $data = $Post->find('first', array( - 'conditions' => array('id' => 1), - 'recursive' => -1 - )); - $data[$Post->alias]['user_id'] = 301; - $Post->save($data, array('counterCache' => false)); - - $users = $User->find('all', array('order' => 'User.id')); - $this->assertEquals(2, $users[0]['User']['post_count']); - $this->assertEquals(1, $users[1]['User']['post_count']); - } - -/** - * test that beforeValidate returning false can abort saves. - * - * @return void - */ - public function testBeforeValidateSaveAbortion() { - $this->loadFixtures('Post'); - $Model = new CallbackPostTestModel(); - $Model->beforeValidateReturn = false; - - $data = array( - 'title' => 'new article', - 'body' => 'this is some text.' - ); - $Model->create(); - $result = $Model->save($data); - $this->assertFalse($result); - } - -/** - * test that beforeSave returning false can abort saves. - * - * @return void - */ - public function testBeforeSaveSaveAbortion() { - $this->loadFixtures('Post'); - $Model = new CallbackPostTestModel(); - $Model->beforeSaveReturn = false; - - $data = array( - 'title' => 'new article', - 'body' => 'this is some text.' - ); - $Model->create(); - $result = $Model->save($data); - $this->assertFalse($result); - } - -/** - * testSaveField method - * - * @return void - */ - public function testSaveField() { - $this->loadFixtures('Article'); - $TestModel = new Article(); - - $TestModel->id = 1; - $result = $TestModel->saveField('title', 'New First Article'); - $this->assertFalse(empty($result)); - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body'), 1); - $expected = array('Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'New First Article', - 'body' => 'First Article Body' - )); - $this->assertEquals($expected, $result); - - $TestModel->id = 1; - $result = $TestModel->saveField('title', ''); - $this->assertFalse(empty($result)); - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body'), 1); - $expected = array('Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => '', - 'body' => 'First Article Body' - )); - $result['Article']['title'] = trim($result['Article']['title']); - $this->assertEquals($expected, $result); - - $TestModel->id = 1; - $TestModel->set('body', 'Messed up data'); - $result = $TestModel->saveField('title', 'First Article'); - $this->assertFalse(empty($result)); - $result = $TestModel->read(array('id', 'user_id', 'title', 'body'), 1); - $expected = array('Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body' - )); - $this->assertEquals($expected, $result); - - $TestModel->recursive = -1; - $TestModel->read(array('id', 'user_id', 'title', 'body'), 1); - - $TestModel->id = 1; - $result = $TestModel->saveField('title', '', true); - $this->assertFalse($result); - - $TestModel->recursive = -1; - $TestModel->id = 1; - $result = $TestModel->saveField('user_id', 9999); - $this->assertTrue((bool)$result); - - $result = $TestModel->read(array('id', 'user_id'), 1); - $expected = array('Article' => array( - 'id' => '1', - 'user_id' => '9999', - )); - $this->assertEquals($expected, $result); - - $this->loadFixtures('Node', 'Dependency'); - $Node = new Node(); - $Node->set('id', 1); - $result = $Node->read(); - $this->assertEquals(array('Second'), Hash::extract($result, 'ParentNode.{n}.name')); - - $Node->saveField('state', 10); - $result = $Node->read(); - $this->assertEquals(array('Second'), Hash::extract($result, 'ParentNode.{n}.name')); - } - -/** - * testSaveWithCreate method - * - * @return void - */ - public function testSaveWithCreate() { - $this->loadFixtures( - 'User', - 'Article', - 'User', - 'Comment', - 'Tag', - 'ArticlesTag', - 'Attachment' - ); - $TestModel = new User(); - - $data = array('User' => array( - 'user' => 'user', - 'password' => '' - )); - $result = $TestModel->save($data); - $this->assertFalse($result); - $this->assertTrue(!empty($TestModel->validationErrors)); - - $TestModel = new Article(); - - $data = array('Article' => array( - 'user_id' => '', - 'title' => '', - 'body' => '' - )); - $result = $TestModel->create($data) && $TestModel->save(); - $this->assertFalse($result); - $this->assertTrue(!empty($TestModel->validationErrors)); - - $data = array('Article' => array( - 'id' => 1, - 'user_id' => '1', - 'title' => 'New First Article', - 'body' => '' - )); - $result = $TestModel->create($data) && $TestModel->save(); - $this->assertFalse($result); - - $data = array('Article' => array( - 'id' => 1, - 'title' => 'New First Article' - )); - $result = $TestModel->create() && $TestModel->save($data, false); - $this->assertFalse(empty($result)); - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 1); - $expected = array('Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'New First Article', - 'body' => 'First Article Body', - 'published' => 'N' - )); - $this->assertEquals($expected, $result); - - $data = array('Article' => array( - 'id' => 1, - 'user_id' => '2', - 'title' => 'First Article', - 'body' => 'New First Article Body', - 'published' => 'Y' - )); - $result = $TestModel->create() && $TestModel->save($data, true, array('id', 'title', 'published')); - $this->assertFalse(empty($result)); - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 1); - $expected = array('Article' => array( - 'id' => '1', - 'user_id' => '1', - 'title' => 'First Article', - 'body' => 'First Article Body', - 'published' => 'Y' - )); - $this->assertEquals($expected, $result); - - $data = array( - 'Article' => array( - 'user_id' => '2', - 'title' => 'New Article', - 'body' => 'New Article Body', - 'created' => '2007-03-18 14:55:23', - 'updated' => '2007-03-18 14:57:31' - ), - 'Tag' => array('Tag' => array(1, 3)) - ); - $TestModel->create(); - $result = $TestModel->create() && $TestModel->save($data); - $this->assertFalse(empty($result)); - - $TestModel->recursive = 2; - $result = $TestModel->read(null, 4); - $expected = array( - 'Article' => array( - 'id' => '4', - 'user_id' => '2', - 'title' => 'New Article', - 'body' => 'New Article Body', - 'published' => 'N', - 'created' => '2007-03-18 14:55:23', - 'updated' => '2007-03-18 14:57:31' - ), - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - ), - 'Comment' => array(), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))); - $this->assertEquals($expected, $result); - - $data = array('Comment' => array( - 'article_id' => '4', - 'user_id' => '1', - 'comment' => 'Comment New Article', - 'published' => 'Y', - 'created' => '2007-03-18 14:57:23', - 'updated' => '2007-03-18 14:59:31' - )); - $result = $TestModel->Comment->create() && $TestModel->Comment->save($data); - $this->assertFalse(empty($result)); - - $data = array('Attachment' => array( - 'comment_id' => '7', - 'attachment' => 'newattachment.zip', - 'created' => '2007-03-18 15:02:23', - 'updated' => '2007-03-18 15:04:31' - )); - $result = $TestModel->Comment->Attachment->save($data); - $this->assertFalse(empty($result)); - - $TestModel->recursive = 2; - $result = $TestModel->read(null, 4); - $expected = array( - 'Article' => array( - 'id' => '4', - 'user_id' => '2', - 'title' => 'New Article', - 'body' => 'New Article Body', - 'published' => 'N', - 'created' => '2007-03-18 14:55:23', - 'updated' => '2007-03-18 14:57:31' - ), - 'User' => array( - 'id' => '2', - 'user' => 'nate', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:18:23', - 'updated' => '2007-03-17 01:20:31' - ), - 'Comment' => array( - array( - 'id' => '7', - 'article_id' => '4', - 'user_id' => '1', - 'comment' => 'Comment New Article', - 'published' => 'Y', - 'created' => '2007-03-18 14:57:23', - 'updated' => '2007-03-18 14:59:31', - 'Article' => array( - 'id' => '4', - 'user_id' => '2', - 'title' => 'New Article', - 'body' => 'New Article Body', - 'published' => 'N', - 'created' => '2007-03-18 14:55:23', - 'updated' => '2007-03-18 14:57:31' - ), - 'User' => array( - 'id' => '1', - 'user' => 'mariano', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:16:23', - 'updated' => '2007-03-17 01:18:31' - ), - 'Attachment' => array( - 'id' => '2', - 'comment_id' => '7', - 'attachment' => 'newattachment.zip', - 'created' => '2007-03-18 15:02:23', - 'updated' => '2007-03-18 15:04:31' - ))), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))); - - $this->assertEquals($expected, $result); - } - -/** - * test that a null Id doesn't cause errors - * - * @return void - */ - public function testSaveWithNullId() { - $this->loadFixtures('User'); - $User = new User(); - $User->read(null, 1); - $User->data['User']['id'] = null; - $result = $User->save(array('password' => 'test')); - $this->assertFalse(empty($result)); - $this->assertTrue($User->id > 0); - - $User->read(null, 2); - $User->data['User']['id'] = null; - $result = $User->save(array('password' => 'test')); - $this->assertFalse(empty($result)); - $this->assertTrue($User->id > 0); - - $User->data['User'] = array('password' => 'something'); - $result = $User->save(); - $this->assertFalse(empty($result)); - $result = $User->read(); - $this->assertEquals('something', $User->data['User']['password']); - } - -/** - * testSaveWithSet method - * - * @return void - */ - public function testSaveWithSet() { - $this->loadFixtures('Article'); - $TestModel = new Article(); - - // Create record we will be updating later - - $data = array('Article' => array( - 'user_id' => '1', - 'title' => 'Fourth Article', - 'body' => 'Fourth Article Body', - 'published' => 'Y' - )); - $result = $TestModel->create() && $TestModel->save($data); - $this->assertFalse(empty($result)); - - // Check record we created - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 4); - $expected = array('Article' => array( - 'id' => '4', - 'user_id' => '1', - 'title' => 'Fourth Article', - 'body' => 'Fourth Article Body', - 'published' => 'Y' - )); - $this->assertEquals($expected, $result); - - // Create new record just to overlap Model->id on previously created record - - $data = array('Article' => array( - 'user_id' => '4', - 'title' => 'Fifth Article', - 'body' => 'Fifth Article Body', - 'published' => 'Y' - )); - $result = $TestModel->create() && $TestModel->save($data); - $this->assertFalse(empty($result)); - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 5); - $expected = array('Article' => array( - 'id' => '5', - 'user_id' => '4', - 'title' => 'Fifth Article', - 'body' => 'Fifth Article Body', - 'published' => 'Y' - )); - $this->assertEquals($expected, $result); - - // Go back and edit the first article we created, starting by checking it's still there - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 4); - $expected = array('Article' => array( - 'id' => '4', - 'user_id' => '1', - 'title' => 'Fourth Article', - 'body' => 'Fourth Article Body', - 'published' => 'Y' - )); - $this->assertEquals($expected, $result); - - // And now do the update with set() - - $data = array('Article' => array( - 'id' => '4', - 'title' => 'Fourth Article - New Title', - 'published' => 'N' - )); - $result = $TestModel->set($data) && $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 4); - $expected = array('Article' => array( - 'id' => '4', - 'user_id' => '1', - 'title' => 'Fourth Article - New Title', - 'body' => 'Fourth Article Body', - 'published' => 'N' - )); - $this->assertEquals($expected, $result); - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 5); - $expected = array('Article' => array( - 'id' => '5', - 'user_id' => '4', - 'title' => 'Fifth Article', - 'body' => 'Fifth Article Body', - 'published' => 'Y' - )); - $this->assertEquals($expected, $result); - - $data = array('Article' => array('id' => '5', 'title' => 'Fifth Article - New Title 5')); - $result = ($TestModel->set($data) && $TestModel->save()); - $this->assertFalse(empty($result)); - - $TestModel->recursive = -1; - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 5); - $expected = array('Article' => array( - 'id' => '5', - 'user_id' => '4', - 'title' => 'Fifth Article - New Title 5', - 'body' => 'Fifth Article Body', - 'published' => 'Y' - )); - $this->assertEquals($expected, $result); - - $TestModel->recursive = -1; - $result = $TestModel->find('all', array( - 'fields' => array('id', 'title'), - 'order' => array('Article.id' => 'ASC') - )); - $expected = array( - array('Article' => array('id' => 1, 'title' => 'First Article')), - array('Article' => array('id' => 2, 'title' => 'Second Article')), - array('Article' => array('id' => 3, 'title' => 'Third Article')), - array('Article' => array('id' => 4, 'title' => 'Fourth Article - New Title')), - array('Article' => array('id' => 5, 'title' => 'Fifth Article - New Title 5')) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveWithNonExistentFields method - * - * @return void - */ - public function testSaveWithNonExistentFields() { - $this->loadFixtures('Article'); - $TestModel = new Article(); - $TestModel->recursive = -1; - - $data = array( - 'non_existent' => 'This field does not exist', - 'user_id' => '1', - 'title' => 'Fourth Article - New Title', - 'body' => 'Fourth Article Body', - 'published' => 'N' - ); - $result = $TestModel->create() && $TestModel->save($data); - $this->assertFalse(empty($result)); - - $expected = array('Article' => array( - 'id' => '4', - 'user_id' => '1', - 'title' => 'Fourth Article - New Title', - 'body' => 'Fourth Article Body', - 'published' => 'N' - )); - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 4); - $this->assertEquals($expected, $result); - - $data = array( - 'user_id' => '1', - 'non_existent' => 'This field does not exist', - 'title' => 'Fifth Article - New Title', - 'body' => 'Fifth Article Body', - 'published' => 'N' - ); - $result = $TestModel->create() && $TestModel->save($data); - $this->assertFalse(empty($result)); - - $expected = array('Article' => array( - 'id' => '5', - 'user_id' => '1', - 'title' => 'Fifth Article - New Title', - 'body' => 'Fifth Article Body', - 'published' => 'N' - )); - $result = $TestModel->read(array('id', 'user_id', 'title', 'body', 'published'), 5); - $this->assertEquals($expected, $result); - } - -/** - * testSaveFromXml method - * - * @return void - */ - public function testSaveFromXml() { - $this->markTestSkipped('This feature needs to be fixed or dropped'); - $this->loadFixtures('Article'); - App::uses('Xml', 'Utility'); - - $Article = new Article(); - $result = $Article->save(Xml::build('
')); - $this->assertFalse(empty($result)); - $results = $Article->find('first', array('conditions' => array('Article.title' => 'test xml'))); - $this->assertFalse(empty($results)); - - $result = $Article->save(Xml::build('
testing6
')); - $this->assertFalse(empty($result)); - $results = $Article->find('first', array('conditions' => array('Article.title' => 'testing'))); - $this->assertFalse(empty($results)); - - $result = $Article->save(Xml::build('
testing with DOMDocument7
', array('return' => 'domdocument'))); - $this->assertFalse(empty($result)); - $results = $Article->find('first', array('conditions' => array('Article.title' => 'testing with DOMDocument'))); - $this->assertFalse(empty($results)); - } - -/** - * testSaveHabtm method - * - * @return void - */ - public function testSaveHabtm() { - $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); - $TestModel = new Article(); - - $result = $TestModel->findById(2); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'User' => array( - 'id' => '3', - 'user' => 'larry', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', - 'created' => '2007-03-17 01:20:23', - 'updated' => '2007-03-17 01:22:31' - ), - 'Comment' => array( - array( - 'id' => '5', - 'article_id' => '2', - 'user_id' => '1', - 'comment' => 'First Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:53:23', - 'updated' => '2007-03-18 10:55:31' - ), - array( - 'id' => '6', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y', - 'created' => '2007-03-18 10:55:23', - 'updated' => '2007-03-18 10:57:31' - )), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ) - ) - ); - $this->assertEquals($expected, $result); - - $data = array( - 'Article' => array( - 'id' => '2', - 'title' => 'New Second Article' - ), - 'Tag' => array('Tag' => array(1, 2)) - ); - - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - $this->assertEquals($data['Tag'], $result['Tag']); - - $TestModel->unbindModel(array('belongsTo' => array('User'), 'hasMany' => array('Comment'))); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'New Second Article', - 'body' => 'Second Article Body' - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ))); - $this->assertEquals($expected, $result); - - $data = array('Article' => array('id' => '2'), 'Tag' => array('Tag' => array(2, 3))); - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'New Second Article', - 'body' => 'Second Article Body' - ), - 'Tag' => array( - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))); - $this->assertEquals($expected, $result); - - $data = array('Tag' => array('Tag' => array(1, 2, 3))); - - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'New Second Article', - 'body' => 'Second Article Body' - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))); - $this->assertEquals($expected, $result); - - $data = array('Tag' => array('Tag' => array())); - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $data = array('Tag' => array('Tag' => '')); - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'New Second Article', - 'body' => 'Second Article Body' - ), - 'Tag' => array() - ); - $this->assertEquals($expected, $result); - - $data = array('Tag' => array('Tag' => array(2, 3))); - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'New Second Article', - 'body' => 'Second Article Body' - ), - 'Tag' => array( - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))); - $this->assertEquals($expected, $result); - - $data = array( - 'Tag' => array( - 'Tag' => array(1, 2) - ), - 'Article' => array( - 'id' => '2', - 'title' => 'New Second Article' - )); - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'New Second Article', - 'body' => 'Second Article Body' - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ))); - $this->assertEquals($expected, $result); - - $data = array( - 'Tag' => array( - 'Tag' => array(1, 2) - ), - 'Article' => array( - 'id' => '2', - 'title' => 'New Second Article Title' - )); - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'New Second Article Title', - 'body' => 'Second Article Body' - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ) - ) - ); - $this->assertEquals($expected, $result); - - $data = array( - 'Tag' => array( - 'Tag' => array(2, 3) - ), - 'Article' => array( - 'id' => '2', - 'title' => 'Changed Second Article' - )); - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Changed Second Article', - 'body' => 'Second Article Body' - ), - 'Tag' => array( - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ) - ) - ); - $this->assertEquals($expected, $result); - - $data = array( - 'Tag' => array( - 'Tag' => array(1, 3) - ), - 'Article' => array('id' => '2'), - ); - - $result = $TestModel->set($data); - $this->assertFalse(empty($result)); - - $result = $TestModel->save(); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Changed Second Article', - 'body' => 'Second Article Body' - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))); - $this->assertEquals($expected, $result); - - $data = array( - 'Article' => array( - 'id' => 10, - 'user_id' => '2', - 'title' => 'New Article With Tags and fieldList', - 'body' => 'New Article Body with Tags and fieldList', - 'created' => '2007-03-18 14:55:23', - 'updated' => '2007-03-18 14:57:31' - ), - 'Tag' => array( - 'Tag' => array(1, 2, 3) - ) - ); - $result = $TestModel->create() - && $TestModel->save($data, true, array('user_id', 'title', 'published')); - $this->assertFalse(empty($result)); - - $TestModel->unbindModel(array( - 'belongsTo' => array('User'), - 'hasMany' => array('Comment') - )); - $result = $TestModel->read(); - $expected = array( - 'Article' => array( - 'id' => 4, - 'user_id' => 2, - 'title' => 'New Article With Tags and fieldList', - 'body' => '', - 'published' => 'N', - 'created' => '', - 'updated' => '' - ), - 'Tag' => array( - 0 => array( - 'id' => 1, - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - 1 => array( - 'id' => 2, - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ), - 2 => array( - 'id' => 3, - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))); - $this->assertEquals($expected, $result); - - $this->loadFixtures('JoinA', 'JoinC', 'JoinAC', 'JoinB', 'JoinAB'); - $TestModel = new JoinA(); - $TestModel->hasBelongsToMany = array('JoinC' => array('unique' => true)); - $data = array( - 'JoinA' => array( - 'id' => 1, - 'name' => 'Join A 1', - 'body' => 'Join A 1 Body', - ), - 'JoinC' => array( - 'JoinC' => array( - array('join_c_id' => 2, 'other' => 'new record'), - array('join_c_id' => 3, 'other' => 'new record') - ) - ) - ); - $TestModel->save($data); - $result = $TestModel->read(null, 1); - $expected = array(4, 5); - $this->assertEquals($expected, Hash::extract($result, 'JoinC.{n}.JoinAsJoinC.id')); - $expected = array('new record', 'new record'); - $this->assertEquals($expected, Hash::extract($result, 'JoinC.{n}.JoinAsJoinC.other')); - } - -/** - * testSaveHabtmNoPrimaryData method - * - * @return void - */ - public function testSaveHabtmNoPrimaryData() { - $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); - $TestModel = new Article(); - - $TestModel->unbindModel(array('belongsTo' => array('User'), 'hasMany' => array('Comment')), false); - $result = $TestModel->findById(2); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - ), - 'Tag' => array( - array( - 'id' => '1', - 'tag' => 'tag1', - 'created' => '2007-03-18 12:22:23', - 'updated' => '2007-03-18 12:24:31' - ), - array( - 'id' => '3', - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ) - ) - ); - $this->assertEquals($expected, $result); - - $TestModel->id = 2; - $data = array('Tag' => array('Tag' => array(2))); - $result = $TestModel->save($data); - - $this->assertEquals($data['Tag'], $result['Tag']); - - $result = $TestModel->findById(2); - $expected = array( - 'Article' => array( - 'id' => '2', - 'user_id' => '3', - 'title' => 'Second Article', - 'body' => 'Second Article Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => static::date() - ), - 'Tag' => array( - array( - 'id' => '2', - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ) - ) - ); - $this->assertEquals($expected, $result); - - $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio'); - $TestModel = new Portfolio(); - $result = $TestModel->findById(2); - $expected = array( - 'Portfolio' => array( - 'id' => 2, - 'seller_id' => 1, - 'name' => 'Portfolio 2' - ), - 'Item' => array( - array( - 'id' => 2, - 'syfile_id' => 2, - 'published' => '', - 'name' => 'Item 2', - 'ItemsPortfolio' => array( - 'id' => 2, - 'item_id' => 2, - 'portfolio_id' => 2 - ) - ), - array( - 'id' => 6, - 'syfile_id' => 6, - 'published' => '', - 'name' => 'Item 6', - 'ItemsPortfolio' => array( - 'id' => 6, - 'item_id' => 6, - 'portfolio_id' => 2 - ) - ) - ) - ); - $this->assertEquals($expected, $result); - - $data = array('Item' => array('Item' => array(1, 2))); - $TestModel->id = 2; - $TestModel->save($data); - $result = $TestModel->findById(2); - $result['Item'] = Hash::sort($result['Item'], '{n}.id', 'asc'); - $expected = array( - 'Portfolio' => array( - 'id' => 2, - 'seller_id' => 1, - 'name' => 'Portfolio 2' - ), - 'Item' => array( - array( - 'id' => 1, - 'syfile_id' => 1, - 'published' => '', - 'name' => 'Item 1', - 'ItemsPortfolio' => array( - 'id' => 7, - 'item_id' => 1, - 'portfolio_id' => 2 - ) - ), - array( - 'id' => 2, - 'syfile_id' => 2, - 'published' => '', - 'name' => 'Item 2', - 'ItemsPortfolio' => array( - 'id' => 8, - 'item_id' => 2, - 'portfolio_id' => 2 - ) - ) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveHabtmCustomKeys method - * - * @return void - */ - public function testSaveHabtmCustomKeys() { - $this->loadFixtures('Story', 'StoriesTag', 'Tag'); - $Story = new Story(); - - $data = array( - 'Story' => array('story' => '1'), - 'Tag' => array( - 'Tag' => array(2, 3) - )); - $result = $Story->set($data); - $this->assertFalse(empty($result)); - - $result = $Story->save(); - $this->assertFalse(empty($result)); - - $result = $Story->find('all', array('order' => array('Story.story'))); - $expected = array( - array( - 'Story' => array( - 'story' => 1, - 'title' => 'First Story' - ), - 'Tag' => array( - array( - 'id' => 2, - 'tag' => 'tag2', - 'created' => '2007-03-18 12:24:23', - 'updated' => '2007-03-18 12:26:31' - ), - array( - 'id' => 3, - 'tag' => 'tag3', - 'created' => '2007-03-18 12:26:23', - 'updated' => '2007-03-18 12:28:31' - ))), - array( - 'Story' => array( - 'story' => 2, - 'title' => 'Second Story' - ), - 'Tag' => array() - )); - $this->assertEquals($expected, $result); - } - -/** - * test that saving habtm records respects conditions set in the 'conditions' key - * for the association. - * - * @return void - */ - public function testHabtmSaveWithConditionsInAssociation() { - $this->loadFixtures('JoinThing', 'Something', 'SomethingElse'); - $Something = new Something(); - $Something->unbindModel(array('hasAndBelongsToMany' => array('SomethingElse')), false); - - $Something->bindModel(array( - 'hasAndBelongsToMany' => array( - 'DoomedSomethingElse' => array( - 'className' => 'SomethingElse', - 'joinTable' => 'join_things', - 'conditions' => array('JoinThing.doomed' => true), - 'unique' => true - ), - 'NotDoomedSomethingElse' => array( - 'className' => 'SomethingElse', - 'joinTable' => 'join_things', - 'conditions' => array('JoinThing.doomed' => 0), - 'unique' => true - ) - ) - ), false); - $result = $Something->read(null, 1); - $this->assertTrue(empty($result['NotDoomedSomethingElse'])); - $this->assertEquals(1, count($result['DoomedSomethingElse'])); - - $data = array( - 'Something' => array('id' => 1), - 'NotDoomedSomethingElse' => array( - 'NotDoomedSomethingElse' => array( - array('something_else_id' => 2, 'doomed' => 0), - array('something_else_id' => 3, 'doomed' => 0) - ) - ) - ); - $Something->create($data); - $result = $Something->save(); - $this->assertFalse(empty($result)); - - $result = $Something->read(null, 1); - $this->assertEquals(2, count($result['NotDoomedSomethingElse'])); - $this->assertEquals(1, count($result['DoomedSomethingElse'])); - } - -/** - * testHabtmSaveKeyResolution method - * - * @return void - */ - public function testHabtmSaveKeyResolution() { - $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies'); - $ThePaper = new ThePaper(); - - $ThePaper->id = 1; - $ThePaper->save(array('Monkey' => array(2, 3))); - - $result = $ThePaper->findById(1); - $expected = array( - array( - 'id' => '2', - 'device_type_id' => '1', - 'name' => 'Device 2', - 'typ' => '1' - ), - array( - 'id' => '3', - 'device_type_id' => '1', - 'name' => 'Device 3', - 'typ' => '2' - )); - $this->assertEquals($expected, $result['Monkey']); - - $ThePaper->id = 2; - $ThePaper->save(array('Monkey' => array(1, 2, 3))); - - $result = $ThePaper->findById(2); - $expected = array( - array( - 'id' => '1', - 'device_type_id' => '1', - 'name' => 'Device 1', - 'typ' => '1' - ), - array( - 'id' => '2', - 'device_type_id' => '1', - 'name' => 'Device 2', - 'typ' => '1' - ), - array( - 'id' => '3', - 'device_type_id' => '1', - 'name' => 'Device 3', - 'typ' => '2' - )); - $this->assertEquals($expected, $result['Monkey']); - - $ThePaper->id = 2; - $ThePaper->save(array('Monkey' => array(1, 3))); - - $result = $ThePaper->findById(2); - $expected = array( - array( - 'id' => '1', - 'device_type_id' => '1', - 'name' => 'Device 1', - 'typ' => '1' - ), - array( - 'id' => '3', - 'device_type_id' => '1', - 'name' => 'Device 3', - 'typ' => '2' - )); - $this->assertEquals($expected, $result['Monkey']); - - $result = $ThePaper->findById(1); - $expected = array( - array( - 'id' => '2', - 'device_type_id' => '1', - 'name' => 'Device 2', - 'typ' => '1' - ), - array( - 'id' => '3', - 'device_type_id' => '1', - 'name' => 'Device 3', - 'typ' => '2' - )); - $this->assertEquals($expected, $result['Monkey']); - } - -/** - * testCreationOfEmptyRecord method - * - * @return void - */ - public function testCreationOfEmptyRecord() { - $this->loadFixtures('Author'); - $TestModel = new Author(); - $this->assertEquals(4, $TestModel->find('count')); - - $TestModel->deleteAll(true, false, false); - $this->assertEquals(0, $TestModel->find('count')); - - $result = $TestModel->save(); - $this->assertTrue(isset($result['Author']['created'])); - $this->assertTrue(isset($result['Author']['updated'])); - $this->assertEquals(1, $TestModel->find('count')); - } - -/** - * testCreateWithPKFiltering method - * - * @return void - */ - public function testCreateWithPKFiltering() { - $TestModel = new Article(); - $data = array( - 'id' => 5, - 'user_id' => 2, - 'title' => 'My article', - 'body' => 'Some text' - ); - - $result = $TestModel->create($data); - $expected = array( - 'Article' => array( - 'published' => 'N', - 'id' => 5, - 'user_id' => 2, - 'title' => 'My article', - 'body' => 'Some text' - )); - - $this->assertEquals($expected, $result); - $this->assertEquals(5, $TestModel->id); - - $result = $TestModel->create($data, true); - $expected = array( - 'Article' => array( - 'published' => 'N', - 'id' => false, - 'user_id' => 2, - 'title' => 'My article', - 'body' => 'Some text' - )); - - $this->assertEquals($expected, $result); - $this->assertFalse($TestModel->id); - - $result = $TestModel->create(array('Article' => $data), true); - $expected = array( - 'Article' => array( - 'published' => 'N', - 'id' => false, - 'user_id' => 2, - 'title' => 'My article', - 'body' => 'Some text' - )); - - $this->assertEquals($expected, $result); - $this->assertFalse($TestModel->id); - - $data = array( - 'id' => 6, - 'user_id' => 2, - 'title' => 'My article', - 'body' => 'Some text', - 'created' => '1970-01-01 00:00:00', - 'updated' => '1970-01-01 12:00:00', - 'modified' => '1970-01-01 12:00:00' - ); - - $result = $TestModel->create($data); - $expected = array( - 'Article' => array( - 'published' => 'N', - 'id' => 6, - 'user_id' => 2, - 'title' => 'My article', - 'body' => 'Some text', - 'created' => '1970-01-01 00:00:00', - 'updated' => '1970-01-01 12:00:00', - 'modified' => '1970-01-01 12:00:00' - )); - $this->assertEquals($expected, $result); - $this->assertEquals(6, $TestModel->id); - - $result = $TestModel->create(array( - 'Article' => array_diff_key($data, array( - 'created' => true, - 'updated' => true, - 'modified' => true - ))), true); - $expected = array( - 'Article' => array( - 'published' => 'N', - 'id' => false, - 'user_id' => 2, - 'title' => 'My article', - 'body' => 'Some text' - )); - $this->assertEquals($expected, $result); - $this->assertFalse($TestModel->id); - } - -/** - * testCreationWithMultipleData method - * - * @return void - */ - public function testCreationWithMultipleData() { - $this->loadFixtures('Article', 'Comment'); - $Article = new Article(); - $Comment = new Comment(); - - $articles = $Article->find('all', array( - 'fields' => array('id', 'title'), - 'recursive' => -1, - 'order' => array('Article.id' => 'ASC') - )); - $expected = array( - array('Article' => array( - 'id' => 1, - 'title' => 'First Article' - )), - array('Article' => array( - 'id' => 2, - 'title' => 'Second Article' - )), - array('Article' => array( - 'id' => 3, - 'title' => 'Third Article' - ))); - $this->assertEquals($expected, $articles); - - $comments = $Comment->find('all', array( - 'fields' => array('id', 'article_id', 'user_id', 'comment', 'published'), - 'recursive' => -1, - 'order' => array('Comment.id' => 'ASC') - )); - $expected = array( - array('Comment' => array( - 'id' => 1, - 'article_id' => 1, - 'user_id' => 2, - 'comment' => 'First Comment for First Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 2, - 'article_id' => 1, - 'user_id' => 4, - 'comment' => 'Second Comment for First Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 3, - 'article_id' => 1, - 'user_id' => 1, - 'comment' => 'Third Comment for First Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 4, - 'article_id' => 1, - 'user_id' => 1, - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N' - )), - array('Comment' => array( - 'id' => 5, - 'article_id' => 2, - 'user_id' => 1, - 'comment' => 'First Comment for Second Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 6, - 'article_id' => 2, - 'user_id' => 2, - 'comment' => 'Second Comment for Second Article', - 'published' => 'Y' - ))); - $this->assertEquals($expected, $comments); - - $data = array( - 'Comment' => array( - 'article_id' => 2, - 'user_id' => 4, - 'comment' => 'Brand New Comment', - 'published' => 'N' - ), - 'Article' => array( - 'id' => 2, - 'title' => 'Second Article Modified' - )); - $result = $Comment->create($data); - $this->assertFalse(empty($result)); - - $result = $Comment->save(); - $this->assertFalse(empty($result)); - - $articles = $Article->find('all', array( - 'fields' => array('id', 'title'), - 'recursive' => -1, - 'order' => array('Article.id' => 'ASC') - )); - $expected = array( - array('Article' => array( - 'id' => 1, - 'title' => 'First Article' - )), - array('Article' => array( - 'id' => 2, - 'title' => 'Second Article' - )), - array('Article' => array( - 'id' => 3, - 'title' => 'Third Article' - ))); - $this->assertEquals($expected, $articles); - - $comments = $Comment->find('all', array( - 'fields' => array('id', 'article_id', 'user_id', 'comment', 'published'), - 'recursive' => -1, - 'order' => array('Comment.id' => 'ASC') - )); - $expected = array( - array('Comment' => array( - 'id' => 1, - 'article_id' => 1, - 'user_id' => 2, - 'comment' => 'First Comment for First Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 2, - 'article_id' => 1, - 'user_id' => 4, - 'comment' => 'Second Comment for First Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 3, - 'article_id' => 1, - 'user_id' => 1, - 'comment' => 'Third Comment for First Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 4, - 'article_id' => 1, - 'user_id' => 1, - 'comment' => 'Fourth Comment for First Article', - 'published' => 'N' - )), - array('Comment' => array( - 'id' => 5, - 'article_id' => 2, - 'user_id' => 1, - 'comment' => 'First Comment for Second Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 6, - 'article_id' => 2, - 'user_id' => 2, 'comment' => - 'Second Comment for Second Article', - 'published' => 'Y' - )), - array('Comment' => array( - 'id' => 7, - 'article_id' => 2, - 'user_id' => 4, - 'comment' => 'Brand New Comment', - 'published' => 'N' - ))); - $this->assertEquals($expected, $comments); - } - -/** - * testCreationWithMultipleDataSameModel method - * - * @return void - */ - public function testCreationWithMultipleDataSameModel() { - $this->loadFixtures('Article'); - $Article = new Article(); - - $result = $Article->field('title', array('id' => 1)); - $this->assertEquals('First Article', $result); - - $data = array( - 'Article' => array( - 'user_id' => 2, - 'title' => 'Brand New Article', - 'body' => 'Brand New Article Body', - 'published' => 'Y' - ), - 'SecondaryArticle' => array( - 'id' => 1 - )); - - $Article->create(); - $result = $Article->save($data); - $this->assertFalse(empty($result)); - - $result = $Article->getInsertID(); - $this->assertTrue(!empty($result)); - - $result = $Article->field('title', array('id' => 1)); - $this->assertEquals('First Article', $result); - - $articles = $Article->find('all', array( - 'fields' => array('id', 'title'), - 'recursive' => -1, - 'order' => array('Article.id' => 'ASC') - )); - $expected = array( - array('Article' => array( - 'id' => 1, - 'title' => 'First Article' - )), - array('Article' => array( - 'id' => 2, - 'title' => 'Second Article' - )), - array('Article' => array( - 'id' => 3, - 'title' => 'Third Article' - )), - array('Article' => array( - 'id' => 4, - 'title' => 'Brand New Article' - ))); - - $this->assertEquals($expected, $articles); - } - -/** - * testCreationWithMultipleDataSameModelManualInstances method - * - * @return void - */ - public function testCreationWithMultipleDataSameModelManualInstances() { - $this->loadFixtures('PrimaryModel'); - $Primary = new PrimaryModel(); - - $result = $Primary->field('primary_name', array('id' => 1)); - $this->assertEquals('Primary Name Existing', $result); - - $data = array( - 'PrimaryModel' => array( - 'primary_name' => 'Primary Name New' - ), - 'SecondaryModel' => array( - 'id' => array(1) - )); - - $Primary->create(); - $result = $Primary->save($data); - $this->assertFalse(empty($result)); - - $result = $Primary->field('primary_name', array('id' => 1)); - $this->assertEquals('Primary Name Existing', $result); - - $result = $Primary->getInsertID(); - $this->assertTrue(!empty($result)); - - $result = $Primary->field('primary_name', array('id' => $result)); - $this->assertEquals('Primary Name New', $result); - - $result = $Primary->find('count'); - $this->assertEquals(2, $result); - } - -/** - * testRecordExists method - * - * @return void - */ - public function testRecordExists() { - $this->loadFixtures('User'); - $TestModel = new User(); - - $this->assertFalse($TestModel->exists()); - $TestModel->read(null, 1); - $this->assertTrue($TestModel->exists()); - $TestModel->create(); - $this->assertFalse($TestModel->exists()); - $TestModel->id = 4; - $this->assertTrue($TestModel->exists()); - - $TestModel = new TheVoid(); - $this->assertFalse($TestModel->exists()); - } - -/** - * testRecordExistsMissingTable method - * - * @expectedException PDOException - * @return void - */ - public function testRecordExistsMissingTable() { - $TestModel = new TheVoid(); - $TestModel->id = 5; - $TestModel->exists(); - } - -/** - * testUpdateExisting method - * - * @return void - */ - public function testUpdateExisting() { - $this->loadFixtures('User', 'Article', 'Comment'); - $TestModel = new User(); - $TestModel->create(); - - $TestModel->save(array( - 'User' => array( - 'user' => 'some user', - 'password' => 'some password' - ))); - $this->assertTrue(is_int($TestModel->id) || (intval($TestModel->id) === 5)); - $id = $TestModel->id; - - $TestModel->save(array( - 'User' => array( - 'user' => 'updated user' - ))); - $this->assertEquals($id, $TestModel->id); - - $result = $TestModel->findById($id); - $this->assertEquals('updated user', $result['User']['user']); - $this->assertEquals('some password', $result['User']['password']); - - $Article = new Article(); - $Comment = new Comment(); - $data = array( - 'Comment' => array( - 'id' => 1, - 'comment' => 'First Comment for First Article' - ), - 'Article' => array( - 'id' => 2, - 'title' => 'Second Article' - )); - - $result = $Article->save($data); - $this->assertFalse(empty($result)); - - $result = $Comment->save($data); - $this->assertFalse(empty($result)); - } - -/** - * test updating records and saving blank values. - * - * @return void - */ - public function testUpdateSavingBlankValues() { - $this->loadFixtures('Article'); - $Article = new Article(); - $Article->validate = array(); - $Article->create(); - $result = $Article->save(array( - 'id' => 1, - 'title' => '', - 'body' => '' - )); - $this->assertTrue((bool)$result); - $result = $Article->find('first', array('conditions' => array('Article.id' => 1))); - $this->assertEquals('', $result['Article']['title'], 'Title is not blank'); - $this->assertEquals('', $result['Article']['body'], 'Body is not blank'); - } - -/** - * testUpdateMultiple method - * - * @return void - */ - public function testUpdateMultiple() { - $this->loadFixtures('Comment', 'Article', 'User', 'CategoryThread'); - $TestModel = new Comment(); - $result = Hash::extract($TestModel->find('all'), '{n}.Comment.user_id'); - $expected = array('2', '4', '1', '1', '1', '2'); - $this->assertEquals($expected, $result); - - $TestModel->updateAll(array('Comment.user_id' => 5), array('Comment.user_id' => 2)); - $result = Hash::combine($TestModel->find('all'), '{n}.Comment.id', '{n}.Comment.user_id'); - $expected = array(1 => 5, 2 => 4, 3 => 1, 4 => 1, 5 => 1, 6 => 5); - $this->assertEquals($expected, $result); - - $result = $TestModel->updateAll( - array('Comment.comment' => "'Updated today'"), - array('Comment.user_id' => 5) - ); - $this->assertFalse(empty($result)); - $result = Hash::extract( - $TestModel->find('all', array( - 'conditions' => array( - 'Comment.user_id' => 5 - ))), - '{n}.Comment.comment' - ); - $expected = array_fill(0, 2, 'Updated today'); - $this->assertEquals($expected, $result); - } - -/** - * testHabtmUuidWithUuidId method - * - * @return void - */ - public function testHabtmUuidWithUuidId() { - $this->loadFixtures('Uuidportfolio', 'Uuiditem', 'UuiditemsUuidportfolio', 'UuiditemsUuidportfolioNumericid'); - $TestModel = new Uuidportfolio(); - - $data = array('Uuidportfolio' => array('name' => 'Portfolio 3')); - $data['Uuiditem']['Uuiditem'] = array('483798c8-c7cc-430e-8cf9-4fcc40cf8569'); - $TestModel->create($data); - $TestModel->save(); - $id = $TestModel->id; - $result = $TestModel->read(null, $id); - $this->assertEquals(1, count($result['Uuiditem'])); - $this->assertEquals(36, strlen($result['Uuiditem'][0]['UuiditemsUuidportfolio']['id'])); - } - -/** - * test HABTM saving when join table has no primary key and only 2 columns. - * - * @return void - */ - public function testHabtmSavingWithNoPrimaryKeyUuidJoinTable() { - $this->loadFixtures('UuidTag', 'Fruit', 'FruitsUuidTag'); - $Fruit = new Fruit(); - $Fruit->FruitsUuidTag->order = null; - $data = array( - 'Fruit' => array( - 'color' => 'Red', - 'shape' => 'Heart-shaped', - 'taste' => 'sweet', - 'name' => 'Strawberry', - ), - 'UuidTag' => array( - 'UuidTag' => array( - '481fc6d0-b920-43e0-e50f-6d1740cf8569' - ) - ) - ); - $result = $Fruit->save($data); - $this->assertFalse(empty($result)); - } - -/** - * test HABTM saving when join table has no primary key and only 2 columns, no with model is used. - * - * @return void - */ - public function testHabtmSavingWithNoPrimaryKeyUuidJoinTableNoWith() { - $this->loadFixtures('UuidTag', 'Fruit', 'FruitsUuidTag'); - $Fruit = new FruitNoWith(); - $data = array( - 'Fruit' => array( - 'color' => 'Red', - 'shape' => 'Heart-shaped', - 'taste' => 'sweet', - 'name' => 'Strawberry', - ), - 'UuidTag' => array( - 'UuidTag' => array( - '481fc6d0-b920-43e0-e50f-6d1740cf8569' - ) - ) - ); - $result = $Fruit->save($data); - $this->assertFalse(empty($result)); - } - -/** - * testHabtmUuidWithNumericId method - * - * @return void - */ - public function testHabtmUuidWithNumericId() { - $this->loadFixtures('Uuidportfolio', 'Uuiditem', 'UuiditemsUuidportfolioNumericid'); - $TestModel = new Uuiditem(); - - $data = array('Uuiditem' => array('name' => 'Item 7', 'published' => 0)); - $data['Uuidportfolio']['Uuidportfolio'] = array('480af662-eb8c-47d3-886b-230540cf8569'); - $TestModel->create($data); - $TestModel->save(); - $id = $TestModel->id; - $result = $TestModel->read(null, $id); - $this->assertEquals(1, count($result['Uuidportfolio'])); - } - -/** - * testSaveMultipleHabtm method - * - * @return void - */ - public function testSaveMultipleHabtm() { - $this->loadFixtures('JoinA', 'JoinB', 'JoinC', 'JoinAB', 'JoinAC'); - $TestModel = new JoinA(); - $result = $TestModel->findById(1); - - $expected = array( - 'JoinA' => array( - 'id' => 1, - 'name' => 'Join A 1', - 'body' => 'Join A 1 Body', - 'created' => '2008-01-03 10:54:23', - 'updated' => '2008-01-03 10:54:23' - ), - 'JoinB' => array( - 0 => array( - 'id' => 2, - 'name' => 'Join B 2', - 'created' => '2008-01-03 10:55:02', - 'updated' => '2008-01-03 10:55:02', - 'JoinAsJoinB' => array( - 'id' => 1, - 'join_a_id' => 1, - 'join_b_id' => 2, - 'other' => 'Data for Join A 1 Join B 2', - 'created' => '2008-01-03 10:56:33', - 'updated' => '2008-01-03 10:56:33' - ))), - 'JoinC' => array( - 0 => array( - 'id' => 2, - 'name' => 'Join C 2', - 'created' => '2008-01-03 10:56:12', - 'updated' => '2008-01-03 10:56:12', - 'JoinAsJoinC' => array( - 'id' => 1, - 'join_a_id' => 1, - 'join_c_id' => 2, - 'other' => 'Data for Join A 1 Join C 2', - 'created' => '2008-01-03 10:57:22', - 'updated' => '2008-01-03 10:57:22' - )))); - - $this->assertEquals($expected, $result); - - $TestModel->id = 1; - $data = array( - 'JoinA' => array( - 'id' => '1', - 'name' => 'New name for Join A 1', - 'updated' => static::date() - ), - 'JoinB' => array( - array( - 'id' => 1, - 'join_b_id' => 2, - 'other' => 'New data for Join A 1 Join B 2', - 'created' => static::date(), - 'updated' => static::date() - )), - 'JoinC' => array( - array( - 'id' => 1, - 'join_c_id' => 2, - 'other' => 'New data for Join A 1 Join C 2', - 'created' => static::date(), - 'updated' => static::date() - ))); - - $TestModel->set($data); - $TestModel->save(); - - $result = $TestModel->findById(1); - $expected = array( - 'JoinA' => array( - 'id' => 1, - 'name' => 'New name for Join A 1', - 'body' => 'Join A 1 Body', - 'created' => '2008-01-03 10:54:23', - 'updated' => static::date() - ), - 'JoinB' => array( - 0 => array( - 'id' => 2, - 'name' => 'Join B 2', - 'created' => '2008-01-03 10:55:02', - 'updated' => '2008-01-03 10:55:02', - 'JoinAsJoinB' => array( - 'id' => 1, - 'join_a_id' => 1, - 'join_b_id' => 2, - 'other' => 'New data for Join A 1 Join B 2', - 'created' => static::date(), - 'updated' => static::date() - ))), - 'JoinC' => array( - 0 => array( - 'id' => 2, - 'name' => 'Join C 2', - 'created' => '2008-01-03 10:56:12', - 'updated' => '2008-01-03 10:56:12', - 'JoinAsJoinC' => array( - 'id' => 1, - 'join_a_id' => 1, - 'join_c_id' => 2, - 'other' => 'New data for Join A 1 Join C 2', - 'created' => static::date(), - 'updated' => static::date() - )))); - - $this->assertEquals($expected, $result); - } - -/** - * testSaveAll method - * - * @return void - */ - public function testSaveAll() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article', 'User'); - $TestModel = new Post(); - - $result = $TestModel->find('all'); - $this->assertEquals(3, count($result)); - $this->assertFalse(isset($result[3])); - - $TestModel->saveAll(array( - 'Post' => array( - 'title' => 'Post with Author', - 'body' => 'This post will be saved with an author' - ), - 'Author' => array( - 'user' => 'bob', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf90' - ))); - - $result = $TestModel->find('all'); - $expected = array( - 'Post' => array( - 'id' => '4', - 'author_id' => '5', - 'title' => 'Post with Author', - 'body' => 'This post will be saved with an author', - 'published' => 'N' - ), - 'Author' => array( - 'id' => '5', - 'user' => 'bob', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf90', - 'test' => 'working' - )); - $this->assertEquals(static::date(), $result[3]['Post']['created']); - $this->assertEquals(static::date(), $result[3]['Post']['updated']); - $this->assertEquals(static::date(), $result[3]['Author']['created']); - $this->assertEquals(static::date(), $result[3]['Author']['updated']); - unset($result[3]['Post']['created'], $result[3]['Post']['updated']); - unset($result[3]['Author']['created'], $result[3]['Author']['updated']); - $this->assertEquals($expected, $result[3]); - $this->assertEquals(4, count($result)); - - $TestModel->deleteAll(true); - $this->assertEquals(array(), $TestModel->find('all')); - - // SQLite seems to reset the PK counter when that happens, so we need this to make the tests pass - $this->db->truncate($TestModel); - - $TestModel->saveAll(array( - array( - 'title' => 'Multi-record post 1', - 'body' => 'First multi-record post', - 'author_id' => 2 - ), - array( - 'title' => 'Multi-record post 2', - 'body' => 'Second multi-record post', - 'author_id' => 2 - ))); - - $result = $TestModel->find('all', array( - 'recursive' => -1, - 'order' => 'Post.id ASC' - )); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '2', - 'title' => 'Multi-record post 1', - 'body' => 'First multi-record post', - 'published' => 'N' - )), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '2', - 'title' => 'Multi-record post 2', - 'body' => 'Second multi-record post', - 'published' => 'N' - ))); - $this->assertEquals(static::date(), $result[0]['Post']['created']); - $this->assertEquals(static::date(), $result[0]['Post']['updated']); - $this->assertEquals(static::date(), $result[1]['Post']['created']); - $this->assertEquals(static::date(), $result[1]['Post']['updated']); - unset($result[0]['Post']['created'], $result[0]['Post']['updated']); - unset($result[1]['Post']['created'], $result[1]['Post']['updated']); - $this->assertEquals($expected, $result); - - $TestModel = new Comment(); - $result = $TestModel->saveAll(array( - 'Comment' => array( - 'article_id' => 2, - 'user_id' => 2, - 'comment' => 'New comment with attachment', - 'published' => 'Y' - ), - 'Attachment' => array( - 'attachment' => 'some_file.tgz' - ))); - $this->assertFalse(empty($result)); - - $result = $TestModel->find('all'); - $expected = array( - 'id' => '7', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'New comment with attachment', - 'published' => 'Y' - ); - $this->assertEquals(static::date(), $result[6]['Comment']['created']); - $this->assertEquals(static::date(), $result[6]['Comment']['updated']); - unset($result[6]['Comment']['created'], $result[6]['Comment']['updated']); - $this->assertEquals($expected, $result[6]['Comment']); - - $expected = array( - 'id' => '2', - 'comment_id' => '7', - 'attachment' => 'some_file.tgz' - ); - $this->assertEquals(static::date(), $result[6]['Attachment']['created']); - $this->assertEquals(static::date(), $result[6]['Attachment']['updated']); - unset($result[6]['Attachment']['created'], $result[6]['Attachment']['updated']); - $this->assertEquals($expected, $result[6]['Attachment']); - } - -/** - * Test SaveAll with Habtm relations - * - * @return void - */ - public function testSaveAllHabtm() { - $this->loadFixtures('Article', 'Tag', 'Comment', 'User', 'ArticlesTag'); - $data = array( - 'Article' => array( - 'user_id' => 1, - 'title' => 'Article Has and belongs to Many Tags' - ), - 'Tag' => array( - 'Tag' => array(1, 2) - ), - 'Comment' => array( - array( - 'comment' => 'Article comment', - 'user_id' => 1 - ))); - $Article = new Article(); - $result = $Article->saveAll($data); - $this->assertFalse(empty($result)); - - $result = $Article->read(); - $this->assertEquals(2, count($result['Tag'])); - $this->assertEquals('tag1', $result['Tag'][0]['tag']); - $this->assertEquals(1, count($result['Comment'])); - $this->assertEquals(1, count($result['Comment'][0]['comment'])); - } - -/** - * Test SaveAll with Habtm relations and extra join table fields - * - * @return void - */ - public function testSaveAllHabtmWithExtraJoinTableFields() { - $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - - $data = array( - 'Something' => array( - 'id' => 4, - 'title' => 'Extra Fields', - 'body' => 'Extra Fields Body', - 'published' => '1' - ), - 'SomethingElse' => array( - array('something_else_id' => 1, 'doomed' => '1'), - array('something_else_id' => 2, 'doomed' => '0'), - array('something_else_id' => 3, 'doomed' => '1') - ) - ); - - $Something = new Something(); - $result = $Something->saveAll($data); - $this->assertFalse(empty($result)); - $result = $Something->read(); - - $this->assertEquals(3, count($result['SomethingElse'])); - $this->assertTrue(Set::matches('/Something[id=4]', $result)); - - $this->assertTrue(Set::matches('/SomethingElse[id=1]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=1]/JoinThing[something_else_id=1]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=1]/JoinThing[doomed=1]', $result)); - - $this->assertTrue(Set::matches('/SomethingElse[id=2]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=2]/JoinThing[something_else_id=2]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=2]/JoinThing[doomed=0]', $result)); - - $this->assertTrue(Set::matches('/SomethingElse[id=3]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=3]/JoinThing[something_else_id=3]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=3]/JoinThing[doomed=1]', $result)); - } - -/** - * testSaveAllHasOne method - * - * @return void - */ - public function testSaveAllHasOne() { - $model = new Comment(); - $model->deleteAll(true); - $this->assertEquals(array(), $model->find('all')); - - $model->Attachment->deleteAll(true); - $this->assertEquals(array(), $model->Attachment->find('all')); - - $this->assertTrue($model->saveAll(array( - 'Comment' => array( - 'comment' => 'Comment with attachment', - 'article_id' => 1, - 'user_id' => 1 - ), - 'Attachment' => array( - 'attachment' => 'some_file.zip' - )))); - $result = $model->find('all', array('fields' => array( - 'Comment.id', 'Comment.comment', 'Attachment.id', - 'Attachment.comment_id', 'Attachment.attachment' - ))); - $expected = array(array( - 'Comment' => array( - 'id' => '1', - 'comment' => 'Comment with attachment' - ), - 'Attachment' => array( - 'id' => '1', - 'comment_id' => '1', - 'attachment' => 'some_file.zip' - ))); - $this->assertEquals($expected, $result); - - $model->Attachment->bindModel(array('belongsTo' => array('Comment')), false); - $data = array( - 'Comment' => array( - 'comment' => 'Comment with attachment', - 'article_id' => 1, - 'user_id' => 1 - ), - 'Attachment' => array( - 'attachment' => 'some_file.zip' - )); - $this->assertTrue($model->saveAll($data, array('validate' => 'first'))); - } - -/** - * testSaveAllBelongsTo method - * - * @return void - */ - public function testSaveAllBelongsTo() { - $model = new Comment(); - $model->deleteAll(true); - $this->assertEquals(array(), $model->find('all')); - - $model->Article->deleteAll(true); - $this->assertEquals(array(), $model->Article->find('all')); - - $this->assertTrue($model->saveAll(array( - 'Comment' => array( - 'comment' => 'Article comment', - 'article_id' => 1, - 'user_id' => 1 - ), - 'Article' => array( - 'title' => 'Model Associations 101', - 'user_id' => 1 - )))); - $result = $model->find('all', array('fields' => array( - 'Comment.id', 'Comment.comment', 'Comment.article_id', 'Article.id', 'Article.title' - ))); - $expected = array(array( - 'Comment' => array( - 'id' => '1', - 'article_id' => '1', - 'comment' => 'Article comment' - ), - 'Article' => array( - 'id' => '1', - 'title' => 'Model Associations 101' - ))); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllHasOneValidation method - * - * @return void - */ - public function testSaveAllHasOneValidation() { - $model = new Comment(); - $model->deleteAll(true); - $this->assertEquals(array(), $model->find('all')); - - $model->Attachment->deleteAll(true); - $this->assertEquals(array(), $model->Attachment->find('all')); - - $model->validate = array('comment' => 'notEmpty'); - $model->Attachment->validate = array('attachment' => 'notEmpty'); - $model->Attachment->bindModel(array('belongsTo' => array('Comment'))); - - $result = $model->saveAll( - array( - 'Comment' => array( - 'comment' => '', - 'article_id' => 1, - 'user_id' => 1 - ), - 'Attachment' => array('attachment' => '') - ), - array('validate' => 'first') - ); - $this->assertEquals(false, $result); - $expected = array( - 'comment' => array('The provided value is invalid'), - 'Attachment' => array( - 'attachment' => array('The provided value is invalid') - ) - ); - $this->assertEquals($expected, $model->validationErrors); - $this->assertEquals($expected['Attachment'], $model->Attachment->validationErrors); - } - -/** - * testSaveAllAtomic method - * - * @return void - */ - public function testSaveAllAtomic() { - $this->loadFixtures('Article', 'User', 'Comment'); - $TestModel = new Article(); - - $result = $TestModel->saveAll(array( - 'Article' => array( - 'title' => 'Post with Author', - 'body' => 'This post will be saved with an author', - 'user_id' => 2 - ), - 'Comment' => array( - array('comment' => 'First new comment', 'user_id' => 2)) - ), array('atomic' => false)); - - $this->assertSame($result, array('Article' => true, 'Comment' => array(true))); - - $result = $TestModel->saveAll(array( - array( - 'id' => '1', - 'title' => 'Baleeted First Post', - 'body' => 'Baleeted!', - 'published' => 'N' - ), - array( - 'id' => '2', - 'title' => 'Just update the title' - ), - array( - 'title' => 'Creating a fourth post', - 'body' => 'Fourth post body', - 'user_id' => 2 - ) - ), array('atomic' => false)); - $this->assertSame($result, array(true, true, true)); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => 'First new comment', - 'published' => 'Y', - 'user_id' => 1 - ), - array( - 'comment' => 'Second new comment', - 'published' => 'Y', - 'user_id' => 2 - )) - ), array('validate' => true, 'atomic' => false)); - $this->assertSame($result, array('Article' => true, 'Comment' => array(true, true))); - - $TestModel->validate = array( - 'title' => 'notEmpty', - 'author_id' => 'numeric' - ); - $result = $TestModel->saveAll(array( - array( - 'id' => '1', - 'title' => 'Un-Baleeted First Post', - 'body' => 'Not Baleeted!', - 'published' => 'Y' - ), - array( - 'id' => '2', - 'title' => '', - 'body' => 'Trying to get away with an empty title' - ) - ), array('validate' => true, 'atomic' => false)); - $this->assertSame(array(true, false), $result); - } - -/** - * testSaveAllDeepAssociated method - * - * @return void - */ - public function testSaveAllDeepAssociated() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->hasAndBelongsToMany = array(); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), array('deep' => true)); - $this->assertTrue($result); - - $result = $TestModel->findById(2); - $expected = array( - 'First Comment for Second Article', - 'Second Comment for Second Article', - 'First new comment', - 'Second new comment' - ); - $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); - $this->assertEquals($expected, $result); - - $result = $TestModel->Comment->User->field('id', array('user' => 'newuser', 'password' => 'newuserpass')); - $this->assertEquals(5, $result); - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsaved')) - ) - ), array('deep' => true)); - $this->assertTrue($result); - - $result = $TestModel->findById(2); - $expected = array( - 'First Comment for Second Article', - 'Second Comment for Second Article', - 'First new comment', - 'Second new comment', - 'Third new comment', - 'Fourth new comment' - ); - $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); - $this->assertEquals($expected, $result); - - $result = $TestModel->Comment->Attachment->field('id', array('attachment' => 'deepsaved')); - $this->assertEquals(2, $result); - $data = array( - 'Attachment' => array( - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - 'user_id' => 5, - 'Article' => array( - 'title' => 'First Article deepsave insert', - 'body' => 'First Article Body deepsave insert', - 'User' => array( - 'user' => '', - 'password' => 'magic' - ), - ), - ) - ); - - $TestModel->Comment->Attachment->create(); - $result = $TestModel->Comment->Attachment->saveAll($data, array('deep' => true)); - $this->assertFalse($result); - - $expected = array('User' => array('user' => array('The provided value is invalid'))); - $this->assertEquals($expected, $TestModel->validationErrors); - - $data['Comment']['Article']['User']['user'] = 'deepsave'; - $TestModel->Comment->Attachment->create(); - $result = $TestModel->Comment->Attachment->saveAll($data, array('deep' => true)); - $this->assertTrue($result); - - $result = $TestModel->Comment->Attachment->findById($TestModel->Comment->Attachment->id); - $expected = array( - 'Attachment' => array( - 'id' => '3', - 'comment_id' => '11', - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'id' => '11', - 'article_id' => '4', - 'user_id' => '5', - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - ) - ); - unset($result['Attachment']['created'], $result['Attachment']['updated']); - $this->assertEquals($expected['Attachment'], $result['Attachment']); - - unset($result['Comment']['created'], $result['Comment']['updated']); - $this->assertEquals($expected['Comment'], $result['Comment']); - - $result = $TestModel->findById($result['Comment']['article_id']); - $expected = array( - 'Article' => array( - 'id' => '4', - 'user_id' => '6', - 'title' => 'First Article deepsave insert', - 'body' => 'First Article Body deepsave insert', - 'published' => 'N', - ), - 'User' => array( - 'id' => '6', - 'user' => 'deepsave', - 'password' => 'magic', - ), - 'Comment' => array( - array( - 'id' => '11', - 'article_id' => '4', - 'user_id' => '5', - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - ) - ) - ); - unset( - $result['Article']['created'], $result['Article']['updated'], - $result['User']['created'], $result['User']['updated'], - $result['Comment'][0]['created'], $result['Comment'][0]['updated'] - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllDeepMany - * tests the validate methods with deeper recursive data - * - * @return void - */ - public function testSaveAllDeepMany() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->hasAndBelongsToMany = array(); - - $data = array( - array( - 'Article' => array('id' => 1), - 'Comment' => array( - array('comment' => 'First comment deepsaved article 1', 'published' => 'Y', 'User' => array('user' => 'savemany', 'password' => 'manysaved')), - array('comment' => 'Second comment deepsaved article 1', 'published' => 'Y', 'user_id' => 2) - ) - ), - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First comment deepsaved article 2', 'published' => 'Y', 'User' => array('user' => 'savemore', 'password' => 'moresaved')), - array('comment' => 'Second comment deepsaved article 2', 'published' => 'Y', 'user_id' => 2) - ) - ) - ); - $result = $TestModel->saveAll($data, array('deep' => true)); - $this->assertTrue($result); - - $data = array( - array( - 'id' => 1, 'body' => '', - 'Comment' => array( - array('comment' => '', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'manysaved')), - array('comment' => 'Second comment deepsaved article 1', 'published' => 'Y', 'user_id' => 2) - ) - ), - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First comment deepsaved article 2', 'published' => 'Y', 'User' => array('user' => 'savemore', 'password' => '')), - array('comment' => '', 'published' => 'Y', 'user_id' => 2) - ) - ) - ); - $TestModel->Comment->validate['comment'] = 'notEmpty'; - $result = $TestModel->saveAll($data, array('deep' => true)); - $this->assertFalse($result); - - $expected = array( - 0 => array( - 'body' => array('The provided value is invalid'), - 'Comment' => array( - 0 => array( - 'comment' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ), - 1 => array( - 'Comment' => array( - 0 => array( - 'User' => array( - 'password' => array('The provided value is invalid') - ) - ), - 1 => array( - 'comment' => array('The provided value is invalid') - ) - ) - ) - ); - $result = $TestModel->validationErrors; - $this->assertSame($expected, $result); - } -/** - * testSaveAllDeepValidateOnly - * tests the validate methods with deeper recursive data - * - * @return void - */ - public function testSaveAllDeepValidateOnly() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->Attachment->validate['attachment'] = 'notEmpty'; - $TestModel->Comment->validate['comment'] = 'notEmpty'; - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), - array('validate' => 'only', 'deep' => true) - ); - $this->assertTrue($result); - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), - array('validate' => 'only', 'deep' => true) - ); - $this->assertFalse($result); - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => 'newuser', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), - array('validate' => 'only', 'atomic' => false, 'deep' => true) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - true - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), - array('validate' => 'only', 'atomic' => false, 'deep' => true) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - false, - true - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsaved')) - ) - ), - array('validate' => 'only', 'deep' => true) - ); - $this->assertTrue($result); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) - ) - ), - array('validate' => 'only', 'deep' => true) - ); - $this->assertFalse($result); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsave')) - ) - ), - array('validate' => 'only', 'atomic' => false, 'deep' => true) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - true - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) - ) - ), - array('validate' => 'only', 'atomic' => false, 'deep' => true) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - false - ) - ); - $this->assertSame($expected, $result); - - $expected = array( - 'Comment' => array( - 1 => array( - 'Attachment' => array( - 'attachment' => array('The provided value is invalid') - ) - ) - ) - ); - $result = $TestModel->validationErrors; - $this->assertSame($expected, $result); - - $data = array( - 'Attachment' => array( - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - 'user_id' => 5, - 'Article' => array( - 'title' => 'First Article deepsave insert', - 'body' => 'First Article Body deepsave insert', - 'User' => array( - 'user' => 'deepsave', - 'password' => 'magic' - ), - ), - ) - ); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertTrue($result); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $expected = array( - 'Attachment' => true, - 'Comment' => true - ); - $this->assertSame($expected, $result); - - $data = array( - 'Attachment' => array( - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - 'user_id' => 5, - 'Article' => array( - 'title' => 'First Article deepsave insert', - 'body' => 'First Article Body deepsave insert', - 'User' => array( - 'user' => '', - 'password' => 'magic' - ), - ), - ) - ); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array( - 'Comment' => array( - 'Article' => array( - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $expected = array( - 'Attachment' => true, - 'Comment' => false - ); - $this->assertEquals($expected, $result); - - $data['Comment']['Article']['body'] = ''; - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array( - 'Comment' => array( - 'Article' => array( - 'body' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $expected = array( - 'Attachment' => true, - 'Comment' => false - ); - $this->assertEquals($expected, $result); - - $data['Comment']['comment'] = ''; - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array( - 'Comment' => array( - 'comment' => array('The provided value is invalid'), - 'Article' => array( - 'body' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $expected = array( - 'Attachment' => true, - 'Comment' => false - ); - $this->assertEquals($expected, $result); - - $data['Attachment']['attachment'] = ''; - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => true)); - $this->assertFalse($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array( - 'attachment' => array('The provided value is invalid'), - 'Comment' => array( - 'comment' => array('The provided value is invalid'), - 'Article' => array( - 'body' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->Comment->validationErrors; - $expected = array( - 'comment' => array('The provided value is invalid'), - 'Article' => array( - 'body' => array('The provided value is invalid'), - 'User' => array( - 'user' => array('The provided value is invalid') - ) - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => true)); - $expected = array( - 'Attachment' => false, - 'Comment' => false - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllNotDeepAssociated method - * test that only directly associated data gets saved - * - * @return void - */ - public function testSaveAllNotDeepAssociated() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->hasAndBelongsToMany = array(); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => 'First new comment', 'published' => 'Y', 'user_id' => 2, - 'User' => array('user' => 'newuser', 'password' => 'newuserpass') - ), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), array('deep' => false)); - $this->assertTrue($result); - - $result = $TestModel->Comment->User->field('id', array('user' => 'newuser', 'password' => 'newuserpass')); - $this->assertFalse($result); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 4), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => 'deepsaved')) - ) - ), array('deep' => false)); - $this->assertTrue($result); - - $result = $TestModel->Comment->Attachment->field('id', array('attachment' => 'deepsaved')); - $this->assertFalse($result); - - $data = array( - 'Attachment' => array( - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - 'user_id' => 4, - 'article_id' => 1, - 'Article' => array( - 'title' => 'First Article deepsave insert', - 'body' => 'First Article Body deepsave insert', - 'User' => array( - 'user' => 'deepsave', - 'password' => 'magic' - ), - ), - ) - ); - $expected = $TestModel->User->find('count'); - - $TestModel->Comment->Attachment->create(); - $result = $TestModel->Comment->Attachment->saveAll($data, array('deep' => false)); - $this->assertTrue($result); - - $result = $TestModel->User->find('count'); - $this->assertEquals($expected, $result); - - $result = $TestModel->Comment->Attachment->findById($TestModel->Comment->Attachment->id); - $expected = array( - 'Attachment' => array( - 'id' => '2', - 'comment_id' => '11', - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'id' => '11', - 'article_id' => 1, - 'user_id' => '4', - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - ) - ); - unset($result['Attachment']['created'], $result['Attachment']['updated']); - $this->assertEquals($expected['Attachment'], $result['Attachment']); - - unset($result['Comment']['created'], $result['Comment']['updated']); - $this->assertEquals($expected['Comment'], $result['Comment']); - } - -/** - * testSaveAllNotDeepMany - * tests the save methods to not save deeper recursive data - * - * @return void - */ - public function testSaveAllNotDeepMany() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->hasAndBelongsToMany = array(); - - $data = array( - array( - 'id' => 1, - 'body' => '', - 'Comment' => array( - array('comment' => '', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'manysaved')), - array('comment' => 'Second comment deepsaved article 1', 'published' => 'Y', 'user_id' => 2) - ) - ), - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First comment deepsaved article 2', 'published' => 'Y', 'User' => array('user' => 'savemore', 'password' => '')), - array('comment' => '', 'published' => 'Y', 'user_id' => 2) - ) - ) - ); - $TestModel->Comment->validate['comment'] = 'notEmpty'; - $result = $TestModel->saveAll($data, array('deep' => false)); - $this->assertFalse($result); - - $expected = array( - 0 => array( - 'body' => array('The provided value is invalid') - ) - ); - $result = $TestModel->validationErrors; - $this->assertSame($expected, $result); - - $data = array( - array( - 'Article' => array('id' => 1, 'body' => 'Ignore invalid comment'), - 'Comment' => array( - array('comment' => '', 'published' => 'Y', 'user_id' => 2) - ) - ), - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => '', 'published' => 'Y', 'user_id' => 2) - ) - ) - ); - $result = $TestModel->saveAll($data, array('deep' => false)); - $this->assertTrue($result); - } -/** - * testSaveAllNotDeepValidateOnly - * tests the validate methods to not validate deeper recursive data - * - * @return void - */ - public function testSaveAllNotDeepValidateOnly() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->Attachment->validate['attachment'] = 'notEmpty'; - $TestModel->Comment->validate['comment'] = 'notEmpty'; - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2, 'body' => ''), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), - array('validate' => 'only', 'deep' => false) - ); - $this->assertFalse($result); - - $expected = array('body' => array('The provided value is invalid')); - $result = $TestModel->validationErrors; - $this->assertSame($expected, $result); - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2, 'body' => 'Ignore invalid user data'), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), - array('validate' => 'only', 'deep' => false) - ); - $this->assertTrue($result); - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2, 'body' => 'Ignore invalid user data'), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'User' => array('user' => '', 'password' => 'newuserpass')), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ), - array('validate' => 'only', 'atomic' => false, 'deep' => false) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - true - ) - ); - $this->assertSame($expected, $result); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2, 'body' => 'Ignore invalid attachment data'), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) - ) - ), - array('validate' => 'only', 'deep' => false) - ); - $this->assertTrue($result); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2, 'body' => 'Ignore invalid attachment data'), - 'Comment' => array( - array('comment' => 'Third new comment', 'published' => 'Y', 'user_id' => 5), - array('comment' => 'Fourth new comment', 'published' => 'Y', 'user_id' => 2, 'Attachment' => array('attachment' => '')) - ) - ), - array('validate' => 'only', 'atomic' => false, 'deep' => false) - ); - $expected = array( - 'Article' => true, - 'Comment' => array( - true, - true - ) - ); - $this->assertSame($expected, $result); - - $expected = array(); - $result = $TestModel->validationErrors; - $this->assertSame($expected, $result); - - $data = array( - 'Attachment' => array( - 'attachment' => 'deepsave insert', - ), - 'Comment' => array( - 'comment' => 'First comment deepsave insert', - 'published' => 'Y', - 'user_id' => 5, - 'Article' => array( - 'title' => 'First Article deepsave insert ignored', - 'body' => 'First Article Body deepsave insert', - 'User' => array( - 'user' => '', - 'password' => 'magic' - ), - ), - ) - ); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => false)); - $this->assertTrue($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array(); - $this->assertSame($expected, $result); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); - $expected = array( - 'Attachment' => true, - 'Comment' => true - ); - $this->assertEquals($expected, $result); - - $data['Comment']['Article']['body'] = ''; - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'deep' => false)); - $this->assertTrue($result); - - $result = $TestModel->Comment->Attachment->validationErrors; - $expected = array(); - $this->assertSame($expected, $result); - - $result = $TestModel->Comment->Attachment->saveAll($data, array('validate' => 'only', 'atomic' => false, 'deep' => false)); - $expected = array( - 'Attachment' => true, - 'Comment' => true - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllHasMany method - * - * @return void - */ - public function testSaveAllHasMany() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $TestModel->hasMany['Comment']['order'] = array('Comment.created' => 'ASC'); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - )); - $this->assertFalse(empty($result)); - - $result = $TestModel->findById(2); - $expected = array( - 'First Comment for Second Article', - 'Second Comment for Second Article', - 'First new comment', - 'Second new comment' - ); - $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); - $this->assertEquals($expected, $result); - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => 'Third new comment', - 'published' => 'Y', - 'user_id' => 1 - ))), - array('atomic' => false) - ); - $this->assertFalse(empty($result)); - - $result = $TestModel->findById(2); - $expected = array( - 'First Comment for Second Article', - 'Second Comment for Second Article', - 'First new comment', - 'Second new comment', - 'Third new comment' - ); - $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); - $this->assertEquals($expected, $result); - - $TestModel->beforeSaveReturn = false; - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => 'Fourth new comment', - 'published' => 'Y', - 'user_id' => 1 - ))), - array('atomic' => false) - ); - $this->assertEquals(array('Article' => false), $result); - - $result = $TestModel->findById(2); - $expected = array( - 'First Comment for Second Article', - 'Second Comment for Second Article', - 'First new comment', - 'Second new comment', - 'Third new comment' - ); - $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment'); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllHasManyValidation method - * - * @return void - */ - public function testSaveAllHasManyValidation() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->validate = array('comment' => 'notEmpty'); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => '', 'published' => 'Y', 'user_id' => 1), - ) - ), array('validate' => true)); - $this->assertFalse($result); - - $expected = array('Comment' => array( - array('comment' => array('The provided value is invalid')) - )); - $this->assertEquals($expected, $TestModel->validationErrors); - $expected = array( - array('comment' => array('The provided value is invalid')) - ); - $this->assertEquals($expected, $TestModel->Comment->validationErrors); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1 - )) - ), array('validate' => 'first')); - $this->assertFalse($result); - } - -/** - * test saveAll with transactions and ensure there is no missing rollback. - * - * @return void - */ - public function testSaveAllManyRowsTransactionNoRollback() { - $this->loadFixtures('Post'); - - $this->getMock('DboSource', array('connect', 'rollback', 'describe'), array(), 'MockTransactionDboSource'); - $db = ConnectionManager::create('mock_transaction', array( - 'datasource' => 'MockTransactionDboSource', - )); - - $db->expects($this->once()) - ->method('describe') - ->will($this->returnValue(array())); - $db->expects($this->once())->method('rollback'); - - $Post = new Post('mock_transaction'); - - $Post->validate = array( - 'title' => array('rule' => array('notEmpty')) - ); - - $data = array( - array('author_id' => 1, 'title' => 'New Fourth Post'), - array('author_id' => 1, 'title' => '') - ); - $Post->saveAll($data, array('atomic' => true)); - } - -/** - * test saveAll with transactions and ensure there is no missing rollback. - * - * @return void - */ - public function testSaveAllAssociatedTransactionNoRollback() { - $testDb = ConnectionManager::getDataSource('test'); - - $this->getMock( - 'DboSource', - array('connect', 'rollback', 'describe', 'create', 'update', 'begin'), - array(), - 'MockTransactionAssociatedDboSource' - ); - $db = ConnectionManager::create('mock_transaction_assoc', array( - 'datasource' => 'MockTransactionAssociatedDboSource', - )); - $this->mockObjects[] = $db; - $db->columns = $testDb->columns; - - $db->expects($this->once())->method('rollback'); - $db->expects($this->any())->method('describe') - ->will($this->returnValue(array( - 'id' => array('type' => 'integer', 'length' => 11), - 'title' => array('type' => 'string'), - 'body' => array('type' => 'text'), - 'published' => array('type' => 'string') - ))); - - $Post = new Post(); - $Post->useDbConfig = 'mock_transaction_assoc'; - $Post->Author->useDbConfig = 'mock_transaction_assoc'; - - $Post->Author->validate = array( - 'user' => array('rule' => array('notEmpty')) - ); - - $data = array( - 'Post' => array( - 'title' => 'New post', - 'body' => 'Content', - 'published' => 'Y' - ), - 'Author' => array( - 'user' => '', - 'password' => "sekret" - ) - ); - $Post->saveAll($data, array('validate' => true)); - } - -/** - * test saveAll with nested saveAll call. - * - * @return void - */ - public function testSaveAllNestedSaveAll() { - $this->loadFixtures('Sample'); - $TransactionTestModel = new TransactionTestModel(); - - $data = array( - array('apple_id' => 1, 'name' => 'sample5'), - ); - - $this->assertTrue($TransactionTestModel->saveAll($data, array('atomic' => true))); - } - -/** - * testSaveAllTransaction method - * - * @return void - */ - public function testSaveAllTransaction() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel = new Post(); - - $TestModel->validate = array('title' => 'notEmpty'); - $data = array( - array('author_id' => 1, 'title' => 'New Fourth Post'), - array('author_id' => 1, 'title' => 'New Fifth Post'), - array('author_id' => 1, 'title' => '') - ); - $this->assertFalse($TestModel->saveAll($data)); - - $result = $TestModel->find('all', array('recursive' => -1)); - $expected = array( - array('Post' => array( - 'id' => '1', - 'author_id' => 1, - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - array('Post' => array( - 'id' => '2', - 'author_id' => 3, - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - )), - array('Post' => array( - 'id' => '3', - 'author_id' => 1, - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ))); - - if (count($result) != 3) { - // Database doesn't support transactions - $expected[] = array( - 'Post' => array( - 'id' => '4', - 'author_id' => 1, - 'title' => 'New Fourth Post', - 'body' => null, - 'published' => 'N', - 'created' => static::date(), - 'updated' => static::date() - )); - - $expected[] = array( - 'Post' => array( - 'id' => '5', - 'author_id' => 1, - 'title' => 'New Fifth Post', - 'body' => null, - 'published' => 'N', - 'created' => static::date(), - 'updated' => static::date() - )); - - $this->assertEquals($expected, $result); - // Skip the rest of the transactional tests - return; - } - - $this->assertEquals($expected, $result); - - $data = array( - array('author_id' => 1, 'title' => 'New Fourth Post'), - array('author_id' => 1, 'title' => ''), - array('author_id' => 1, 'title' => 'New Sixth Post') - ); - $this->assertFalse($TestModel->saveAll($data)); - - $result = $TestModel->find('all', array('recursive' => -1)); - $expected = array( - array('Post' => array( - 'id' => '1', - 'author_id' => 1, - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - array('Post' => array( - 'id' => '2', - 'author_id' => 3, - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - )), - array('Post' => array( - 'id' => '3', - 'author_id' => 1, - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ))); - - if (count($result) != 3) { - // Database doesn't support transactions - $expected[] = array( - 'Post' => array( - 'id' => '4', - 'author_id' => 1, - 'title' => 'New Fourth Post', - 'body' => 'Third Post Body', - 'published' => 'N', - 'created' => static::date(), - 'updated' => static::date() - )); - - $expected[] = array( - 'Post' => array( - 'id' => '5', - 'author_id' => 1, - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'N', - 'created' => static::date(), - 'updated' => static::date() - )); - } - $this->assertEquals($expected, $result); - - $TestModel->validate = array('title' => 'notEmpty'); - $data = array( - array('author_id' => 1, 'title' => 'New Fourth Post'), - array('author_id' => 1, 'title' => 'New Fifth Post'), - array('author_id' => 1, 'title' => 'New Sixth Post') - ); - $this->assertTrue($TestModel->saveAll($data)); - - $result = $TestModel->find('all', array( - 'recursive' => -1, - 'fields' => array('author_id', 'title', 'body', 'published'), - 'order' => array('Post.created' => 'ASC') - )); - - $expected = array( - array('Post' => array( - 'author_id' => 1, - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y' - )), - array('Post' => array( - 'author_id' => 3, - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y' - )), - array('Post' => array( - 'author_id' => 1, - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y' - )), - array('Post' => array( - 'author_id' => 1, - 'title' => 'New Fourth Post', - 'body' => '', - 'published' => 'N' - )), - array('Post' => array( - 'author_id' => 1, - 'title' => 'New Fifth Post', - 'body' => '', - 'published' => 'N' - )), - array('Post' => array( - 'author_id' => 1, - 'title' => 'New Sixth Post', - 'body' => '', - 'published' => 'N' - ))); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllValidation method - * - * @return void - */ - public function testSaveAllValidation() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel = new Post(); - - $data = array( - array( - 'id' => '1', - 'title' => 'Baleeted First Post', - 'body' => 'Baleeted!', - 'published' => 'N' - ), - array( - 'id' => '2', - 'title' => 'Just update the title' - ), - array( - 'title' => 'Creating a fourth post', - 'body' => 'Fourth post body', - 'author_id' => 2 - )); - - $this->assertTrue($TestModel->saveAll($data)); - - $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '1', - 'title' => 'Baleeted First Post', - 'body' => 'Baleeted!', - 'published' => 'N', - 'created' => '2007-03-18 10:39:23' - )), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '3', - 'title' => 'Just update the title', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23' - )), - array( - 'Post' => array( - 'id' => '3', - 'author_id' => '1', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - )), - array( - 'Post' => array( - 'id' => '4', - 'author_id' => '2', - 'title' => 'Creating a fourth post', - 'body' => 'Fourth post body', - 'published' => 'N' - ))); - $this->assertEquals(static::date(), $result[0]['Post']['updated']); - $this->assertEquals(static::date(), $result[1]['Post']['updated']); - $this->assertEquals(static::date(), $result[3]['Post']['created']); - $this->assertEquals(static::date(), $result[3]['Post']['updated']); - unset($result[0]['Post']['updated'], $result[1]['Post']['updated']); - unset($result[3]['Post']['created'], $result[3]['Post']['updated']); - $this->assertEquals($expected, $result); - - $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); - $data = array( - array( - 'id' => '1', - 'title' => 'Un-Baleeted First Post', - 'body' => 'Not Baleeted!', - 'published' => 'Y' - ), - array( - 'id' => '2', - 'title' => '', - 'body' => 'Trying to get away with an empty title' - )); - $result = $TestModel->saveAll($data); - $this->assertFalse($result); - - $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); - $errors = array(1 => array('title' => array('The provided value is invalid'))); - $transactionWorked = Set::matches('/Post[1][title=Baleeted First Post]', $result); - if (!$transactionWorked) { - $this->assertTrue(Set::matches('/Post[1][title=Un-Baleeted First Post]', $result)); - $this->assertTrue(Set::matches('/Post[2][title=Just update the title]', $result)); - } - - $this->assertEquals($errors, $TestModel->validationErrors); - - $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); - $data = array( - array( - 'id' => '1', - 'title' => 'Un-Baleeted First Post', - 'body' => 'Not Baleeted!', - 'published' => 'Y' - ), - array( - 'id' => '2', - 'title' => '', - 'body' => 'Trying to get away with an empty title' - )); - $result = $TestModel->saveAll($data, array('validate' => true, 'atomic' => false)); - $this->assertEquals(array(true, false), $result); - $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); - $errors = array(1 => array('title' => array('The provided value is invalid'))); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '1', - 'title' => 'Un-Baleeted First Post', - 'body' => 'Not Baleeted!', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23' - ) - ), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '3', - 'title' => 'Just update the title', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23' - ) - ), - array( - 'Post' => array( - 'id' => '3', - 'author_id' => '1', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ) - ), - array( - 'Post' => array( - 'id' => '4', - 'author_id' => '2', - 'title' => 'Creating a fourth post', - 'body' => 'Fourth post body', - 'published' => 'N' - ) - ) - ); - - $this->assertEquals(static::date(), $result[0]['Post']['updated']); - $this->assertEquals(static::date(), $result[1]['Post']['updated']); - $this->assertEquals(static::date(), $result[3]['Post']['updated']); - $this->assertEquals(static::date(), $result[3]['Post']['created']); - unset( - $result[0]['Post']['updated'], $result[1]['Post']['updated'], - $result[3]['Post']['updated'], $result[3]['Post']['created'] - ); - $this->assertEquals($expected, $result); - $this->assertEquals($errors, $TestModel->validationErrors); - - $data = array( - array( - 'id' => '1', - 'title' => 'Re-Baleeted First Post', - 'body' => 'Baleeted!', - 'published' => 'N' - ), - array( - 'id' => '2', - 'title' => '', - 'body' => 'Trying to get away with an empty title' - )); - $this->assertFalse($TestModel->saveAll($data, array('validate' => 'first'))); - - $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); - unset( - $result[0]['Post']['updated'], $result[1]['Post']['updated'], - $result[3]['Post']['updated'], $result[3]['Post']['created'] - ); - $this->assertEquals($expected, $result); - $this->assertEquals($errors, $TestModel->validationErrors); - } - -/** - * testSaveAllValidationOnly method - * - * @return void - */ - public function testSaveAllValidationOnly() { - $this->loadFixtures('Comment', 'Attachment'); - $TestModel = new Comment(); - $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); - - $data = array( - 'Comment' => array( - 'comment' => 'This is the comment' - ), - 'Attachment' => array( - 'attachment' => '' - ) - ); - - $result = $TestModel->saveAll($data, array('validate' => 'only')); - $this->assertFalse($result); - - $TestModel = new Article(); - $TestModel->validate = array('title' => 'notEmpty'); - $result = $TestModel->saveAll( - array( - 0 => array('title' => ''), - 1 => array('title' => 'title 1'), - 2 => array('title' => 'title 2'), - ), - array('validate' => 'only') - ); - $this->assertFalse($result); - $expected = array( - 0 => array('title' => array('The provided value is invalid')), - ); - $this->assertEquals($expected, $TestModel->validationErrors); - - $result = $TestModel->saveAll( - array( - 0 => array('title' => 'title 0'), - 1 => array('title' => ''), - 2 => array('title' => 'title 2'), - ), - array('validate' => 'only') - ); - $this->assertFalse($result); - $expected = array( - 1 => array('title' => array('The provided value is invalid')), - ); - $this->assertEquals($expected, $TestModel->validationErrors); - } - -/** - * testSaveAllValidateFirst method - * - * @return void - */ - public function testSaveAllValidateFirst() { - $this->loadFixtures('Article', 'Comment', 'Attachment', 'User', 'ArticlesTag', 'Tag'); - $model = new Article(); - $model->deleteAll(true); - - $model->Comment->validate = array('comment' => 'notEmpty'); - $result = $model->saveAll(array( - 'Article' => array( - 'title' => 'Post with Author', - 'body' => 'This post will be saved author' - ), - 'Comment' => array( - array('comment' => 'First new comment'), - array('comment' => '') - ) - ), array('validate' => 'first')); - - $this->assertFalse($result); - - $result = $model->find('all'); - $this->assertSame(array(), $result); - $expected = array('Comment' => array( - 1 => array('comment' => array('The provided value is invalid')) - )); - - $this->assertEquals($expected['Comment'], $model->Comment->validationErrors); - - $this->assertSame($model->Comment->find('count'), 0); - - $result = $model->saveAll( - array( - 'Article' => array( - 'title' => 'Post with Author', - 'body' => 'This post will be saved with an author', - 'user_id' => 2 - ), - 'Comment' => array( - array( - 'comment' => 'Only new comment', - 'user_id' => 2 - ))), - array('validate' => 'first') - ); - - $this->assertTrue($result); - - $result = $model->Comment->find('all'); - $this->assertSame(count($result), 1); - $result = Hash::extract($result, '{n}.Comment.article_id'); - $this->assertEquals(4, $result[0]); - - $model->deleteAll(true); - $data = array( - 'Article' => array( - 'title' => 'Post with Author saveAlled from comment', - 'body' => 'This post will be saved with an author', - 'user_id' => 2 - ), - 'Comment' => array( - 'comment' => 'Only new comment', 'user_id' => 2 - )); - - $result = $model->Comment->saveAll($data, array('validate' => 'first')); - $this->assertFalse(empty($result)); - - $result = $model->find('all'); - $this->assertEquals( - $result[0]['Article']['title'], - 'Post with Author saveAlled from comment' - ); - $this->assertEquals('Only new comment', $result[0]['Comment'][0]['comment']); - } - -/** - * test saveAll()'s return is correct when using atomic = false and validate = first. - * - * @return void - */ - public function testSaveAllValidateFirstAtomicFalse() { - $this->loadFixtures('Something'); - $Something = new Something(); - $invalidData = array( - array( - 'title' => 'foo', - 'body' => 'bar', - 'published' => 'baz', - ), - array( - 'body' => 3, - 'published' => 'sd', - ), - ); - $Something->create(); - $Something->validate = array( - 'title' => array( - 'rule' => 'alphaNumeric', - 'required' => true, - ), - 'body' => array( - 'rule' => 'alphaNumeric', - 'required' => true, - 'allowEmpty' => true, - ), - ); - $result = $Something->saveAll($invalidData, array( - 'atomic' => false, - 'validate' => 'first', - )); - $expected = array(true, false); - $this->assertEquals($expected, $result); - - $Something = new Something(); - $validData = array( - array( - 'title' => 'title value', - 'body' => 'body value', - 'published' => 'baz', - ), - array( - 'title' => 'valid', - 'body' => 'this body', - 'published' => 'sd', - ), - ); - $Something->create(); - $result = $Something->saveAll($validData, array( - 'atomic' => false, - 'validate' => 'first', - )); - $expected = array(true, true); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllHasManyValidationOnly method - * - * @return void - */ - public function testSaveAllHasManyValidationOnly() { - $this->loadFixtures('Article', 'Comment', 'Attachment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->validate = array('comment' => 'notEmpty'); - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'id' => 1, - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1), - array( - 'id' => 2, - 'comment' => - 'comment', - 'published' => 'Y', - 'user_id' => 1 - ))), - array('validate' => 'only') - ); - $this->assertFalse($result); - - $result = $TestModel->saveAll( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'id' => 1, - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1 - ), - array( - 'id' => 2, - 'comment' => 'comment', - 'published' => 'Y', - 'user_id' => 1 - ), - array( - 'id' => 3, - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1 - ))), - array( - 'validate' => 'only', - 'atomic' => false - )); - $expected = array( - 'Article' => true, - 'Comment' => array(false, true, false) - ); - $this->assertSame($expected, $result); - - $expected = array('Comment' => array( - 0 => array('comment' => array('The provided value is invalid')), - 2 => array('comment' => array('The provided value is invalid')) - )); - $this->assertEquals($expected, $TestModel->validationErrors); - - $expected = array( - 0 => array('comment' => array('The provided value is invalid')), - 2 => array('comment' => array('The provided value is invalid')) - ); - $this->assertEquals($expected, $TestModel->Comment->validationErrors); - } - -/** - * test that saveAll still behaves like previous versions (does not necessarily need a first argument) - * - * @return void - */ - public function testSaveAllWithSet() { - $this->loadFixtures('Article', 'Tag', 'Comment', 'User', 'ArticlesTag'); - $data = array( - 'Article' => array( - 'user_id' => 1, - 'title' => 'Article Has and belongs to Many Tags' - ), - 'Tag' => array( - 'Tag' => array(1, 2) - ), - 'Comment' => array( - array( - 'comment' => 'Article comment', - 'user_id' => 1 - ))); - $Article = new Article(); - $Article->set($data); - $result = $Article->saveAll(); - $this->assertFalse(empty($result)); - } - -/** - * test that saveAll behaves like plain save() when supplied empty data - * - * @link https://cakephp.lighthouseapp.com/projects/42648/tickets/277-test-saveall-with-validation-returns-incorrect-boolean-when-saving-empty-data - * @return void - */ - public function testSaveAllEmptyData() { - $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); - - $this->loadFixtures('Article', 'ProductUpdateAll', 'Comment', 'Attachment'); - $model = new Article(); - $result = $model->saveAll(array(), array('validate' => 'first')); - $this->assertFalse(empty($result)); - - $model = new ProductUpdateAll(); - $result = $model->saveAll(); - $this->assertFalse($result); - } - -/** - * testSaveAssociated method - * - * @return void - */ - public function testSaveAssociated() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article', 'User'); - $TestModel = new Post(); - - $result = $TestModel->find('all'); - $this->assertEquals(3, count($result)); - $this->assertFalse(isset($result[3])); - - $TestModel->saveAssociated(array( - 'Post' => array( - 'title' => 'Post with Author', - 'body' => 'This post will be saved with an author' - ), - 'Author' => array( - 'user' => 'bob', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf90' - ))); - - $result = $TestModel->find('all', array('order' => array('Post.id ' => 'ASC'))); - $expected = array( - 'Post' => array( - 'id' => '4', - 'author_id' => '5', - 'title' => 'Post with Author', - 'body' => 'This post will be saved with an author', - 'published' => 'N' - ), - 'Author' => array( - 'id' => '5', - 'user' => 'bob', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf90', - 'test' => 'working' - )); - $this->assertEquals(static::date(), $result[3]['Post']['updated']); - $this->assertEquals(static::date(), $result[3]['Post']['created']); - $this->assertEquals(static::date(), $result[3]['Author']['created']); - $this->assertEquals(static::date(), $result[3]['Author']['updated']); - unset( - $result[3]['Post']['updated'], $result[3]['Post']['created'], - $result[3]['Author']['updated'], $result[3]['Author']['created'] - ); - $this->assertEquals($expected, $result[3]); - $this->assertEquals(4, count($result)); - - $TestModel = new Comment(); - $result = $TestModel->saveAssociated(array( - 'Comment' => array( - 'article_id' => 2, - 'user_id' => 2, - 'comment' => 'New comment with attachment', - 'published' => 'Y' - ), - 'Attachment' => array( - 'attachment' => 'some_file.tgz' - ))); - $this->assertFalse(empty($result)); - - $result = $TestModel->find('all'); - $expected = array( - 'id' => '7', - 'article_id' => '2', - 'user_id' => '2', - 'comment' => 'New comment with attachment', - 'published' => 'Y' - ); - $this->assertEquals(static::date(), $result[6]['Comment']['updated']); - $this->assertEquals(static::date(), $result[6]['Comment']['created']); - unset($result[6]['Comment']['updated'], $result[6]['Comment']['created']); - $this->assertEquals($expected, $result[6]['Comment']); - - $expected = array( - 'id' => '2', - 'comment_id' => '7', - 'attachment' => 'some_file.tgz' - ); - $this->assertEquals(static::date(), $result[6]['Attachment']['updated']); - $this->assertEquals(static::date(), $result[6]['Attachment']['created']); - unset($result[6]['Attachment']['updated'], $result[6]['Attachment']['created']); - $this->assertEquals($expected, $result[6]['Attachment']); - } - -/** - * Test that validate = first, atomic = false works when associated records - * fail validation. - * - * @return void - */ - public function testSaveAssociatedAtomicFalseValidateFirstWithErrors() { - $this->loadFixtures('Comment', 'Article', 'User'); - $Article = ClassRegistry::init('Article'); - $Article->Comment->validator()->add('comment', array( - array('rule' => 'notEmpty') - )); - - $data = array( - 'Article' => array( - 'user_id' => 1, - 'title' => 'Foo', - 'body' => 'text', - 'published' => 'N' - ), - 'Comment' => array( - array( - 'user_id' => 1, - 'comment' => '', - 'published' => 'N', - ) - ), - ); - - $Article->saveAssociated( - $data, - array('validate' => 'first', 'atomic' => false) - ); - - $result = $Article->validationErrors; - $expected = array( - 'Comment' => array( - array( - 'comment' => array('The provided value is invalid') - ) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveMany method - * - * @return void - */ - public function testSaveMany() { - $this->loadFixtures('Post'); - $TestModel = new Post(); - $TestModel->deleteAll(true); - $this->assertEquals(array(), $TestModel->find('all')); - - // SQLite seems to reset the PK counter when that happens, so we need this to make the tests pass - $this->db->truncate($TestModel); - - $TestModel->saveMany(array( - array( - 'title' => 'Multi-record post 1', - 'body' => 'First multi-record post', - 'author_id' => 2 - ), - array( - 'title' => 'Multi-record post 2', - 'body' => 'Second multi-record post', - 'author_id' => 2 - ))); - - $result = $TestModel->find('all', array( - 'recursive' => -1, - 'order' => 'Post.id ASC' - )); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '2', - 'title' => 'Multi-record post 1', - 'body' => 'First multi-record post', - 'published' => 'N' - ) - ), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '2', - 'title' => 'Multi-record post 2', - 'body' => 'Second multi-record post', - 'published' => 'N' - ) - ) - ); - $this->assertEquals(static::date(), $result[0]['Post']['updated']); - $this->assertEquals(static::date(), $result[0]['Post']['created']); - $this->assertEquals(static::date(), $result[1]['Post']['updated']); - $this->assertEquals(static::date(), $result[1]['Post']['created']); - unset($result[0]['Post']['updated'], $result[0]['Post']['created']); - unset($result[1]['Post']['updated'], $result[1]['Post']['created']); - $this->assertEquals($expected, $result); - } - -/** - * Test SaveMany with validate=false. - * - * @return void - */ - public function testSaveManyValidateFalse() { - $this->loadFixtures('Post'); - $TestModel = new Post(); - $TestModel->deleteAll(true); - $data = array( - array('id' => 1, 'author_id' => 1, 'title' => 'hi'), - array('id' => 2, 'author_id' => 1, 'title' => 'bye') - ); - $result = $TestModel->saveAll($data, array('validate' => false)); - $this->assertTrue($result); - } - -/** - * Test SaveAssociated with Habtm relations - * - * @return void - */ - public function testSaveAssociatedHabtm() { - $this->loadFixtures('Article', 'Tag', 'Comment', 'User', 'ArticlesTag'); - $data = array( - 'Article' => array( - 'user_id' => 1, - 'title' => 'Article Has and belongs to Many Tags' - ), - 'Tag' => array( - 'Tag' => array(1, 2) - ), - 'Comment' => array( - array( - 'comment' => 'Article comment', - 'user_id' => 1 - ))); - $Article = new Article(); - $result = $Article->saveAssociated($data); - $this->assertFalse(empty($result)); - - $result = $Article->read(); - $this->assertEquals(2, count($result['Tag'])); - $this->assertEquals('tag1', $result['Tag'][0]['tag']); - $this->assertEquals(1, count($result['Comment'])); - $this->assertEquals(1, count($result['Comment'][0]['comment'])); - } - -/** - * Test SaveAssociated with Habtm relations and extra join table fields - * - * @return void - */ - public function testSaveAssociatedHabtmWithExtraJoinTableFields() { - $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - - $data = array( - 'Something' => array( - 'id' => 4, - 'title' => 'Extra Fields', - 'body' => 'Extra Fields Body', - 'published' => '1' - ), - 'SomethingElse' => array( - array('something_else_id' => 1, 'doomed' => '1'), - array('something_else_id' => 2, 'doomed' => '0'), - array('something_else_id' => 3, 'doomed' => '1') - ) - ); - - $Something = new Something(); - $result = $Something->saveAssociated($data); - $this->assertFalse(empty($result)); - $result = $Something->read(); - - $this->assertEquals(3, count($result['SomethingElse'])); - $this->assertTrue(Set::matches('/Something[id=4]', $result)); - - $this->assertTrue(Set::matches('/SomethingElse[id=1]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=1]/JoinThing[something_else_id=1]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=1]/JoinThing[doomed=1]', $result)); - - $this->assertTrue(Set::matches('/SomethingElse[id=2]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=2]/JoinThing[something_else_id=2]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=2]/JoinThing[doomed=0]', $result)); - - $this->assertTrue(Set::matches('/SomethingElse[id=3]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=3]/JoinThing[something_else_id=3]', $result)); - $this->assertTrue(Set::matches('/SomethingElse[id=3]/JoinThing[doomed=1]', $result)); - } - -/** - * testSaveAssociatedHasOne method - * - * @return void - */ - public function testSaveAssociatedHasOne() { - $model = new Comment(); - $model->deleteAll(true); - $this->assertEquals(array(), $model->find('all')); - - $model->Attachment->deleteAll(true); - $this->assertEquals(array(), $model->Attachment->find('all')); - - $this->assertTrue($model->saveAssociated(array( - 'Comment' => array( - 'comment' => 'Comment with attachment', - 'article_id' => 1, - 'user_id' => 1 - ), - 'Attachment' => array( - 'attachment' => 'some_file.zip' - )))); - $result = $model->find('all', array('fields' => array( - 'Comment.id', 'Comment.comment', 'Attachment.id', - 'Attachment.comment_id', 'Attachment.attachment' - ))); - $expected = array(array( - 'Comment' => array( - 'id' => '1', - 'comment' => 'Comment with attachment' - ), - 'Attachment' => array( - 'id' => '1', - 'comment_id' => '1', - 'attachment' => 'some_file.zip' - ))); - $this->assertEquals($expected, $result); - - $model->Attachment->bindModel(array('belongsTo' => array('Comment')), false); - $data = array( - 'Comment' => array( - 'comment' => 'Comment with attachment', - 'article_id' => 1, - 'user_id' => 1 - ), - 'Attachment' => array( - 'attachment' => 'some_file.zip' - )); - $this->assertTrue($model->saveAssociated($data, array('validate' => 'first'))); - } - -/** - * testSaveAssociatedBelongsTo method - * - * @return void - */ - public function testSaveAssociatedBelongsTo() { - $model = new Comment(); - $model->deleteAll(true); - $this->assertEquals(array(), $model->find('all')); - - $model->Article->deleteAll(true); - $this->assertEquals(array(), $model->Article->find('all')); - - $this->assertTrue($model->saveAssociated(array( - 'Comment' => array( - 'comment' => 'Article comment', - 'article_id' => 1, - 'user_id' => 1 - ), - 'Article' => array( - 'title' => 'Model Associations 101', - 'user_id' => 1 - )))); - $result = $model->find('all', array('fields' => array( - 'Comment.id', 'Comment.comment', 'Comment.article_id', 'Article.id', 'Article.title' - ))); - $expected = array(array( - 'Comment' => array( - 'id' => '1', - 'article_id' => '1', - 'comment' => 'Article comment' - ), - 'Article' => array( - 'id' => '1', - 'title' => 'Model Associations 101' - ))); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAssociatedHasOneValidation method - * - * @return void - */ - public function testSaveAssociatedHasOneValidation() { - $model = new Comment(); - $model->deleteAll(true); - $this->assertEquals(array(), $model->find('all')); - - $model->Attachment->deleteAll(true); - $this->assertEquals(array(), $model->Attachment->find('all')); - - $model->validate = array('comment' => 'notEmpty'); - $model->Attachment->validate = array('attachment' => 'notEmpty'); - $model->Attachment->bindModel(array('belongsTo' => array('Comment'))); - - $result = $model->saveAssociated( - array( - 'Comment' => array( - 'comment' => '', - 'article_id' => 1, - 'user_id' => 1 - ), - 'Attachment' => array('attachment' => '') - ) - ); - $this->assertFalse($result); - $expected = array( - 'comment' => array( - 'The provided value is invalid' - ), - 'Attachment' => array( - 'attachment' => array( - 'The provided value is invalid' - ) - ) - ); - $this->assertEquals($expected, $model->validationErrors); - $this->assertEquals($expected['Attachment'], $model->Attachment->validationErrors); - } - -/** - * testSaveAssociatedAtomic method - * - * @return void - */ - public function testSaveAssociatedAtomic() { - $this->loadFixtures('Article', 'User'); - $TestModel = new Article(); - - $result = $TestModel->saveAssociated(array( - 'Article' => array( - 'title' => 'Post with Author', - 'body' => 'This post will be saved with an author', - 'user_id' => 2 - ), - 'Comment' => array( - array('comment' => 'First new comment', 'user_id' => 2)) - ), array('atomic' => false)); - - $this->assertSame($result, array('Article' => true, 'Comment' => array(true))); - - $result = $TestModel->saveAssociated(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => 'First new comment', - 'published' => 'Y', - 'user_id' => 1 - ), - array( - 'comment' => 'Second new comment', - 'published' => 'Y', - 'user_id' => 2 - )) - ), array('validate' => true, 'atomic' => false)); - $this->assertSame($result, array('Article' => true, 'Comment' => array(true, true))); - } - -/** - * testSaveManyAtomic method - * - * @return void - */ - public function testSaveManyAtomic() { - $this->loadFixtures('Article', 'User'); - $TestModel = new Article(); - - $result = $TestModel->saveMany(array( - array( - 'id' => '1', - 'title' => 'Baleeted First Post', - 'body' => 'Baleeted!', - 'published' => 'N' - ), - array( - 'id' => '2', - 'title' => 'Just update the title' - ), - array( - 'title' => 'Creating a fourth post', - 'body' => 'Fourth post body', - 'user_id' => 2 - ) - ), array('atomic' => false)); - $this->assertSame($result, array(true, true, true)); - - $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); - $result = $TestModel->saveMany(array( - array( - 'id' => '1', - 'title' => 'Un-Baleeted First Post', - 'body' => 'Not Baleeted!', - 'published' => 'Y' - ), - array( - 'id' => '2', - 'title' => '', - 'body' => 'Trying to get away with an empty title' - ) - ), array('validate' => true, 'atomic' => false)); - - $this->assertSame(array(true, false), $result); - } - -/** - * testSaveAssociatedHasMany method - * - * @return void - */ - public function testSaveAssociatedHasMany() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - - $result = $TestModel->saveAssociated(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - )); - $this->assertFalse(empty($result)); - - $result = $TestModel->findById(2); - $expected = array( - 'First Comment for Second Article', - 'Second Comment for Second Article', - 'First new comment', - 'Second new comment' - ); - $this->assertEquals($expected, Hash::extract($result['Comment'], '{n}.comment')); - - $result = $TestModel->saveAssociated( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => 'Third new comment', - 'published' => 'Y', - 'user_id' => 1 - ))), - array('atomic' => false) - ); - $this->assertFalse(empty($result)); - - $result = $TestModel->findById(2); - $expected = array( - 'First Comment for Second Article', - 'Second Comment for Second Article', - 'First new comment', - 'Second new comment', - 'Third new comment' - ); - $this->assertEquals($expected, Hash::extract($result['Comment'], '{n}.comment')); - - $TestModel->beforeSaveReturn = false; - $result = $TestModel->saveAssociated( - array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => 'Fourth new comment', - 'published' => 'Y', - 'user_id' => 1 - ))), - array('atomic' => false) - ); - $this->assertEquals(array('Article' => false), $result); - - $result = $TestModel->findById(2); - $expected = array( - 'First Comment for Second Article', - 'Second Comment for Second Article', - 'First new comment', - 'Second new comment', - 'Third new comment' - ); - $this->assertEquals($expected, Hash::extract($result['Comment'], '{n}.comment')); - } - -/** - * testSaveAssociatedHasManyEmpty method - * - * @return void - */ - public function testSaveAssociatedHasManyEmpty() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - $TestModel->validate = $TestModel->Comment->validate = array('user_id' => array('notEmpty' => array('rule' => 'notEmpty', 'required' => true))); - - //empty hasMany data is ignored in save - $result = $TestModel->saveAssociated(array( - 'Article' => array('title' => 'title', 'user_id' => 1), - 'Comment' => array() - ), array('validate' => true)); - $this->assertTrue($result); - - $result = $TestModel->saveAssociated(array( - 'Article' => array('title' => 'title', 'user_id' => 1), - 'Comment' => array() - ), array('validate' => true, 'atomic' => false)); - $this->assertEquals(array('Article' => true), $result); - - //empty primary data is not ignored - $result = $TestModel->saveAssociated(array('Article' => array()), array('validate' => true)); - $this->assertFalse($result); - - $result = $TestModel->saveAssociated(array('Article' => array()), array('validate' => true, 'atomic' => false)); - $this->assertEquals(array('Article' => false), $result); - } - -/** - * testSaveAssociatedHasManyValidation method - * - * @return void - */ - public function testSaveAssociatedHasManyValidation() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->validate = array('comment' => 'notEmpty'); - - $result = $TestModel->saveAssociated(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array('comment' => '', 'published' => 'Y', 'user_id' => 1), - ) - ), array('validate' => true)); - $this->assertFalse($result); - - $expected = array('Comment' => array( - array('comment' => array('The provided value is invalid')) - )); - $this->assertEquals($expected, $TestModel->validationErrors); - $expected = array( - array('comment' => array('The provided value is invalid')) - ); - $this->assertEquals($expected, $TestModel->Comment->validationErrors); - - $result = $TestModel->saveAssociated(array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1 - )) - ), array('validate' => 'first')); - $this->assertFalse($result); - } - -/** - * test saveMany with transactions and ensure there is no missing rollback. - * - * @return void - */ - public function testSaveManyTransactionNoRollback() { - $this->loadFixtures('Post'); - - $this->getMock('DboSource', array('connect', 'rollback', 'describe'), array(), 'MockManyTransactionDboSource'); - $db = ConnectionManager::create('mock_many_transaction', array( - 'datasource' => 'MockManyTransactionDboSource', - )); - - $db->expects($this->once()) - ->method('describe') - ->will($this->returnValue(array())); - $db->expects($this->once())->method('rollback'); - - $Post = new Post('mock_many_transaction'); - - $Post->validate = array( - 'title' => array('rule' => array('notEmpty')) - ); - - $data = array( - array('author_id' => 1, 'title' => 'New Fourth Post'), - array('author_id' => 1, 'title' => '') - ); - $Post->saveMany($data); - } - -/** - * test saveAssociated with transactions and ensure there is no missing rollback. - * - * @return void - */ - public function testSaveAssociatedTransactionNoRollback() { - $testDb = ConnectionManager::getDataSource('test'); - - $this->getMock( - 'DboSource', - array('connect', 'rollback', 'describe', 'create', 'begin'), - array(), - 'MockAssociatedTransactionDboSource', - false - ); - $db = ConnectionManager::create('mock_assoc_transaction', array( - 'datasource' => 'MockAssociatedTransactionDboSource', - )); - $this->mockObjects[] = $db; - $db->columns = $testDb->columns; - - $db->expects($this->once())->method('rollback'); - $db->expects($this->any())->method('describe') - ->will($this->returnValue(array( - 'id' => array('type' => 'integer', 'length' => 11), - 'title' => array('type' => 'string'), - 'body' => array('type' => 'text'), - 'published' => array('type' => 'string') - ))); - - $Post = new Post(); - $Post->useDbConfig = 'mock_assoc_transaction'; - $Post->Author->useDbConfig = 'mock_assoc_transaction'; - - $Post->Author->validate = array( - 'user' => array('rule' => array('notEmpty')) - ); - - $data = array( - 'Post' => array( - 'title' => 'New post', - 'body' => 'Content', - 'published' => 'Y' - ), - 'Author' => array( - 'user' => '', - 'password' => "sekret" - ) - ); - $Post->saveAssociated($data, array('validate' => true, 'atomic' => true)); - } - -/** - * test saveMany with nested saveMany call. - * - * @return void - */ - public function testSaveManyNestedSaveMany() { - $this->loadFixtures('Sample'); - $TransactionManyTestModel = new TransactionManyTestModel(); - - $data = array( - array('apple_id' => 1, 'name' => 'sample5'), - ); - - $this->assertTrue($TransactionManyTestModel->saveMany($data, array('atomic' => true))); - } - -/** - * testSaveManyTransaction method - * - * @return void - */ - public function testSaveManyTransaction() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel = new Post(); - - $TestModel->validate = array('title' => 'notEmpty'); - $data = array( - array('author_id' => 1, 'title' => 'New Fourth Post'), - array('author_id' => 1, 'title' => 'New Fifth Post'), - array('author_id' => 1, 'title' => '') - ); - $this->assertFalse($TestModel->saveMany($data)); - - $result = $TestModel->find('all', array('recursive' => -1)); - $expected = array( - array('Post' => array( - 'id' => '1', - 'author_id' => 1, - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - array('Post' => array( - 'id' => '2', - 'author_id' => 3, - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - )), - array('Post' => array( - 'id' => '3', - 'author_id' => 1, - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ))); - - if (count($result) != 3) { - // Database doesn't support transactions - $expected[] = array( - 'Post' => array( - 'id' => '4', - 'author_id' => 1, - 'title' => 'New Fourth Post', - 'body' => null, - 'published' => 'N' - )); - - $expected[] = array( - 'Post' => array( - 'id' => '5', - 'author_id' => 1, - 'title' => 'New Fifth Post', - 'body' => null, - 'published' => 'N', - )); - - $this->assertEquals(static::date(), $result[3]['Post']['created']); - $this->assertEquals(static::date(), $result[3]['Post']['updated']); - $this->assertEquals(static::date(), $result[4]['Post']['created']); - $this->assertEquals(static::date(), $result[4]['Post']['updated']); - unset($result[3]['Post']['created'], $result[3]['Post']['updated']); - unset($result[4]['Post']['created'], $result[4]['Post']['updated']); - $this->assertEquals($expected, $result); - // Skip the rest of the transactional tests - return; - } - - $this->assertEquals($expected, $result); - - $data = array( - array('author_id' => 1, 'title' => 'New Fourth Post'), - array('author_id' => 1, 'title' => ''), - array('author_id' => 1, 'title' => 'New Sixth Post') - ); - $this->assertFalse($TestModel->saveMany($data)); - - $result = $TestModel->find('all', array('recursive' => -1)); - $expected = array( - array('Post' => array( - 'id' => '1', - 'author_id' => 1, - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:39:23', - 'updated' => '2007-03-18 10:41:31' - )), - array('Post' => array( - 'id' => '2', - 'author_id' => 3, - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23', - 'updated' => '2007-03-18 10:43:31' - )), - array('Post' => array( - 'id' => '3', - 'author_id' => 1, - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - ))); - - if (count($result) != 3) { - // Database doesn't support transactions - $expected[] = array( - 'Post' => array( - 'id' => '4', - 'author_id' => 1, - 'title' => 'New Fourth Post', - 'body' => 'Third Post Body', - 'published' => 'N' - )); - - $expected[] = array( - 'Post' => array( - 'id' => '5', - 'author_id' => 1, - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'N' - )); - $this->assertEquals(static::date(), $result[3]['Post']['created']); - $this->assertEquals(static::date(), $result[3]['Post']['updated']); - $this->assertEquals(static::date(), $result[4]['Post']['created']); - $this->assertEquals(static::date(), $result[4]['Post']['updated']); - unset($result[3]['Post']['created'], $result[3]['Post']['updated']); - unset($result[4]['Post']['created'], $result[4]['Post']['updated']); - } - $this->assertEquals($expected, $result); - - $TestModel->validate = array('title' => 'notEmpty'); - $data = array( - array('author_id' => 1, 'title' => 'New Fourth Post'), - array('author_id' => 1, 'title' => 'New Fifth Post'), - array('author_id' => 1, 'title' => 'New Sixth Post') - ); - $this->assertTrue($TestModel->saveMany($data)); - - $result = $TestModel->find('all', array( - 'recursive' => -1, - 'fields' => array('author_id', 'title', 'body', 'published'), - 'order' => array('Post.created' => 'ASC') - )); - - $expected = array( - array('Post' => array( - 'author_id' => 1, - 'title' => 'First Post', - 'body' => 'First Post Body', - 'published' => 'Y' - )), - array('Post' => array( - 'author_id' => 3, - 'title' => 'Second Post', - 'body' => 'Second Post Body', - 'published' => 'Y' - )), - array('Post' => array( - 'author_id' => 1, - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y' - )), - array('Post' => array( - 'author_id' => 1, - 'title' => 'New Fourth Post', - 'body' => '', - 'published' => 'N' - )), - array('Post' => array( - 'author_id' => 1, - 'title' => 'New Fifth Post', - 'body' => '', - 'published' => 'N' - )), - array('Post' => array( - 'author_id' => 1, - 'title' => 'New Sixth Post', - 'body' => '', - 'published' => 'N' - ))); - $this->assertEquals($expected, $result); - } - -/** - * testSaveManyValidation method - * - * @return void - */ - public function testSaveManyValidation() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel = new Post(); - - $data = array( - array( - 'id' => '1', - 'title' => 'Baleeted First Post', - 'body' => 'Baleeted!', - 'published' => 'N' - ), - array( - 'id' => '2', - 'title' => 'Just update the title' - ), - array( - 'title' => 'Creating a fourth post', - 'body' => 'Fourth post body', - 'author_id' => 2 - )); - - $this->assertTrue($TestModel->saveMany($data)); - - $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '1', - 'title' => 'Baleeted First Post', - 'body' => 'Baleeted!', - 'published' => 'N', - 'created' => '2007-03-18 10:39:23' - ) - ), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '3', - 'title' => 'Just update the title', - 'body' => 'Second Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:41:23' - ) - ), - array( - 'Post' => array( - 'id' => '3', - 'author_id' => '1', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - 'created' => '2007-03-18 10:43:23', - 'updated' => '2007-03-18 10:45:31' - )), - array( - 'Post' => array( - 'id' => '4', - 'author_id' => '2', - 'title' => 'Creating a fourth post', - 'body' => 'Fourth post body', - 'published' => 'N' - ) - ) - ); - - $this->assertEquals(static::date(), $result[0]['Post']['updated']); - $this->assertEquals(static::date(), $result[1]['Post']['updated']); - $this->assertEquals(static::date(), $result[3]['Post']['created']); - $this->assertEquals(static::date(), $result[3]['Post']['updated']); - unset($result[0]['Post']['updated'], $result[1]['Post']['updated']); - unset($result[3]['Post']['created'], $result[3]['Post']['updated']); - $this->assertEquals($expected, $result); - - $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); - $data = array( - array( - 'id' => '1', - 'title' => 'Un-Baleeted First Post', - 'body' => 'Not Baleeted!', - 'published' => 'Y' - ), - array( - 'id' => '2', - 'title' => '', - 'body' => 'Trying to get away with an empty title' - )); - $result = $TestModel->saveMany($data); - $this->assertFalse($result); - - $result = $TestModel->find('all', array('recursive' => -1, 'order' => 'Post.id ASC')); - $errors = array(1 => array('title' => array('The provided value is invalid'))); - $transactionWorked = Set::matches('/Post[1][title=Baleeted First Post]', $result); - if (!$transactionWorked) { - $this->assertTrue(Set::matches('/Post[1][title=Un-Baleeted First Post]', $result)); - $this->assertTrue(Set::matches('/Post[2][title=Just update the title]', $result)); - } - - $this->assertEquals($errors, $TestModel->validationErrors); - - $TestModel->validate = array('title' => 'notEmpty', 'author_id' => 'numeric'); - $data = array( - array( - 'id' => '1', - 'title' => 'Un-Baleeted First Post', - 'body' => 'Not Baleeted!', - 'published' => 'Y' - ), - array( - 'id' => '2', - 'title' => '', - 'body' => 'Trying to get away with an empty title' - )); - $result = $TestModel->saveMany($data, array('validate' => true, 'atomic' => false)); - $this->assertEquals(array(true, false), $result); - - $result = $TestModel->find('all', array( - 'fields' => array('id', 'author_id', 'title', 'body', 'published'), - 'recursive' => -1, - 'order' => 'Post.id ASC' - )); - $errors = array(1 => array('title' => array('The provided value is invalid'))); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '1', - 'title' => 'Un-Baleeted First Post', - 'body' => 'Not Baleeted!', - 'published' => 'Y', - )), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '3', - 'title' => 'Just update the title', - 'body' => 'Second Post Body', - 'published' => 'Y', - )), - array( - 'Post' => array( - 'id' => '3', - 'author_id' => '1', - 'title' => 'Third Post', - 'body' => 'Third Post Body', - 'published' => 'Y', - )), - array( - 'Post' => array( - 'id' => '4', - 'author_id' => '2', - 'title' => 'Creating a fourth post', - 'body' => 'Fourth post body', - 'published' => 'N', - ))); - $this->assertEquals($expected, $result); - $this->assertEquals($errors, $TestModel->validationErrors); - - $data = array( - array( - 'id' => '1', - 'title' => 'Re-Baleeted First Post', - 'body' => 'Baleeted!', - 'published' => 'N' - ), - array( - 'id' => '2', - 'title' => '', - 'body' => 'Trying to get away with an empty title' - )); - $this->assertFalse($TestModel->saveMany($data, array('validate' => 'first'))); - - $result = $TestModel->find('all', array( - 'fields' => array('id', 'author_id', 'title', 'body', 'published'), - 'recursive' => -1, - 'order' => 'Post.id ASC' - )); - $this->assertEquals($expected, $result); - $this->assertEquals($errors, $TestModel->validationErrors); - } - -/** - * testValidateMany method - * - * @return void - */ - public function testValidateMany() { - $TestModel = new Article(); - $TestModel->validate = array('title' => 'notEmpty'); - $data = array( - 0 => array('title' => ''), - 1 => array('title' => 'title 1'), - 2 => array('title' => 'title 2'), - ); - $result = $TestModel->validateMany($data); - $this->assertFalse($result); - $expected = array( - 0 => array('title' => array('The provided value is invalid')), - ); - $this->assertEquals($expected, $TestModel->validationErrors); - - $data = array( - 0 => array('title' => 'title 0'), - 1 => array('title' => ''), - 2 => array('title' => 'title 2'), - ); - $result = $TestModel->validateMany($data); - $this->assertFalse($result); - $expected = array( - 1 => array('title' => array('The provided value is invalid')), - ); - $this->assertEquals($expected, $TestModel->validationErrors); - } - -/** - * testSaveAssociatedValidateFirst method - * - * @return void - */ - public function testSaveAssociatedValidateFirst() { - $this->loadFixtures('Article', 'Comment', 'Attachment'); - $model = new Article(); - $model->deleteAll(true); - - $model->Comment->validate = array('comment' => 'notEmpty'); - $result = $model->saveAssociated(array( - 'Article' => array( - 'title' => 'Post with Author', - 'body' => 'This post will be saved author' - ), - 'Comment' => array( - array('comment' => 'First new comment'), - array('comment' => '') - ) - ), array('validate' => 'first')); - - $this->assertFalse($result); - - $result = $model->find('all'); - $this->assertSame(array(), $result); - $expected = array('Comment' => array( - 1 => array('comment' => array('The provided value is invalid')) - )); - - $this->assertEquals($expected['Comment'], $model->Comment->validationErrors); - - $this->assertSame($model->Comment->find('count'), 0); - - $result = $model->saveAssociated( - array( - 'Article' => array( - 'title' => 'Post with Author', - 'body' => 'This post will be saved with an author', - 'user_id' => 2 - ), - 'Comment' => array( - array( - 'comment' => 'Only new comment', - 'user_id' => 2 - ))), - array('validate' => 'first') - ); - - $this->assertTrue($result); - - $result = $model->Comment->find('all'); - $this->assertSame(count($result), 1); - $result = Hash::extract($result, '{n}.Comment.article_id'); - $this->assertEquals(4, $result[0]); - - $model->deleteAll(true); - $data = array( - 'Article' => array( - 'title' => 'Post with Author saveAlled from comment', - 'body' => 'This post will be saved with an author', - 'user_id' => 2 - ), - 'Comment' => array( - 'comment' => 'Only new comment', 'user_id' => 2 - )); - - $result = $model->Comment->saveAssociated($data, array('validate' => 'first')); - $this->assertFalse(empty($result)); - - $result = $model->find('all'); - $this->assertEquals( - 'Post with Author saveAlled from comment', - $result[0]['Article']['title'] - ); - $this->assertEquals('Only new comment', $result[0]['Comment'][0]['comment']); - } - -/** - * test saveMany()'s return is correct when using atomic = false and validate = first. - * - * @return void - */ - public function testSaveManyValidateFirstAtomicFalse() { - $Something = new Something(); - $invalidData = array( - array( - 'title' => 'foo', - 'body' => 'bar', - 'published' => 'baz', - ), - array( - 'body' => 3, - 'published' => 'sd', - ), - ); - $Something->create(); - $Something->validate = array( - 'title' => array( - 'rule' => 'alphaNumeric', - 'required' => true, - ), - 'body' => array( - 'rule' => 'alphaNumeric', - 'required' => true, - 'allowEmpty' => true, - ), - ); - $result = $Something->saveMany($invalidData, array( - 'atomic' => false, - 'validate' => 'first', - )); - $expected = array(true, false); - $this->assertEquals($expected, $result); - - $Something = new Something(); - $validData = array( - array( - 'title' => 'title value', - 'body' => 'body value', - 'published' => 'baz', - ), - array( - 'title' => 'valid', - 'body' => 'this body', - 'published' => 'sd', - ), - ); - $Something->create(); - $result = $Something->saveMany($validData, array( - 'atomic' => false, - 'validate' => 'first', - )); - $expected = array(true, true); - $this->assertEquals($expected, $result); - } - -/** - * testValidateAssociated method - * - * @return void - */ - public function testValidateAssociated() { - $this->loadFixtures('Attachment', 'Article', 'Comment'); - $TestModel = new Comment(); - $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); - - $data = array( - 'Comment' => array( - 'comment' => 'This is the comment' - ), - 'Attachment' => array( - 'attachment' => '' - ) - ); - - $result = $TestModel->validateAssociated($data); - $this->assertFalse($result); - - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - $TestModel->Comment->validate = array('comment' => 'notEmpty'); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'id' => 1, - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1), - array( - 'id' => 2, - 'comment' => - 'comment', - 'published' => 'Y', - 'user_id' => 1 - ))); - $result = $TestModel->validateAssociated($data); - $this->assertFalse($result); - - $data = array( - 'Article' => array('id' => 2), - 'Comment' => array( - array( - 'id' => 1, - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1 - ), - array( - 'id' => 2, - 'comment' => 'comment', - 'published' => 'Y', - 'user_id' => 1 - ), - array( - 'id' => 3, - 'comment' => '', - 'published' => 'Y', - 'user_id' => 1 - ))); - $result = $TestModel->validateAssociated($data, array( - 'atomic' => false - )); - $expected = array( - 'Article' => true, - 'Comment' => array(false, true, false) - ); - $this->assertSame($expected, $result); - - $expected = array('Comment' => array( - 0 => array('comment' => array('The provided value is invalid')), - 2 => array('comment' => array('The provided value is invalid')) - )); - $this->assertEquals($expected, $TestModel->validationErrors); - - $expected = array( - 0 => array('comment' => array('The provided value is invalid')), - 2 => array('comment' => array('The provided value is invalid')) - ); - $this->assertEquals($expected, $TestModel->Comment->validationErrors); - } - -/** - * test that saveMany behaves like plain save() when suplied empty data - * - * @link https://cakephp.lighthouseapp.com/projects/42648/tickets/277-test-saveall-with-validation-returns-incorrect-boolean-when-saving-empty-data - * @return void - */ - public function testSaveManyEmptyData() { - $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); - - $this->loadFixtures('Article', 'ProductUpdateAll', 'Comment', 'Attachment'); - $model = new Article(); - $result = $model->saveMany(array(), array('validate' => true)); - $this->assertFalse(empty($result)); - - $model = new ProductUpdateAll(); - $result = $model->saveMany(array()); - $this->assertFalse($result); - } - -/** - * test that saveAssociated behaves like plain save() when supplied empty data - * - * @link https://cakephp.lighthouseapp.com/projects/42648/tickets/277-test-saveall-with-validation-returns-incorrect-boolean-when-saving-empty-data - * @return void - */ - public function testSaveAssociatedEmptyData() { - $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); - - $this->loadFixtures('Article', 'ProductUpdateAll', 'Comment', 'Attachment'); - $model = new Article(); - $result = $model->saveAssociated(array(), array('validate' => true)); - $this->assertFalse(empty($result)); - - $model = new ProductUpdateAll(); - $result = $model->saveAssociated(array()); - $this->assertFalse($result); - } - -/** - * Test that saveAssociated will accept expression object values when saving. - * - * @return void - */ - public function testSaveAssociatedExpressionObjects() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article', 'User'); - $TestModel = new Post(); - $db = $TestModel->getDataSource(); - - $TestModel->saveAssociated(array( - 'Post' => array( - 'title' => $db->expression("(SELECT 'Post with Author')"), - 'body' => 'This post will be saved with an author' - ), - 'Author' => array( - 'user' => 'bob', - 'password' => '5f4dcc3b5aa765d61d8327deb882cf90' - )), array('atomic' => false)); - - $result = $TestModel->find('first', array( - 'order' => array('Post.id ' => 'DESC') - )); - $this->assertEquals('Post with Author', $result['Post']['title']); - } - -/** - * testUpdateWithCalculation method - * - * @return void - */ - public function testUpdateWithCalculation() { - $this->loadFixtures('DataTest'); - $model = new DataTest(); - $model->deleteAll(true); - $result = $model->saveMany(array( - array('count' => 5, 'float' => 1.1), - array('count' => 3, 'float' => 1.2), - array('count' => 4, 'float' => 1.3), - array('count' => 1, 'float' => 2.0), - )); - $this->assertFalse(empty($result)); - - $result = Hash::extract($model->find('all', array('fields' => 'count')), '{n}.DataTest.count'); - $this->assertEquals(array(5, 3, 4, 1), $result); - - $this->assertTrue($model->updateAll(array('count' => 'count + 2'))); - $result = Hash::extract($model->find('all', array('fields' => 'count')), '{n}.DataTest.count'); - $this->assertEquals(array(7, 5, 6, 3), $result); - - $this->assertTrue($model->updateAll(array('DataTest.count' => 'DataTest.count - 1'))); - $result = Hash::extract($model->find('all', array('fields' => 'count')), '{n}.DataTest.count'); - $this->assertEquals(array(6, 4, 5, 2), $result); - } - - public function testToggleBoolFields() { - $this->loadFixtures('CounterCacheUser', 'CounterCachePost'); - $Post = new CounterCachePost(); - $Post->unbindModel(array('belongsTo' => array('User')), true); - - $true = array('Post' => array('published' => true, 'id' => 2)); - $false = array('Post' => array('published' => false, 'id' => 2)); - $fields = array('Post.published', 'Post.id'); - $updateConditions = array('Post.id' => 2); - - // check its true - $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); - $this->assertEquals($true, $result); - - // Testing without the alias - $this->assertTrue($Post->updateAll(array('published' => 'NOT published'), $updateConditions)); - $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); - $this->assertEquals($false, $result); - - $this->assertTrue($Post->updateAll(array('published' => 'NOT published'), $updateConditions)); - $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); - $this->assertEquals($true, $result); - - $db = ConnectionManager::getDataSource('test'); - $alias = $db->name('Post.published'); - - // Testing with the alias - $this->assertTrue($Post->updateAll(array('Post.published' => "NOT $alias"), $updateConditions)); - $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); - $this->assertEquals($false, $result); - - $this->assertTrue($Post->updateAll(array('Post.published' => "NOT $alias"), $updateConditions)); - $result = $Post->find('first', array('conditions' => $updateConditions, 'fields' => $fields)); - $this->assertEquals($true, $result); - } - -/** - * TestFindAllWithoutForeignKey - * - * @return void - */ - public function testFindAllForeignKey() { - $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll = new ProductUpdateAll(); - - $conditions = array('Group.name' => 'group one'); - - $ProductUpdateAll->bindModel(array( - 'belongsTo' => array( - 'Group' => array('className' => 'GroupUpdateAll') - ) - )); - - $ProductUpdateAll->belongsTo = array( - 'Group' => array('className' => 'GroupUpdateAll', 'foreignKey' => 'group_id') - ); - - $results = $ProductUpdateAll->find('all', compact('conditions')); - $this->assertTrue(!empty($results)); - - $ProductUpdateAll->bindModel(array('belongsTo' => array('Group'))); - $ProductUpdateAll->belongsTo = array( - 'Group' => array( - 'className' => 'GroupUpdateAll', - 'foreignKey' => false, - 'conditions' => 'ProductUpdateAll.groupcode = Group.code' - )); - - $resultsFkFalse = $ProductUpdateAll->find('all', compact('conditions')); - $this->assertTrue(!empty($resultsFkFalse)); - $expected = array( - '0' => array( - 'ProductUpdateAll' => array( - 'id' => 1, - 'name' => 'product one', - 'groupcode' => 120, - 'group_id' => 1), - 'Group' => array( - 'id' => 1, - 'name' => 'group one', - 'code' => 120) - ), - '1' => array( - 'ProductUpdateAll' => array( - 'id' => 2, - 'name' => 'product two', - 'groupcode' => 120, - 'group_id' => 1), - 'Group' => array( - 'id' => 1, - 'name' => 'group one', - 'code' => 120) - ) - - ); - $this->assertEquals($expected, $results); - $this->assertEquals($expected, $resultsFkFalse); - } - -/** - * test updateAll with empty values. - * - * @return void - */ - public function testUpdateAllEmptyValues() { - $this->skipIf($this->db instanceof Sqlserver || $this->db instanceof Postgres, 'This test is not compatible with Postgres or SQL Server.'); - - $this->loadFixtures('Author', 'Post'); - $model = new Author(); - $result = $model->updateAll(array('user' => '""')); - $this->assertTrue($result); - } - -/** - * testUpdateAllWithJoins - * - * @return void - */ - public function testUpdateAllWithJoins() { - $this->skipIf(!$this->db instanceof Mysql, 'Currently, there is no way of doing joins in an update statement in postgresql or sqlite'); - - $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll = new ProductUpdateAll(); - - $conditions = array('Group.name' => 'group one'); - - $ProductUpdateAll->bindModel(array('belongsTo' => array( - 'Group' => array('className' => 'GroupUpdateAll'))) - ); - - $ProductUpdateAll->updateAll(array('name' => "'new product'"), $conditions); - $results = $ProductUpdateAll->find('all', array( - 'conditions' => array('ProductUpdateAll.name' => 'new product') - )); - $expected = array( - '0' => array( - 'ProductUpdateAll' => array( - 'id' => 1, - 'name' => 'new product', - 'groupcode' => 120, - 'group_id' => 1), - 'Group' => array( - 'id' => 1, - 'name' => 'group one', - 'code' => 120) - ), - '1' => array( - 'ProductUpdateAll' => array( - 'id' => 2, - 'name' => 'new product', - 'groupcode' => 120, - 'group_id' => 1), - 'Group' => array( - 'id' => 1, - 'name' => 'group one', - 'code' => 120))); - - $this->assertEquals($expected, $results); - } - -/** - * testUpdateAllWithoutForeignKey - * - * @return void - */ - public function testUpdateAllWithoutForeignKey() { - $this->skipIf(!$this->db instanceof Mysql, 'Currently, there is no way of doing joins in an update statement in postgresql'); - - $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll = new ProductUpdateAll(); - - $conditions = array('Group.name' => 'group one'); - - $ProductUpdateAll->bindModel(array('belongsTo' => array( - 'Group' => array('className' => 'GroupUpdateAll') - ))); - - $ProductUpdateAll->belongsTo = array( - 'Group' => array( - 'className' => 'GroupUpdateAll', - 'foreignKey' => false, - 'conditions' => 'ProductUpdateAll.groupcode = Group.code' - ) - ); - - $ProductUpdateAll->updateAll(array('name' => "'new product'"), $conditions); - $resultsFkFalse = $ProductUpdateAll->find('all', array('conditions' => array('ProductUpdateAll.name' => 'new product'))); - $expected = array( - '0' => array( - 'ProductUpdateAll' => array( - 'id' => 1, - 'name' => 'new product', - 'groupcode' => 120, - 'group_id' => 1), - 'Group' => array( - 'id' => 1, - 'name' => 'group one', - 'code' => 120) - ), - '1' => array( - 'ProductUpdateAll' => array( - 'id' => 2, - 'name' => 'new product', - 'groupcode' => 120, - 'group_id' => 1), - 'Group' => array( - 'id' => 1, - 'name' => 'group one', - 'code' => 120))); - $this->assertEquals($expected, $resultsFkFalse); - } - -/** - * test writing floats in german locale. - * - * @return void - */ - public function testWriteFloatAsGerman() { - $restore = setlocale(LC_NUMERIC, 0); - - $this->skipIf(setlocale(LC_NUMERIC, 'de_DE') === false, "The German locale isn't available."); - - $model = new DataTest(); - $result = $model->save(array( - 'count' => 1, - 'float' => 3.14593 - )); - $this->assertTrue((bool)$result); - setlocale(LC_NUMERIC, $restore); - } - -/** - * Test returned array contains primary key when save creates a new record - * - * @return void - */ - public function testPkInReturnArrayForCreate() { - $this->loadFixtures('Article'); - $TestModel = new Article(); - - $data = array('Article' => array( - 'user_id' => '1', - 'title' => 'Fourth Article', - 'body' => 'Fourth Article Body', - 'published' => 'Y' - )); - $result = $TestModel->save($data); - $this->assertSame($result['Article']['id'], $TestModel->id); - } - -/** - * testSaveAllFieldListValidateBelongsTo - * - * @return void - */ - public function testSaveAllFieldListValidateBelongsTo() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel = new Post(); - - $result = $TestModel->find('all'); - $this->assertEquals(3, count($result)); - $this->assertFalse(isset($result[3])); - - // test belongsTo - $fieldList = array( - 'Post' => array('title'), - 'Author' => array('user') - ); - $data = array( - 'Post' => array( - 'title' => 'Post without body', - 'body' => 'This will not be saved', - ), - 'Author' => array( - 'user' => 'bob', - 'test' => 'This will not be saved', - - )); - $TestModel->saveAll($data, array('fieldList' => $fieldList)); - - $result = $TestModel->find('all', array( - 'order' => 'Post.id ASC', - )); - $expected = array( - 'Post' => array( - 'id' => '4', - 'author_id' => '5', - 'title' => 'Post without body', - 'body' => null, - 'published' => 'N', - 'created' => static::date(), - 'updated' => static::date(), - ), - 'Author' => array( - 'id' => '5', - 'user' => 'bob', - 'password' => null, - 'created' => static::date(), - 'updated' => static::date(), - 'test' => 'working', - ), - ); - $this->assertEquals($expected, $result[3]); - $this->assertEquals(4, count($result)); - $this->assertEquals('', $result[3]['Post']['body']); - $this->assertEquals('working', $result[3]['Author']['test']); - - $fieldList = array( - 'Post' => array('title') - ); - $data = array( - 'Post' => array( - 'title' => 'Post without body 2', - 'body' => 'This will not be saved' - ), - 'Author' => array( - 'user' => 'jack' - ) - ); - $TestModel->saveAll($data, array('fieldList' => $fieldList)); - $result = $TestModel->find('all', array( - 'order' => 'Post.id ASC', - )); - $this->assertNull($result[4]['Post']['body']); - - $fieldList = array( - 'Author' => array('password') - ); - $data = array( - 'Post' => array( - 'id' => '5', - 'title' => 'Post title', - 'body' => 'Post body' - ), - 'Author' => array( - 'id' => '6', - 'user' => 'will not change', - 'password' => 'foobar' - ) - ); - $result = $TestModel->saveAll($data, array('fieldList' => $fieldList)); - $this->assertTrue($result); - - $result = $TestModel->find('all', array( - 'order' => 'Post.id ASC', - )); - $expected = array( - 'Post' => array( - 'id' => '5', - 'author_id' => '6', - 'title' => 'Post title', - 'body' => 'Post body', - 'published' => 'N', - 'created' => self::date(), - 'updated' => self::date() - ), - 'Author' => array( - 'id' => '6', - 'user' => 'jack', - 'password' => 'foobar', - 'created' => self::date(), - 'updated' => self::date(), - 'test' => 'working' - ), - ); - $this->assertEquals($expected, $result[4]); - - // test multirecord - $this->db->truncate($TestModel); - - $fieldList = array('title', 'author_id'); - $TestModel->saveAll(array( - array( - 'title' => 'Multi-record post 1', - 'body' => 'First multi-record post', - 'author_id' => 2 - ), - array( - 'title' => 'Multi-record post 2', - 'body' => 'Second multi-record post', - 'author_id' => 2 - )), array('fieldList' => $fieldList)); - - $result = $TestModel->find('all', array( - 'recursive' => -1, - 'order' => 'Post.id ASC' - )); - $expected = array( - array( - 'Post' => array( - 'id' => '1', - 'author_id' => '2', - 'title' => 'Multi-record post 1', - 'body' => '', - 'published' => 'N', - 'created' => static::date(), - 'updated' => static::date() - ) - ), - array( - 'Post' => array( - 'id' => '2', - 'author_id' => '2', - 'title' => 'Multi-record post 2', - 'body' => '', - 'published' => 'N', - 'created' => static::date(), - 'updated' => static::date() - ) - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllFieldListHasMany method - * - * return @void - */ - public function testSaveAllFieldListHasMany() { - $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - - $this->db->truncate($TestModel); - $this->db->truncate(new Comment()); - - $data = array( - 'Article' => array('title' => 'I will not save'), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), - array('comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2) - ) - ); - - $fieldList = array( - 'Article' => array('id'), - 'Comment' => array('article_id', 'user_id') - ); - $TestModel->saveAll($data, array('fieldList' => $fieldList)); - - $result = $TestModel->find('all'); - $this->assertEquals('', $result[0]['Article']['title']); - $this->assertEquals('', $result[0]['Comment'][0]['comment']); - $this->assertEquals('', $result[0]['Comment'][1]['comment']); - - $fieldList = array( - 'Article' => array('id'), - 'Comment' => array('user_id') - ); - $TestModel->saveAll($data, array('fieldList' => $fieldList)); - $result = $TestModel->find('all'); - - $this->assertEquals('', $result[1]['Article']['title']); - $this->assertEquals(2, count($result[1]['Comment'])); - - $TestModel->whitelist = array('id'); - $TestModel->Comment->whitelist = array('user_id'); - $TestModel->saveAll($data); - $result = $TestModel->find('all'); - - $this->assertEquals('', $result[2]['Article']['title']); - $this->assertEquals(2, count($result[2]['Comment'])); - } - -/** - * testSaveAllFieldListHasOne method - * - * @return void - */ - public function testSaveAllFieldListHasOne() { - $this->loadFixtures('Attachment', 'Comment', 'Article', 'User'); - $TestModel = new Comment(); - - $TestModel->validate = array('comment' => 'notEmpty'); - $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); - - $record = array( - 'Comment' => array( - 'user_id' => 1, - 'article_id' => 1, - 'comment' => '', - ), - 'Attachment' => array( - 'attachment' => '' - ) - ); - $result = $TestModel->saveAll($record, array('validate' => 'only')); - $this->assertFalse($result); - - $fieldList = array( - 'Comment' => array('id', 'article_id', 'user_id'), - 'Attachment' => array('comment_id') - ); - $result = $TestModel->saveAll($record, array( - 'fieldList' => $fieldList, 'validate' => 'only' - )); - $this->assertTrue($result); - $this->assertEmpty($TestModel->validationErrors); - } - -/** - * testSaveAllFieldListHasOneAddFkToWhitelist method - * - * @return void - */ - public function testSaveAllFieldListHasOneAddFkToWhitelist() { - $this->loadFixtures('ArticleFeatured', 'Featured'); - $Article = new ArticleFeatured(); - $Article->belongsTo = $Article->hasMany = array(); - $Article->Featured->validate = array('end_date' => 'notEmpty'); - - $record = array( - 'ArticleFeatured' => array( - 'user_id' => 1, - 'title' => 'First Article', - 'body' => '', - 'published' => 'Y' - ), - 'Featured' => array( - 'category_id' => 1, - 'end_date' => '' - ) - ); - $result = $Article->saveAll($record, array('validate' => 'only')); - $this->assertFalse($result); - $expected = array( - 'body' => array( - 'The provided value is invalid' - ), - 'Featured' => array( - 'end_date' => array( - 'The provided value is invalid' - ) - ) - ); - $this->assertEquals($expected, $Article->validationErrors); - - $fieldList = array( - 'ArticleFeatured' => array('user_id', 'title'), - 'Featured' => array('category_id') - ); - - $result = $Article->saveAll($record, array( - 'fieldList' => $fieldList, 'validate' => 'first' - )); - $this->assertTrue($result); - $this->assertEmpty($Article->validationErrors); - - $Article->recursive = 0; - $result = $Article->find('first', array('order' => array('ArticleFeatured.created' => 'DESC'))); - $this->assertSame($result['ArticleFeatured']['id'], $result['Featured']['article_featured_id']); - } - -/** - * testSaveAllDeepFieldListValidateBelongsTo - * - * @return void - */ - public function testSaveAllDeepFieldListValidateBelongsTo() { - $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment', 'Article', 'User'); - $TestModel = new Post(); - $TestModel->Author->bindModel(array('hasMany' => array('Comment' => array('foreignKey' => 'user_id'))), false); - $TestModel->recursive = 2; - - $result = $TestModel->find('all'); - $this->assertEquals(3, count($result)); - $this->assertFalse(isset($result[3])); - - // test belongsTo - $fieldList = array( - 'Post' => array('title', 'author_id'), - 'Author' => array('user'), - 'Comment' => array('comment') - ); - $TestModel->saveAll(array( - 'Post' => array( - 'title' => 'Post without body', - 'body' => 'This will not be saved', - ), - 'Author' => array( - 'user' => 'bob', - 'test' => 'This will not be saved', - 'Comment' => array( - array('id' => 5, 'comment' => 'I am still published', 'published' => 'N')) - - )), array('fieldList' => $fieldList, 'deep' => true)); - - $result = $TestModel->Author->Comment->find('first', array( - 'conditions' => array('Comment.id' => 5), - 'fields' => array('comment', 'published') - )); - $expected = array( - 'Comment' => array( - 'comment' => 'I am still published', - 'published' => 'Y' - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllDeepFieldListHasMany method - * - * return @void - */ - public function testSaveAllDeepFieldListHasMany() { - $this->loadFixtures('Article', 'Comment', 'User'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - - $this->db->truncate($TestModel); - $this->db->truncate(new Comment()); - - $fieldList = array( - 'Article' => array('id'), - 'Comment' => array('article_id', 'user_id'), - 'User' => array('user') - ); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2, 'title' => 'I will not save'), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), - array( - 'comment' => 'Second new comment', 'published' => 'Y', 'user_id' => 2, - 'User' => array('user' => 'nopassword', 'password' => 'not saved') - ) - ) - ), array('fieldList' => $fieldList, 'deep' => true)); - - $result = $TestModel->Comment->User->find('first', array( - 'conditions' => array('User.user' => 'nopassword'), - 'fields' => array('user', 'password') - )); - $expected = array( - 'User' => array( - 'user' => 'nopassword', - 'password' => '' - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllDeepHasManyBelongsTo method - * - * return @void - */ - public function testSaveAllDeepHasManyBelongsTo() { - $this->loadFixtures('Article', 'Comment', 'User'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); - - $this->db->truncate($TestModel); - $this->db->truncate(new Comment()); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2, 'title' => 'The title'), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), - array( - 'comment' => 'belongsto', 'published' => 'Y', - 'User' => array('user' => 'findme', 'password' => 'somepass') - ) - ) - ), array('deep' => true)); - - $result = $TestModel->Comment->User->find('first', array( - 'conditions' => array('User.user' => 'findme'), - 'fields' => array('id', 'user', 'password') - )); - $expected = array( - 'User' => array( - 'id' => 5, - 'user' => 'findme', - 'password' => 'somepass', - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->Comment->find('first', array( - 'conditions' => array('Comment.user_id' => 5), - 'fields' => array('id', 'comment', 'published', 'user_id') - )); - $expected = array( - 'Comment' => array( - 'id' => 2, - 'comment' => 'belongsto', - 'published' => 'Y', - 'user_id' => 5 - ) - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllDeepHasManyhasMany method - * - * return @void - */ - public function testSaveAllDeepHasManyHasMany() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->Comment->belongsTo = array(); - $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment')), false); - $TestModel->Comment->bindModel(array('hasMany' => array('Attachment')), false); - - $this->db->truncate($TestModel); - $this->db->truncate(new Comment()); - $this->db->truncate(new Attachment()); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2, 'title' => 'The title'), - 'Comment' => array( - array('comment' => 'First new comment', 'published' => 'Y', 'user_id' => 1), - array( - 'comment' => 'hasmany', 'published' => 'Y', 'user_id' => 5, - 'Attachment' => array( - array('attachment' => 'first deep attachment'), - array('attachment' => 'second deep attachment'), - ) - ) - ) - ), array('deep' => true)); - - $result = $TestModel->Comment->find('first', array( - 'conditions' => array('Comment.comment' => 'hasmany'), - 'fields' => array('id', 'comment', 'published', 'user_id'), - 'recursive' => -1 - )); - $expected = array( - 'Comment' => array( - 'id' => 2, - 'comment' => 'hasmany', - 'published' => 'Y', - 'user_id' => 5 - ) - ); - $this->assertEquals($expected, $result); - - $result = $TestModel->Comment->Attachment->find('all', array( - 'fields' => array('attachment', 'comment_id'), - 'order' => array('Attachment.id' => 'ASC') - )); - $expected = array( - array('Attachment' => array('attachment' => 'first deep attachment', 'comment_id' => 2)), - array('Attachment' => array('attachment' => 'second deep attachment', 'comment_id' => 2)), - ); - $this->assertEquals($expected, $result); - } - -/** - * testSaveAllDeepOrderHasManyHasMany method - * - * return @void - */ - public function testSaveAllDeepOrderHasManyHasMany() { - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->Comment->belongsTo = array(); - $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment')), false); - $TestModel->Comment->bindModel(array('hasMany' => array('Attachment')), false); - - $this->db->truncate($TestModel); - $this->db->truncate(new Comment()); - $this->db->truncate(new Attachment()); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 2, 'title' => 'Comment has its data after Attachment'), - 'Comment' => array( - array( - 'Attachment' => array( - array('attachment' => 'attachment should be created with comment_id'), - array('attachment' => 'comment should be created with article_id'), - ), - 'comment' => 'after associated data', - 'user_id' => 1 - ) - ) - ), array('deep' => true)); - $result = $TestModel->Comment->find('first', array( - 'conditions' => array('Comment.article_id' => 2), - )); - - $this->assertEquals(2, $result['Comment']['article_id']); - $this->assertEquals(2, count($result['Attachment'])); - } - -/** - * testSaveAllDeepEmptyHasManyHasMany method - * - * return @void - */ - public function testSaveAllDeepEmptyHasManyHasMany() { - $this->skipIf(!$this->db instanceof Mysql, 'This test is only compatible with Mysql.'); - - $this->loadFixtures('Article', 'Comment', 'User', 'Attachment'); - $TestModel = new Article(); - $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->Comment->belongsTo = array(); - $TestModel->Comment->unbindModel(array('hasOne' => array('Attachment')), false); - $TestModel->Comment->bindModel(array('hasMany' => array('Attachment')), false); - - $this->db->truncate($TestModel); - $this->db->truncate(new Comment()); - $this->db->truncate(new Attachment()); - - $result = $TestModel->saveAll(array( - 'Article' => array('id' => 3, 'user_id' => 1, 'title' => 'Comment has no data'), - 'Comment' => array( - array( - 'user_id' => 1, - 'Attachment' => array( - array('attachment' => 'attachment should be created with comment_id'), - array('attachment' => 'comment should be created with article_id'), - ), - ) - ) - ), array('deep' => true)); - $result = $TestModel->Comment->find('first', array( - 'conditions' => array('Comment.article_id' => 3), - )); - - $this->assertEquals(3, $result['Comment']['article_id']); - $this->assertEquals(2, count($result['Attachment'])); - } - -/** - * testUpdateAllBoolean - * - * return @void - */ - public function testUpdateAllBoolean() { - $this->loadFixtures('Item', 'Syfile', 'Portfolio', 'Image', 'ItemsPortfolio'); - $TestModel = new Item(); - $result = $TestModel->updateAll(array('published' => true)); - $this->assertTrue($result); - - $result = $TestModel->find('first', array('fields' => array('id', 'published'))); - $this->assertEquals(true, $result['Item']['published']); - } - -/** - * testUpdateAllBooleanConditions - * - * return @void - */ - public function testUpdateAllBooleanConditions() { - $this->loadFixtures('Item', 'Syfile', 'Portfolio', 'Image', 'ItemsPortfolio'); - $TestModel = new Item(); - - $result = $TestModel->updateAll(array('published' => true), array('Item.id' => 1)); - $this->assertTrue($result); - $result = $TestModel->find('first', array( - 'fields' => array('id', 'published'), - 'conditions' => array('Item.id' => 1))); - $this->assertEquals(true, $result['Item']['published']); - } - -/** - * testUpdateBoolean - * - * return @void - */ - public function testUpdateBoolean() { - $this->loadFixtures('Item', 'Syfile', 'Portfolio', 'Image', 'ItemsPortfolio'); - $TestModel = new Item(); - - $result = $TestModel->save(array('published' => true, 'id' => 1)); - $this->assertTrue((bool)$result); - $result = $TestModel->find('first', array( - 'fields' => array('id', 'published'), - 'conditions' => array('Item.id' => 1))); - $this->assertEquals(true, $result['Item']['published']); - } - -/** - * Test the clear() method. - * - * @return void - */ - public function testClear() { - $this->loadFixtures('Bid'); - $model = ClassRegistry::init('Bid'); - $model->set(array('name' => 'Testing', 'message_id' => 3)); - $this->assertTrue(isset($model->data['Bid']['name'])); - $this->assertTrue($model->clear()); - $this->assertFalse(isset($model->data['Bid']['name'])); - $this->assertFalse(isset($model->data['Bid']['message_id'])); - } -} diff --git a/Cake/Test/TestCase/Model/models.php b/Cake/Test/TestCase/Model/models.php deleted file mode 100644 index 65a888ef188..00000000000 --- a/Cake/Test/TestCase/Model/models.php +++ /dev/null @@ -1,4868 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.6464 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Model; - -use Cake\Model\Model; -use Cake\TestSuite\Fixture\TestModel as CakeTestModel; - -/** - * AppModel class - * - */ -class AppModel extends Model { - -/** - * findMethods property - * - * @var array - */ - public $findMethods = array('published' => true); - -/** - * useDbConfig property - * - * @var array - */ - public $useDbConfig = 'test'; - -/** - * _findPublished custom find - * - * @return array - */ - protected function _findPublished($state, $query, $results = array()) { - if ($state === 'before') { - $query['conditions']['published'] = 'Y'; - return $query; - } - return $results; - } - -} - -/** - * Test class - * - */ -class Test extends CakeTestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * name property - * - * @var string - */ - public $name = 'Test'; - -/** - * schema property - * - * @var array - */ - protected $_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '1', 'length' => '8', 'key' => 'primary'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'notes' => array('type' => 'text', 'null' => '1', 'default' => 'write some notes here', 'length' => ''), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - -} - -/** - * TestAlias class - * - */ -class TestAlias extends CakeTestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * name property - * - * @var string - */ - public $name = 'TestAlias'; - -/** - * schema property - * - * @var array - */ - protected $_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '1', 'length' => '8', 'key' => 'primary'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'notes' => array('type' => 'text', 'null' => '1', 'default' => 'write some notes here', 'length' => ''), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); -} - -/** - * TestValidate class - * - */ -class TestValidate extends CakeTestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * name property - * - * @var string - */ - public $name = 'TestValidate'; - -/** - * schema property - * - * @var array - */ - protected $_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'title' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'body' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => ''), - 'number' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'modified' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - -/** - * validateNumber method - * - * @param mixed $value - * @param mixed $options - * @return void - */ - public function validateNumber($value, $options) { - $options = array_merge(array('min' => 0, 'max' => 100), $options); - $valid = ($value['number'] >= $options['min'] && $value['number'] <= $options['max']); - return $valid; - } - -/** - * validateTitle method - * - * @param mixed $value - * @return void - */ - public function validateTitle($value) { - return (!empty($value) && strpos(strtolower($value['title']), 'title-') === 0); - } - -} - -/** - * User class - * - */ -class User extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'User'; - -/** - * validate property - * - * @var array - */ - public $validate = array('user' => 'notEmpty', 'password' => 'notEmpty'); - -/** - * beforeFind() callback - * - * @return boolean - * @throws \Exception - */ - public function beforeFind($queryData) { - if (!empty($queryData['lazyLoad'])) { - if (!isset($this->Article, $this->Comment, $this->ArticleFeatured)) { - throw new \Exception('Unavailable associations'); - } - } - return true; - } - -} - -/** - * Article class - * - */ -class Article extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Article'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('User'); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Comment' => array('dependent' => true)); - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Tag'); - -/** - * validate property - * - * @var array - */ - public $validate = array( - 'user_id' => 'numeric', - 'title' => array('required' => false, 'rule' => 'notEmpty'), - 'body' => array('required' => false, 'rule' => 'notEmpty'), - ); - -/** - * beforeSaveReturn property - * - * @var boolean - */ - public $beforeSaveReturn = true; - -/** - * beforeSave method - * - * @return void - */ - public function beforeSave($options = array()) { - return $this->beforeSaveReturn; - } - -/** - * titleDuplicate method - * - * @param string $title - * @return void - */ - public static function titleDuplicate($title) { - if ($title === 'My Article Title') { - return false; - } - return true; - } - -} - -/** - * Model stub for beforeDelete testing - * - * @see #250 - */ -class BeforeDeleteComment extends CakeTestModel { - - public $name = 'BeforeDeleteComment'; - - public $useTable = 'comments'; - - public function beforeDelete($cascade = true) { - $db = $this->getDataSource(); - $db->delete($this, array($this->alias . '.' . $this->primaryKey => array(1, 3))); - return true; - } - -} - -/** - * NumericArticle class - * - */ -class NumericArticle extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'NumericArticle'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'numeric_articles'; - -} - -/** - * Article10 class - * - */ -class Article10 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Article10'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'articles'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Comment' => array('dependent' => true, 'exclusive' => true)); - -} - -/** - * ArticleFeatured class - * - */ -class ArticleFeatured extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ArticleFeatured'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('User', 'Category'); - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array('Featured'); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Comment' => array('className' => 'Comment', 'dependent' => true)); - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Tag'); - -/** - * validate property - * - * @var array - */ - public $validate = array('user_id' => 'numeric', 'title' => 'notEmpty', 'body' => 'notEmpty'); - -} - -/** - * Featured class - * - */ -class Featured extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Featured'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('ArticleFeatured', 'Category'); -} - -/** - * Tag class - * - */ -class Tag extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Tag'; -} - -/** - * ArticlesTag class - * - */ -class ArticlesTag extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ArticlesTag'; -} - -/** - * ArticleFeaturedsTag class - * - */ -class ArticleFeaturedsTag extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ArticleFeaturedsTag'; -} - -/** - * Comment class - * - */ -class Comment extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Comment'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Article', 'User'); - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array('Attachment' => array('dependent' => true)); -} - -/** - * Modified Comment Class has afterFind Callback - * - */ -class ModifiedComment extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Comment'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'comments'; - -/** - * Property used to toggle filtering of results - * - * @var boolean - */ - public $remove = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Article'); - -/** - * afterFind callback - * - * @return void - */ - public function afterFind($results, $primary = false) { - if (isset($results[0])) { - $results[0]['Comment']['callback'] = 'Fire'; - } - if ($this->remove) { - return array(); - } - return $results; - } - -} - -/** - * Modified Comment Class has afterFind Callback - * - */ -class AgainModifiedComment extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Comment'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'comments'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Article'); - -/** - * afterFind callback - * - * @return void - */ - public function afterFind($results, $primary = false) { - if (isset($results[0])) { - $results[0]['Comment']['querytype'] = $this->findQueryType; - } - return $results; - } - -} - -/** - * MergeVarPluginAppModel class - * - */ -class MergeVarPluginAppModel extends Model { - -} - -/** - * MergeVarPluginPost class - * - */ -class MergeVarPluginPost extends MergeVarPluginAppModel { - -/** - * actsAs parameter - * - * @var array - */ - public $actsAs = array( - 'Tree' - ); - -/** - * useTable parameter - * - * @var string - */ - public $useTable = 'posts'; -} - -/** - * MergeVarPluginComment class - * - */ -class MergeVarPluginComment extends MergeVarPluginAppModel { - -/** - * useTable parameter - * - * @var string - */ - public $useTable = 'comments'; -} - -/** - * Attachment class - * - */ -class Attachment extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Attachment'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Comment'); -} - -/** - * ModifiedAttachment class - * - */ -class ModifiedAttachment extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ModifiedAttachment'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'attachments'; - -/** - * afterFind callback - * - * @return void - */ - public function afterFind($results, $primary = false) { - if (isset($results['id'])) { - $results['callback'] = 'Fired'; - } - return $results; - } - -} - -/** - * Category class - * - */ -class Category extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Category'; -} - -/** - * CategoryThread class - * - */ -class CategoryThread extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'CategoryThread'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('ParentCategory' => array('className' => 'CategoryThread', 'foreignKey' => 'parent_id')); -} - -/** - * Apple class - * - */ -class Apple extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Apple'; - -/** - * validate property - * - * @var array - */ - public $validate = array('name' => 'notEmpty'); - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array('Sample'); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Child' => array('className' => 'Apple', 'dependent' => true)); - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Parent' => array('className' => 'Apple', 'foreignKey' => 'apple_id')); -} - -/** - * Sample class - * - */ -class Sample extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Sample'; - -/** - * belongsTo property - * - * @var string - */ - public $belongsTo = 'Apple'; -} - -/** - * AnotherArticle class - * - */ -class AnotherArticle extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'AnotherArticle'; - -/** - * hasMany property - * - * @var string - */ - public $hasMany = 'Home'; -} - -/** - * Advertisement class - * - */ -class Advertisement extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Advertisement'; - -/** - * hasMany property - * - * @var string - */ - public $hasMany = 'Home'; -} - -/** - * Home class - * - */ -class Home extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Home'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('AnotherArticle', 'Advertisement'); -} - -/** - * Post class - * - */ -class Post extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Post'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Author'); - - public function beforeFind($queryData) { - if (isset($queryData['connection'])) { - $this->useDbConfig = $queryData['connection']; - } - return true; - } - - public function afterFind($results, $primary = false) { - $this->useDbConfig = 'test'; - return $results; - } - -} - -/** - * Author class - * - */ -class Author extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Author'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Post'); - -/** - * afterFind method - * - * @param array $results - * @return void - */ - public function afterFind($results, $primary = false) { - $results[0]['Author']['test'] = 'working'; - return $results; - } - -} - -/** - * ModifiedAuthor class - * - */ -class ModifiedAuthor extends Author { - -/** - * name property - * - * @var string - */ - public $name = 'Author'; - -/** - * afterFind method - * - * @param array $results - * @return void - */ - public function afterFind($results, $primary = false) { - foreach ($results as $index => $result) { - $results[$index]['Author']['user'] .= ' (CakePHP)'; - } - return $results; - } - -} - -/** - * Project class - * - */ -class Project extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Project'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Thread'); -} - -/** - * Thread class - * - */ -class Thread extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Thread'; - -/** - * hasMany property - * - * @var array - */ - public $belongsTo = array('Project'); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Message'); -} - -/** - * Message class - * - */ -class Message extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Message'; - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array('Bid'); -} - -/** - * Bid class - * - */ -class Bid extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Bid'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Message'); -} - -/** - * BiddingMessage class - * - */ -class BiddingMessage extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'BiddingMessage'; - -/** - * primaryKey property - * - * @var string - */ - public $primaryKey = 'bidding'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'Bidding' => array( - 'foreignKey' => false, - 'conditions' => array('BiddingMessage.bidding = Bidding.bid') - ) - ); -} - -/** - * Bidding class - * - */ -class Bidding extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Bidding'; - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array( - 'BiddingMessage' => array( - 'foreignKey' => false, - 'conditions' => array('BiddingMessage.bidding = Bidding.bid'), - 'dependent' => true - ) - ); -} - -/** - * NodeAfterFind class - * - */ -class NodeAfterFind extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'NodeAfterFind'; - -/** - * validate property - * - * @var array - */ - public $validate = array('name' => 'notEmpty'); - -/** - * useTable property - * - * @var string - */ - public $useTable = 'apples'; - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array('Sample' => array('className' => 'NodeAfterFindSample')); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Child' => array('className' => 'NodeAfterFind', 'dependent' => true)); - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Parent' => array('className' => 'NodeAfterFind', 'foreignKey' => 'apple_id')); - -/** - * afterFind method - * - * @param mixed $results - * @return array - */ - public function afterFind($results, $primary = false) { - return $results; - } - -} - -/** - * NodeAfterFindSample class - * - */ -class NodeAfterFindSample extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'NodeAfterFindSample'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'samples'; - -/** - * belongsTo property - * - * @var string - */ - public $belongsTo = 'NodeAfterFind'; -} - -/** - * NodeNoAfterFind class - * - */ -class NodeNoAfterFind extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'NodeAfterFind'; - -/** - * validate property - * - * @var array - */ - public $validate = array('name' => 'notEmpty'); - -/** - * useTable property - * - * @var string - */ - public $useTable = 'apples'; - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array('Sample' => array('className' => 'NodeAfterFindSample')); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Child' => array('className' => 'NodeAfterFind', 'dependent' => true)); - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Parent' => array('className' => 'NodeAfterFind', 'foreignKey' => 'apple_id')); -} - -/** - * Node class - * - */ -class Node extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Node'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array( - 'ParentNode' => array( - 'className' => 'Node', - 'joinTable' => 'dependency', - 'with' => 'Dependency', - 'foreignKey' => 'child_id', - 'associationForeignKey' => 'parent_id', - ) - ); -} - -/** - * Dependency class - * - */ -class Dependency extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Dependency'; -} - -/** - * ModelA class - * - */ -class ModelA extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ModelA'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'apples'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('ModelB', 'ModelC'); -} - -/** - * ModelB class - * - */ -class ModelB extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ModelB'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'messages'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('ModelD'); -} - -/** - * ModelC class - * - */ -class ModelC extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ModelC'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'bids'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('ModelD'); -} - -/** - * ModelD class - * - */ -class ModelD extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ModelD'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'threads'; -} - -/** - * Something class - * - */ -class Something extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Something'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('SomethingElse' => array('with' => array('JoinThing' => array('doomed')))); -} - -/** - * SomethingElse class - * - */ -class SomethingElse extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'SomethingElse'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Something' => array('with' => 'JoinThing')); - -/** - * afterFind callBack - * - * @param array $results - * @param bool $primary - * @return array - */ - public function afterFind($results, $primary = false) { - foreach ($results as $key => $result) { - if (!empty($result[$this->alias]) && is_array($result[$this->alias])) { - $results[$key][$this->alias]['afterFind'] = 'Successfully added by AfterFind'; - } - } - return $results; - } - -} - -/** - * JoinThing class - * - */ -class JoinThing extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'JoinThing'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Something', 'SomethingElse'); - -/** - * afterFind callBack - * - * @param array $results - * @param bool $primary - * @return array - */ - public function afterFind($results, $primary = false) { - foreach ($results as $key => $result) { - if (!empty($result[$this->alias]) && is_array($result[$this->alias])) { - $results[$key][$this->alias]['afterFind'] = 'Successfully added by AfterFind'; - } - } - return $results; - } - -} - -/** - * Portfolio class - * - */ -class Portfolio extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Portfolio'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Item'); -} - -/** - * Item class - * - */ -class Item extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Item'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Syfile' => array('counterCache' => true)); - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Portfolio' => array('unique' => false)); -} - -/** - * ItemsPortfolio class - * - */ -class ItemsPortfolio extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ItemsPortfolio'; -} - -/** - * Syfile class - * - */ -class Syfile extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Syfile'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Image'); -} - -/** - * Image class - * - */ -class Image extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Image'; -} - -/** - * DeviceType class - * - */ -class DeviceType extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'DeviceType'; - -/** - * order property - * - * @var array - */ - public $order = array('DeviceType.order' => 'ASC'); - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'DeviceTypeCategory', 'FeatureSet', 'ExteriorTypeCategory', - 'Image' => array('className' => 'Document'), - 'Extra1' => array('className' => 'Document'), - 'Extra2' => array('className' => 'Document')); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Device' => array('order' => array('Device.id' => 'ASC'))); -} - -/** - * DeviceTypeCategory class - * - */ -class DeviceTypeCategory extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'DeviceTypeCategory'; -} - -/** - * FeatureSet class - * - */ -class FeatureSet extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'FeatureSet'; -} - -/** - * ExteriorTypeCategory class - * - */ -class ExteriorTypeCategory extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ExteriorTypeCategory'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Image' => array('className' => 'Device')); -} - -/** - * Document class - * - */ -class Document extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Document'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('DocumentDirectory'); -} - -/** - * Device class - * - */ -class Device extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Device'; -} - -/** - * DocumentDirectory class - * - */ -class DocumentDirectory extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'DocumentDirectory'; -} - -/** - * PrimaryModel class - * - */ -class PrimaryModel extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'PrimaryModel'; -} - -/** - * SecondaryModel class - * - */ -class SecondaryModel extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'SecondaryModel'; -} - -/** - * JoinA class - * - */ -class JoinA extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'JoinA'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('JoinB', 'JoinC'); -} - -/** - * JoinB class - * - */ -class JoinB extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'JoinB'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('JoinA'); -} - -/** - * JoinC class - * - */ -class JoinC extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'JoinC'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('JoinA'); -} - -/** - * ThePaper class - * - */ -class ThePaper extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ThePaper'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'apples'; - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array('Itself' => array('className' => 'ThePaper', 'foreignKey' => 'apple_id')); - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Monkey' => array('joinTable' => 'the_paper_monkies', 'order' => 'id')); -} - -/** - * Monkey class - * - */ -class Monkey extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Monkey'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'devices'; -} - -/** - * AssociationTest1 class - * - */ -class AssociationTest1 extends CakeTestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'join_as'; - -/** - * name property - * - * @var string - */ - public $name = 'AssociationTest1'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('AssociationTest2' => array( - 'unique' => false, 'joinTable' => 'join_as_join_bs', 'foreignKey' => false - )); -} - -/** - * AssociationTest2 class - * - */ -class AssociationTest2 extends CakeTestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'join_bs'; - -/** - * name property - * - * @var string - */ - public $name = 'AssociationTest2'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('AssociationTest1' => array( - 'unique' => false, 'joinTable' => 'join_as_join_bs' - )); -} - -/** - * Callback class - * - */ -class Callback extends CakeTestModel { - -} - -/** - * CallbackPostTestModel class - * - */ -class CallbackPostTestModel extends CakeTestModel { - - public $useTable = 'posts'; - -/** - * variable to control return of beforeValidate - * - * @var boolean - */ - public $beforeValidateReturn = true; - -/** - * variable to control return of beforeSave - * - * @var boolean - */ - public $beforeSaveReturn = true; - -/** - * variable to control return of beforeDelete - * - * @var boolean - */ - public $beforeDeleteReturn = true; - -/** - * beforeSave callback - * - * @return boolean - */ - public function beforeSave($options = array()) { - return $this->beforeSaveReturn; - } - -/** - * beforeValidate callback - * - * @param array $options Options passed from Model::save(). - * @return boolean True if validate operation should continue, false to abort - * @see Model::save() - */ - public function beforeValidate($options = array()) { - return $this->beforeValidateReturn; - } - -/** - * beforeDelete callback - * - * @return boolean - */ - public function beforeDelete($cascade = true) { - return $this->beforeDeleteReturn; - } - -} - -/** - * Uuid class - * - */ -class Uuid extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Uuid'; -} - -/** - * DataTest class - * - */ -class DataTest extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'DataTest'; -} - -/** - * TheVoid class - * - */ -class TheVoid extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TheVoid'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; -} - -/** - * ValidationTest1 class - * - */ -class ValidationTest1 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ValidationTest1'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * schema property - * - * @var array - */ - protected $_schema = array(); - -/** - * validate property - * - * @var array - */ - public $validate = array( - 'title' => 'notEmpty', - 'published' => 'customValidationMethod', - 'body' => array( - 'notEmpty', - '/^.{5,}$/s' => 'no matchy', - '/^[0-9A-Za-z \\.]{1,}$/s' - ) - ); - -/** - * customValidationMethod method - * - * @param mixed $data - * @return void - */ - public function customValidationMethod($data) { - return $data === 1; - } - -/** - * Custom validator with parameters + default values - * - * @return array - */ - public function customValidatorWithParams($data, $validator, $or = true, $ignoreOnSame = 'id') { - $this->validatorParams = get_defined_vars(); - unset($this->validatorParams['this']); - return true; - } - -/** - * Custom validator with message - * - * @return array - */ - public function customValidatorWithMessage($data) { - return 'This field will *never* validate! Muhahaha!'; - } - -/** - * Test validation with many parameters - * - * @return void - */ - public function customValidatorWithSixParams($data, $one = 1, $two = 2, $three = 3, $four = 4, $five = 5, $six = 6) { - $this->validatorParams = get_defined_vars(); - unset($this->validatorParams['this']); - return true; - } - -} - -/** - * ValidationTest2 class - * - */ -class ValidationTest2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ValidationTest2'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * validate property - * - * @var array - */ - public $validate = array( - 'title' => 'notEmpty', - 'published' => 'customValidationMethod', - 'body' => array( - 'notEmpty', - '/^.{5,}$/s' => 'no matchy', - '/^[0-9A-Za-z \\.]{1,}$/s' - ) - ); - -/** - * customValidationMethod method - * - * @param mixed $data - * @return void - */ - public function customValidationMethod($data) { - return $data === 1; - } - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - return array(); - } - -} - -/** - * Person class - * - */ -class Person extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Person'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'Mother' => array( - 'className' => 'Person', - 'foreignKey' => 'mother_id' - ), - 'Father' => array( - 'className' => 'Person', - 'foreignKey' => 'father_id' - ) - ); -} - -/** - * UnderscoreField class - * - */ -class UnderscoreField extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'UnderscoreField'; -} - -/** - * Product class - * - */ -class Product extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Product'; -} - -/** - * Story class - * - */ -class Story extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Story'; - -/** - * primaryKey property - * - * @var string - */ - public $primaryKey = 'story'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Tag' => array('foreignKey' => 'story')); - -/** - * validate property - * - * @var array - */ - public $validate = array('title' => 'notEmpty'); -} - -/** - * Cd class - * - */ -class Cd extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Cd'; - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array( - 'OverallFavorite' => array( - 'foreignKey' => 'model_id', - 'dependent' => true, - 'conditions' => array('model_type' => 'Cd') - ) - ); - -} - -/** - * Book class - * - */ -class Book extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Book'; - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array( - 'OverallFavorite' => array( - 'foreignKey' => 'model_id', - 'dependent' => true, - 'conditions' => 'OverallFavorite.model_type = \'Book\'' - ) - ); - -} - -/** - * OverallFavorite class - * - */ -class OverallFavorite extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'OverallFavorite'; -} - -/** - * MyUser class - * - */ -class MyUser extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'MyUser'; - -/** - * undocumented variable - * - * @var string - */ - public $hasAndBelongsToMany = array('MyCategory'); -} - -/** - * MyCategory class - * - */ -class MyCategory extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'MyCategory'; - -/** - * undocumented variable - * - * @var string - */ - public $hasAndBelongsToMany = array('MyProduct', 'MyUser'); -} - -/** - * MyProduct class - * - */ -class MyProduct extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'MyProduct'; - -/** - * undocumented variable - * - * @var string - */ - public $hasAndBelongsToMany = array('MyCategory'); -} - -/** - * MyCategoriesMyUser class - * - */ -class MyCategoriesMyUser extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'MyCategoriesMyUser'; -} - -/** - * MyCategoriesMyProduct class - * - */ -class MyCategoriesMyProduct extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'MyCategoriesMyProduct'; -} - -/** - * NumberTree class - * - */ -class NumberTree extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'NumberTree'; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Tree'); - -/** - * initialize method - * - * @param integer $levelLimit - * @param integer $childLimit - * @param mixed $currentLevel - * @param mixed $parent_id - * @param string $prefix - * @param boolean $hierarchal - * @return void - */ - public function initialize($levelLimit = 3, $childLimit = 3, $currentLevel = null, $parentId = null, $prefix = '1', $hierarchal = true) { - if (!$parentId) { - $db = ConnectionManager::getDataSource($this->useDbConfig); - $db->truncate($this->table); - $this->save(array($this->name => array('name' => '1. Root'))); - $this->initialize($levelLimit, $childLimit, 1, $this->id, '1', $hierarchal); - $this->create(array()); - } - - if (!$currentLevel || $currentLevel > $levelLimit) { - return; - } - - for ($i = 1; $i <= $childLimit; $i++) { - $name = $prefix . '.' . $i; - $data = array($this->name => array('name' => $name)); - $this->create($data); - - if ($hierarchal) { - if ($this->name === 'UnconventionalTree') { - $data[$this->name]['join'] = $parentId; - } else { - $data[$this->name]['parent_id'] = $parentId; - } - } - $this->save($data); - $this->initialize($levelLimit, $childLimit, $currentLevel + 1, $this->id, $name, $hierarchal); - } - } - -} - -/** - * NumberTreeTwo class - * - */ -class NumberTreeTwo extends NumberTree { - -/** - * name property - * - * @var string - */ - public $name = 'NumberTreeTwo'; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array(); -} - -/** - * FlagTree class - * - */ -class FlagTree extends NumberTree { - -/** - * name property - * - * @var string - */ - public $name = 'FlagTree'; -} - -/** - * UnconventionalTree class - * - */ -class UnconventionalTree extends NumberTree { - -/** - * name property - * - * @var string - */ - public $name = 'UnconventionalTree'; - - public $actsAs = array( - 'Tree' => array( - 'parent' => 'join', - 'left' => 'left', - 'right' => 'right' - ) - ); - -} - -/** - * UuidTree class - * - */ -class UuidTree extends NumberTree { - -/** - * name property - * - * @var string - */ - public $name = 'UuidTree'; -} - -/** - * Campaign class - * - */ -class Campaign extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Campaign'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Ad' => array('fields' => array('id', 'campaign_id', 'name'))); -} - -/** - * Ad class - * - */ -class Ad extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Ad'; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Tree'); - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Campaign'); -} - -/** - * AfterTree class - * - */ -class AfterTree extends NumberTree { - -/** - * name property - * - * @var string - */ - public $name = 'AfterTree'; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Tree'); - - public function afterSave($created, $options = array()) { - if ($created && isset($this->data['AfterTree'])) { - $this->data['AfterTree']['name'] = 'Six and One Half Changed in AfterTree::afterSave() but not in database'; - } - } - -} - -/** - * Nonconformant Content class - * - */ -class Content extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Content'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'Content'; - -/** - * primaryKey property - * - * @var string - */ - public $primaryKey = 'iContentId'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Account' => array('className' => 'Account', 'with' => 'ContentAccount', 'joinTable' => 'ContentAccounts', 'foreignKey' => 'iContentId', 'associationForeignKey', 'iAccountId')); -} - -/** - * Nonconformant Account class - * - */ -class Account extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Account'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'Accounts'; - -/** - * primaryKey property - * - * @var string - */ - public $primaryKey = 'iAccountId'; -} - -/** - * Nonconformant ContentAccount class - * - */ -class ContentAccount extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ContentAccount'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'ContentAccounts'; - -/** - * primaryKey property - * - * @var string - */ - public $primaryKey = 'iContentAccountsId'; -} - -/** - * FilmFile class - * - */ -class FilmFile extends CakeTestModel { - - public $name = 'FilmFile'; - -} - -/** - * Basket test model - * - */ -class Basket extends CakeTestModel { - - public $name = 'Basket'; - - public $belongsTo = array( - 'FilmFile' => array( - 'className' => 'FilmFile', - 'foreignKey' => 'object_id', - 'conditions' => "Basket.type = 'file'", - 'fields' => '', - 'order' => '' - ) - ); - -} - -/** - * TestPluginArticle class - * - */ -class TestPluginArticle extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestPluginArticle'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('User'); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'TestPluginComment' => array( - 'className' => 'TestPlugin.TestPluginComment', - 'foreignKey' => 'article_id', - 'dependent' => true - ) - ); -} - -/** - * TestPluginComment class - * - */ -class TestPluginComment extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestPluginComment'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'TestPluginArticle' => array( - 'className' => 'TestPlugin.TestPluginArticle', - 'foreignKey' => 'article_id', - ), - 'TestPlugin.User' - ); -} - -/** - * Uuidportfolio class - * - */ -class Uuidportfolio extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Uuidportfolio'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Uuiditem'); -} - -/** - * Uuiditem class - * - */ -class Uuiditem extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Uuiditem'; - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('Uuidportfolio' => array('with' => 'UuiditemsUuidportfolioNumericid')); - -} - -/** - * UuiditemsPortfolio class - * - */ -class UuiditemsUuidportfolio extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'UuiditemsUuidportfolio'; -} - -/** - * UuiditemsPortfolioNumericid class - * - */ -class UuiditemsUuidportfolioNumericid extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'UuiditemsUuidportfolioNumericid'; -} - -/** - * TranslateTestModel class. - * - */ -class TranslateTestModel extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TranslateTestModel'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'i18n'; - -/** - * displayField property - * - * @var string - */ - public $displayField = 'field'; -} - -/** - * TranslateTestModel class. - * - */ -class TranslateWithPrefix extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TranslateWithPrefix'; - -/** - * tablePrefix property - * - * @var string - */ - public $tablePrefix = 'i18n_'; - -/** - * displayField property - * - * @var string - */ - public $displayField = 'field'; - -} - -/** - * TranslatedItem class. - * - */ -class TranslatedItem extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TranslatedItem'; - -/** - * cacheQueries property - * - * @var boolean - */ - public $cacheQueries = false; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Translate' => array('content', 'title')); - -/** - * translateModel property - * - * @var string - */ - public $translateModel = 'TranslateTestModel'; - -} - -/** - * TranslatedItem class. - * - */ -class TranslatedItem2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TranslatedItem'; - -/** - * cacheQueries property - * - * @var boolean - */ - public $cacheQueries = false; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Translate' => array('content', 'title')); - -/** - * translateModel property - * - * @var string - */ - public $translateModel = 'TranslateWithPrefix'; - -} - -/** - * TranslatedItemWithTable class. - * - */ -class TranslatedItemWithTable extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TranslatedItemWithTable'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'translated_items'; - -/** - * cacheQueries property - * - * @var boolean - */ - public $cacheQueries = false; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Translate' => array('content', 'title')); - -/** - * translateModel property - * - * @var string - */ - public $translateModel = 'TranslateTestModel'; - -/** - * translateTable property - * - * @var string - */ - public $translateTable = 'another_i18n'; - -} - -/** - * TranslateArticleModel class. - * - */ -class TranslateArticleModel extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TranslateArticleModel'; - -/** - * useTable property - * - * @var string - */ - public $useTable = 'article_i18n'; - -/** - * displayField property - * - * @var string - */ - public $displayField = 'field'; - -} - -/** - * TranslatedArticle class. - * - */ -class TranslatedArticle extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TranslatedArticle'; - -/** - * cacheQueries property - * - * @var boolean - */ - public $cacheQueries = false; - -/** - * actsAs property - * - * @var array - */ - public $actsAs = array('Translate' => array('title', 'body')); - -/** - * translateModel property - * - * @var string - */ - public $translateModel = 'TranslateArticleModel'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('User'); - -/** - * belongsTo property - * - * @var array - */ - public $hasMany = array('TranslatedItem'); - -} - -class CounterCacheUser extends CakeTestModel { - - public $name = 'CounterCacheUser'; - - public $alias = 'User'; - - public $hasMany = array( - 'Post' => array( - 'className' => 'CounterCachePost', - 'foreignKey' => 'user_id' - ) - ); -} - -class CounterCachePost extends CakeTestModel { - - public $name = 'CounterCachePost'; - - public $alias = 'Post'; - - public $belongsTo = array( - 'User' => array( - 'className' => 'CounterCacheUser', - 'foreignKey' => 'user_id', - 'counterCache' => true - ) - ); -} - -class CounterCacheUserNonstandardPrimaryKey extends CakeTestModel { - - public $name = 'CounterCacheUserNonstandardPrimaryKey'; - - public $alias = 'User'; - - public $primaryKey = 'uid'; - - public $hasMany = array( - 'Post' => array( - 'className' => 'CounterCachePostNonstandardPrimaryKey', - 'foreignKey' => 'uid' - ) - ); - -} - -class CounterCachePostNonstandardPrimaryKey extends CakeTestModel { - - public $name = 'CounterCachePostNonstandardPrimaryKey'; - - public $alias = 'Post'; - - public $primaryKey = 'pid'; - - public $belongsTo = array( - 'User' => array( - 'className' => 'CounterCacheUserNonstandardPrimaryKey', - 'foreignKey' => 'uid', - 'counterCache' => true - ) - ); - -} - -class ArticleB extends CakeTestModel { - - public $name = 'ArticleB'; - - public $useTable = 'articles'; - - public $hasAndBelongsToMany = array( - 'TagB' => array( - 'className' => 'TagB', - 'joinTable' => 'articles_tags', - 'foreignKey' => 'article_id', - 'associationForeignKey' => 'tag_id' - ) - ); - -} - -class TagB extends CakeTestModel { - - public $name = 'TagB'; - - public $useTable = 'tags'; - - public $hasAndBelongsToMany = array( - 'ArticleB' => array( - 'className' => 'ArticleB', - 'joinTable' => 'articles_tags', - 'foreignKey' => 'tag_id', - 'associationForeignKey' => 'article_id' - ) - ); - -} - -class Fruit extends CakeTestModel { - - public $name = 'Fruit'; - - public $hasAndBelongsToMany = array( - 'UuidTag' => array( - 'className' => 'UuidTag', - 'joinTable' => 'fruits_uuid_tags', - 'foreignKey' => 'fruit_id', - 'associationForeignKey' => 'uuid_tag_id', - 'with' => 'FruitsUuidTag' - ) - ); - -} - -class FruitsUuidTag extends CakeTestModel { - - public $name = 'FruitsUuidTag'; - - public $primaryKey = false; - - public $belongsTo = array( - 'UuidTag' => array( - 'className' => 'UuidTag', - 'foreignKey' => 'uuid_tag_id', - ), - 'Fruit' => array( - 'className' => 'Fruit', - 'foreignKey' => 'fruit_id', - ) - ); - -} - -class UuidTag extends CakeTestModel { - - public $name = 'UuidTag'; - - public $hasAndBelongsToMany = array( - 'Fruit' => array( - 'className' => 'Fruit', - 'joinTable' => 'fruits_uuid_tags', - 'foreign_key' => 'uuid_tag_id', - 'associationForeignKey' => 'fruit_id', - 'with' => 'FruitsUuidTag' - ) - ); - -} - -class FruitNoWith extends CakeTestModel { - - public $name = 'Fruit'; - - public $useTable = 'fruits'; - - public $hasAndBelongsToMany = array( - 'UuidTag' => array( - 'className' => 'UuidTagNoWith', - 'joinTable' => 'fruits_uuid_tags', - 'foreignKey' => 'fruit_id', - 'associationForeignKey' => 'uuid_tag_id', - ) - ); - -} - -class UuidTagNoWith extends CakeTestModel { - - public $name = 'UuidTag'; - - public $useTable = 'uuid_tags'; - - public $hasAndBelongsToMany = array( - 'Fruit' => array( - 'className' => 'FruitNoWith', - 'joinTable' => 'fruits_uuid_tags', - 'foreign_key' => 'uuid_tag_id', - 'associationForeignKey' => 'fruit_id', - ) - ); - -} - -class ProductUpdateAll extends CakeTestModel { - - public $name = 'ProductUpdateAll'; - - public $useTable = 'product_update_all'; - -} - -class GroupUpdateAll extends CakeTestModel { - - public $name = 'GroupUpdateAll'; - - public $useTable = 'group_update_all'; - -} - -class TransactionTestModel extends CakeTestModel { - - public $name = 'TransactionTestModel'; - - public $useTable = 'samples'; - - public function afterSave($created, $options = array()) { - $data = array( - array('apple_id' => 1, 'name' => 'sample6'), - ); - $this->saveAll($data, array('atomic' => true, 'callbacks' => false)); - } - -} - -class TransactionManyTestModel extends CakeTestModel { - - public $name = 'TransactionManyTestModel'; - - public $useTable = 'samples'; - - public function afterSave($created, $options = array()) { - $data = array( - array('apple_id' => 1, 'name' => 'sample6'), - ); - $this->saveMany($data, array('atomic' => true, 'callbacks' => false)); - } - -} - -class Site extends CakeTestModel { - - public $name = 'Site'; - - public $useTable = 'sites'; - - public $hasAndBelongsToMany = array( - 'Domain' => array('unique' => 'keepExisting'), - ); -} - -class Domain extends CakeTestModel { - - public $name = 'Domain'; - - public $useTable = 'domains'; - - public $hasAndBelongsToMany = array( - 'Site' => array('unique' => 'keepExisting'), - ); -} - -/** - * TestModel class - * - */ -class TestModel extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * schema property - * - * @var array - */ - protected $_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '11'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), - 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), - 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'), - 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), - 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => '155'), - 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - -/** - * find method - * - * @param mixed $conditions - * @param mixed $fields - * @param mixed $order - * @param mixed $recursive - * @return void - */ - public function find($conditions = null, $fields = null, $order = null, $recursive = null) { - return array($conditions, $fields); - } - -/** - * findAll method - * - * @param mixed $conditions - * @param mixed $fields - * @param mixed $order - * @param mixed $recursive - * @return void - */ - public function findAll($conditions = null, $fields = null, $order = null, $recursive = null) { - return $conditions; - } - -} - -/** - * TestModel2 class - * - */ -class TestModel2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel2'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; -} - -/** - * TestModel4 class - * - */ -class TestModel3 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel3'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; -} - -/** - * TestModel4 class - * - */ -class TestModel4 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel4'; - -/** - * table property - * - * @var string - */ - public $table = 'test_model4'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'TestModel4Parent' => array( - 'className' => 'TestModel4', - 'foreignKey' => 'parent_id' - ) - ); - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array( - 'TestModel5' => array( - 'className' => 'TestModel5', - 'foreignKey' => 'test_model4_id' - ) - ); - -/** - * hasAndBelongsToMany property - * - * @var array - */ - public $hasAndBelongsToMany = array('TestModel7' => array( - 'className' => 'TestModel7', - 'joinTable' => 'test_model4_test_model7', - 'foreignKey' => 'test_model4_id', - 'associationForeignKey' => 'test_model7_id', - 'with' => 'TestModel4TestModel7' - )); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * TestModel4TestModel7 class - * - */ -class TestModel4TestModel7 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel4TestModel7'; - -/** - * table property - * - * @var string - */ - public $table = 'test_model4_test_model7'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'test_model4_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'test_model7_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8') - ); - } - return $this->_schema; - } - -} - -/** - * TestModel5 class - * - */ -class TestModel5 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel5'; - -/** - * table property - * - * @var string - */ - public $table = 'test_model5'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('TestModel4' => array( - 'className' => 'TestModel4', - 'foreignKey' => 'test_model4_id' - )); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('TestModel6' => array( - 'className' => 'TestModel6', - 'foreignKey' => 'test_model5_id' - )); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'test_model4_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * TestModel6 class - * - */ -class TestModel6 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel6'; - -/** - * table property - * - * @var string - */ - public $table = 'test_model6'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'TestModel5' => array( - 'className' => 'TestModel5', - 'foreignKey' => 'test_model5_id' - ) - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'test_model5_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * TestModel7 class - * - */ -class TestModel7 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel7'; - -/** - * table property - * - * @var string - */ - public $table = 'test_model7'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * TestModel8 class - * - */ -class TestModel8 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel8'; - -/** - * table property - * - * @var string - */ - public $table = 'test_model8'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array( - 'TestModel9' => array( - 'className' => 'TestModel9', - 'foreignKey' => 'test_model8_id', - 'conditions' => 'TestModel9.name != \'mariano\'' - ) - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'test_model9_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * TestModel9 class - * - */ -class TestModel9 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'TestModel9'; - -/** - * table property - * - * @var string - */ - public $table = 'test_model9'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'TestModel8' => array( - 'className' => 'TestModel8', - 'foreignKey' => 'test_model8_id', - 'conditions' => 'TestModel8.name != \'larry\'' - ) - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'test_model8_id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '11'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * Level class - * - */ -class Level extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Level'; - -/** - * table property - * - * @var string - */ - public $table = 'level'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'Group' => array( - 'className' => 'Group' - ), - 'User2' => array( - 'className' => 'User2' - ) - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20'), - ); - } - return $this->_schema; - } - -} - -/** - * Group class - * - */ -class Group extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Group'; - -/** - * table property - * - * @var string - */ - public $table = 'group'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('Level'); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array('Category2', 'User2'); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'level_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20'), - ); - } - return $this->_schema; - } - -} - -/** - * User2 class - * - */ -class User2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'User2'; - -/** - * table property - * - * @var string - */ - public $table = 'user'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'Group' => array( - 'className' => 'Group' - ), - 'Level' => array( - 'className' => 'Level' - ) - ); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'Article2' => array( - 'className' => 'Article2' - ), - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'group_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'level_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20'), - ); - } - return $this->_schema; - } - -} - -/** - * Category2 class - * - */ -class Category2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Category2'; - -/** - * table property - * - * @var string - */ - public $table = 'category'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'Group' => array( - 'className' => 'Group', - 'foreignKey' => 'group_id' - ), - 'ParentCat' => array( - 'className' => 'Category2', - 'foreignKey' => 'parent_id' - ) - ); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'ChildCat' => array( - 'className' => 'Category2', - 'foreignKey' => 'parent_id' - ), - 'Article2' => array( - 'className' => 'Article2', - 'order' => 'Article2.published_date DESC', - 'foreignKey' => 'category_id', - 'limit' => '3') - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), - 'group_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), - 'parent_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), - 'name' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), - 'icon' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), - 'description' => array('type' => 'text', 'null' => false, 'default' => '', 'length' => null), - - ); - } - return $this->_schema; - } - -} - -/** - * Article2 class - * - */ -class Article2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Article2'; - -/** - * table property - * - * @var string - */ - public $table = 'articles'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'Category2' => array('className' => 'Category2'), - 'User2' => array('className' => 'User2') - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), - 'category_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'user_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'rate_count' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'rate_sum' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'viewed' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'version' => array('type' => 'string', 'null' => true, 'default' => '', 'length' => '45'), - 'title' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '200'), - 'intro' => array('text' => 'string', 'null' => true, 'default' => '', 'length' => null), - 'comments' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '4'), - 'body' => array('text' => 'string', 'null' => true, 'default' => '', 'length' => null), - 'isdraft' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'length' => '1'), - 'allow_comments' => array('type' => 'boolean', 'null' => false, 'default' => '1', 'length' => '1'), - 'moderate_comments' => array('type' => 'boolean', 'null' => false, 'default' => '1', 'length' => '1'), - 'published' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'length' => '1'), - 'multipage' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'length' => '1'), - 'published_date' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null), - 'created' => array('type' => 'datetime', 'null' => false, 'default' => '0000-00-00 00:00:00', 'length' => null), - 'modified' => array('type' => 'datetime', 'null' => false, 'default' => '0000-00-00 00:00:00', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * CategoryFeatured2 class - * - */ -class CategoryFeatured2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'CategoryFeatured2'; - -/** - * table property - * - * @var string - */ - public $table = 'category_featured'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), - 'parent_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '10'), - 'name' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), - 'icon' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'), - 'description' => array('text' => 'string', 'null' => false, 'default' => '', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * Featured2 class - * - */ -class Featured2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Featured2'; - -/** - * table property - * - * @var string - */ - public $table = 'featured2'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'CategoryFeatured2' => array( - 'className' => 'CategoryFeatured2' - ) - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'article_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'category_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20') - ); - } - return $this->_schema; - } - -} - -/** - * Comment2 class - * - */ -class Comment2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Comment2'; - -/** - * table property - * - * @var string - */ - public $table = 'comment'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('ArticleFeatured2', 'User2'); - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'article_featured_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'user_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'name' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20') - ); - } - return $this->_schema; - } - -} - -/** - * ArticleFeatured2 class - * - */ -class ArticleFeatured2 extends CakeTestModel { - -/** - * name property - * - * @var string - */ - public $name = 'ArticleFeatured2'; - -/** - * table property - * - * @var string - */ - public $table = 'article_featured'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'CategoryFeatured2' => array('className' => 'CategoryFeatured2'), - 'User2' => array('className' => 'User2') - ); - -/** - * hasOne property - * - * @var array - */ - public $hasOne = array( - 'Featured2' => array('className' => 'Featured2') - ); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'Comment2' => array('className' => 'Comment2', 'dependent' => true) - ); - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - if (!isset($this->_schema)) { - $this->_schema = array( - 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => '10'), - 'category_featured_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'user_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => '10'), - 'title' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => '20'), - 'body' => array('text' => 'string', 'null' => true, 'default' => '', 'length' => null), - 'published' => array('type' => 'boolean', 'null' => false, 'default' => '0', 'length' => '1'), - 'published_date' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null), - 'created' => array('type' => 'datetime', 'null' => false, 'default' => '0000-00-00 00:00:00', 'length' => null), - 'modified' => array('type' => 'datetime', 'null' => false, 'default' => '0000-00-00 00:00:00', 'length' => null) - ); - } - return $this->_schema; - } - -} - -/** - * MysqlTestModel class - * - */ -class MysqlTestModel extends Model { - -/** - * name property - * - * @var string - */ - public $name = 'MysqlTestModel'; - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; - -/** - * find method - * - * @param mixed $conditions - * @param mixed $fields - * @param mixed $order - * @param mixed $recursive - * @return void - */ - public function find($conditions = null, $fields = null, $order = null, $recursive = null) { - return $conditions; - } - -/** - * findAll method - * - * @param mixed $conditions - * @param mixed $fields - * @param mixed $order - * @param mixed $recursive - * @return void - */ - public function findAll($conditions = null, $fields = null, $order = null, $recursive = null) { - return $conditions; - } - -/** - * schema method - * - * @return void - */ - public function schema($field = false) { - return array( - 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'), - 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'), - 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'), - 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), - 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), - 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'), - 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'), - 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'), - 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''), - 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''), - 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''), - 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null) - ); - } - -} - -/** - * Test model for datasource prefixes - * - */ -class PrefixTestModel extends CakeTestModel { -} - -class PrefixTestUseTableModel extends CakeTestModel { - - public $name = 'PrefixTest'; - - public $useTable = 'prefix_tests'; - -} - -/** - * ScaffoldMock class - * - */ -class ScaffoldMock extends CakeTestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'articles'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'User' => array( - 'className' => 'Cake\Test\TestCase\Model\ScaffoldUser', - 'foreignKey' => 'user_id', - ) - ); - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'Comment' => array( - 'className' => 'Cake\Test\TestCase\Model\ScaffoldComment', - 'foreignKey' => 'article_id', - ) - ); - -/** - * hasAndBelongsToMany property - * - * @var string - */ - public $hasAndBelongsToMany = array( - 'ScaffoldTag' => array( - 'className' => 'Cake\Test\TestCase\Model\ScaffoldTag', - 'foreignKey' => 'something_id', - 'associationForeignKey' => 'something_else_id', - 'joinTable' => 'join_things' - ) - ); - -} - -/** - * ScaffoldUser class - * - */ -class ScaffoldUser extends CakeTestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'users'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'Article' => array( - 'className' => 'Cake\Test\TestCase\Model\ScaffoldMock', - 'foreignKey' => 'article_id', - ) - ); -} - -/** - * ScaffoldComment class - * - */ -class ScaffoldComment extends CakeTestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'comments'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'Article' => array( - 'className' => 'Cake\Test\TestCase\Model\ScaffoldMock', - 'foreignKey' => 'article_id', - ) - ); -} - -/** - * ScaffoldTag class - * - */ -class ScaffoldTag extends CakeTestModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'tags'; - -} - -/** - * Player class - * - */ -class Player extends CakeTestModel { - - public $hasAndBelongsToMany = array( - 'Guild' => array( - 'with' => 'GuildsPlayer', - 'unique' => true, - ), - ); - -} - -/** - * Guild class - * - */ -class Guild extends CakeTestModel { - - public $hasAndBelongsToMany = array( - 'Player' => array( - 'with' => 'GuildsPlayer', - 'unique' => true, - ), - ); - -} - -/** - * GuildsPlayer class - * - */ -class GuildsPlayer extends CakeTestModel { - - public $useDbConfig = 'test2'; - - public $belongsTo = array( - 'Player', - 'Guild', - ); -} - -/** - * Armor class - * - */ -class Armor extends CakeTestModel { - - public $useDbConfig = 'test2'; - - public $hasAndBelongsToMany = array( - 'Player' => array('with' => 'ArmorsPlayer'), - ); -} - -/** - * ArmorsPlayer class - * - */ -class ArmorsPlayer extends CakeTestModel { - - public $useDbConfig = 'test_database_three'; - -} - -/** - * CustomArticle class - * - */ -class CustomArticle extends AppModel { - -/** - * useTable property - * - * @var string - */ - public $useTable = 'articles'; - -/** - * findMethods property - * - * @var array - */ - public $findMethods = array('unPublished' => true); - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array('User'); - -/** - * _findUnPublished custom find - * - * @return array - */ - protected function _findUnPublished($state, $query, $results = array()) { - if ($state === 'before') { - $query['conditions']['published'] = 'N'; - return $query; - } - return $results; - } - -/** - * Alters title data - * - * @param array $options Options passed from Model::save(). - * @return boolean True if validate operation should continue, false to abort - * @see Model::save() - */ - public function beforeValidate($options = array()) { - $this->data[$this->alias]['title'] = 'foo'; - if ($this->findMethods['unPublished'] === true) { - $this->findMethods['unPublished'] = false; - } else { - $this->findMethods['unPublished'] = 'true again'; - } - } - -} diff --git a/Cake/Test/TestCase/TestSuite/ControllerTestCaseTest.php b/Cake/Test/TestCase/TestSuite/ControllerTestCaseTest.php index 543e3b31a40..f7ef860a769 100644 --- a/Cake/Test/TestCase/TestSuite/ControllerTestCaseTest.php +++ b/Cake/Test/TestCase/TestSuite/ControllerTestCaseTest.php @@ -22,13 +22,12 @@ use Cake\Core\App; use Cake\Core\Configure; use Cake\Core\Plugin; -use Cake\Model\Model; +use Cake\ORM\Table; use Cake\Routing\Router; use Cake\TestSuite\Reporter\HtmlReporter; use Cake\TestSuite\TestCase; use Cake\Utility\ClassRegistry; -require_once dirname(__DIR__) . DS . 'Model/models.php'; /** * AppController class diff --git a/Cake/Test/TestCase/Utility/ClassRegistryTest.php b/Cake/Test/TestCase/Utility/ClassRegistryTest.php deleted file mode 100644 index 5122c7c7646..00000000000 --- a/Cake/Test/TestCase/Utility/ClassRegistryTest.php +++ /dev/null @@ -1,313 +0,0 @@ - - * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * For full copyright and license information, please see the LICENSE.txt - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 1.2.0.5432 - * @license http://www.opensource.org/licenses/mit-license.php MIT License - */ -namespace Cake\Test\TestCase\Utility; - -use Cake\Core\Plugin; -use Cake\Database\ConnectionManager; -use Cake\TestSuite\Fixture\TestModel; -use Cake\TestSuite\TestCase; -use Cake\Utility\ClassRegistry; - -/** - * ClassRegisterModel class - * - */ -class ClassRegisterModel extends TestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; -} - -/** - * RegisterArticle class - * - */ -class RegisterArticle extends ClassRegisterModel { -} - -/** - * RegisterArticleFeatured class - * - */ -class RegisterArticleFeatured extends ClassRegisterModel { -} - -/** - * RegisterArticleTag class - * - */ -class RegisterArticleTag extends ClassRegisterModel { -} - -/** - * RegistryPluginAppModel class - * - */ -class RegistryPluginAppModel extends ClassRegisterModel { - -/** - * tablePrefix property - * - * @var string - */ - public $tablePrefix = 'something_'; -} - -/** - * TestRegistryPluginModel class - * - */ -class TestRegistryPluginModel extends RegistryPluginAppModel { -} - -/** - * RegisterCategory class - * - */ -class RegisterCategory extends ClassRegisterModel { -} -/** - * RegisterPrefixedDs class - * - */ -class RegisterPrefixedDs extends ClassRegisterModel { - -/** - * useDbConfig property - * - * @var string - */ - public $useDbConfig = 'doesnotexist'; -} - -/** - * Abstract class for testing ClassRegistry. - */ -abstract class ClassRegistryAbstractModel extends ClassRegisterModel { - - public abstract function doSomething(); - -} - -/** - * Interface for testing ClassRegistry - */ -interface ClassRegistryInterfaceTest { - - public function doSomething(); - -} - -/** - * ClassRegistryTest class - * - */ -class ClassRegistryTest extends TestCase { - - public function setUp() { - $this->markTestIncomplete('ClassRegistry and models do not work right now.'); - } - -/** - * testAddModel method - * - * @return void - */ - public function testAddModel() { - $Tag = ClassRegistry::init(__NAMESPACE__ . '\RegisterArticleTag'); - $this->assertInstanceOf(__NAMESPACE__ . '\RegisterArticleTag', $Tag); - - $TagCopy = ClassRegistry::isKeySet(__NAMESPACE__ . '\RegisterArticleTag'); - $this->assertTrue($TagCopy); - - $Tag->name = 'SomeNewName'; - - $TagCopy = ClassRegistry::getObject(__NAMESPACE__ . '\RegisterArticleTag'); - - $this->assertInstanceOf(__NAMESPACE__ . '\RegisterArticleTag', $TagCopy); - $this->assertSame($Tag, $TagCopy); - - $NewTag = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag')); - $this->assertInstanceOf('RegisterArticleTag', $Tag); - - $NewTagCopy = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag')); - - $this->assertNotSame($Tag, $NewTag); - $this->assertSame($NewTag, $NewTagCopy); - - $NewTag->name = 'SomeOtherName'; - $this->assertNotSame($Tag, $NewTag); - $this->assertSame($NewTag, $NewTagCopy); - - $Tag->name = 'SomeOtherName'; - $this->assertNotSame($Tag, $NewTag); - - $this->assertTrue($TagCopy->name === 'SomeOtherName'); - - $User = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false)); - $this->assertInstanceOf('AppModel', $User); - - $UserCopy = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false)); - $this->assertInstanceOf('AppModel', $UserCopy); - $this->assertEquals($User, $UserCopy); - - $Category = ClassRegistry::init(array('class' => 'RegisterCategory')); - $this->assertInstanceOf('RegisterCategory', $Category); - - $ParentCategory = ClassRegistry::init(array('class' => 'RegisterCategory', 'alias' => 'ParentCategory')); - $this->assertInstanceOf('RegisterCategory', $ParentCategory); - $this->assertNotSame($Category, $ParentCategory); - - $this->assertNotEquals($Category->alias, $ParentCategory->alias); - $this->assertEquals('RegisterCategory', $Category->alias); - $this->assertEquals('ParentCategory', $ParentCategory->alias); - } - -/** - * testClassRegistryFlush method - * - * @return void - */ - public function testClassRegistryFlush() { - ClassRegistry::init('RegisterArticleTag'); - - $ArticleTag = ClassRegistry::getObject('RegisterArticleTag'); - $this->assertInstanceOf('RegisterArticleTag', $ArticleTag); - ClassRegistry::flush(); - - $NoArticleTag = ClassRegistry::isKeySet('RegisterArticleTag'); - $this->assertFalse($NoArticleTag); - $this->assertInstanceOf('RegisterArticleTag', $ArticleTag); - } - -/** - * testAddMultipleModels method - * - * @return void - */ - public function testAddMultipleModels() { - $Article = ClassRegistry::isKeySet('Article'); - $this->assertFalse($Article); - - $Featured = ClassRegistry::isKeySet('Featured'); - $this->assertFalse($Featured); - - $Tag = ClassRegistry::isKeySet('Tag'); - $this->assertFalse($Tag); - - $models = array(array('class' => 'RegisterArticle', 'alias' => 'Article'), - array('class' => 'RegisterArticleFeatured', 'alias' => 'Featured'), - array('class' => 'RegisterArticleTag', 'alias' => 'Tag')); - - $added = ClassRegistry::init($models); - $this->assertTrue($added); - - $Article = ClassRegistry::isKeySet('Article'); - $this->assertTrue($Article); - - $Featured = ClassRegistry::isKeySet('Featured'); - $this->assertTrue($Featured); - - $Tag = ClassRegistry::isKeySet('Tag'); - $this->assertTrue($Tag); - - $Article = ClassRegistry::getObject('Article'); - $this->assertInstanceOf('RegisterArticle', $Article); - - $Featured = ClassRegistry::getObject('Featured'); - $this->assertInstanceOf('RegisterArticleFeatured', $Featured); - - $Tag = ClassRegistry::getObject('Tag'); - $this->assertInstanceOf('RegisterArticleTag', $Tag); - } - -/** - * testPluginAppModel method - * - * @return void - */ - public function testPluginAppModel() { - $TestRegistryPluginModel = ClassRegistry::isKeySet('TestRegistryPluginModel'); - $this->assertFalse($TestRegistryPluginModel); - - //Faking a plugin - Plugin::load('RegistryPlugin', array('path' => '/fake/path')); - $TestRegistryPluginModel = ClassRegistry::init('RegistryPlugin.TestRegistryPluginModel'); - $this->assertInstanceOf('TestRegistryPluginModel', $TestRegistryPluginModel); - - $this->assertEquals('something_', $TestRegistryPluginModel->tablePrefix); - - $PluginUser = ClassRegistry::init(array('class' => 'RegistryPlugin.RegisterUser', 'alias' => 'RegistryPluginUser', 'table' => false)); - $this->assertInstanceOf('RegistryPluginAppModel', $PluginUser); - - $PluginUserCopy = ClassRegistry::getObject('RegistryPluginUser'); - $this->assertInstanceOf('RegistryPluginAppModel', $PluginUserCopy); - $this->assertSame($PluginUser, $PluginUserCopy); - Plugin::unload(); - } - -/** - * Tests prefixed datasource names for test purposes - * - */ - public function testPrefixedTestDatasource() { - ClassRegistry::config(array('testing' => true)); - $Model = ClassRegistry::init(__NAMESPACE__ . '\RegisterPrefixedDs'); - $this->assertEquals('test', $Model->useDbConfig); - ClassRegistry::removeObject(__NAMESPACE__ . '\RegisterPrefixedDs'); - - $testConfig = ConnectionManager::getDataSource('test')->config; - ConnectionManager::create('test_doesnotexist', $testConfig); - - $Model = ClassRegistry::init(__NAMESPACE__ . '\RegisterArticle'); - $this->assertEquals('test', $Model->useDbConfig); - $Model = ClassRegistry::init(__NAMESPACE__ . '\RegisterPrefixedDs'); - $this->assertEquals('test_doesnotexist', $Model->useDbConfig); - } - -/** - * Tests that passing the string parameter to init() will return false if the model does not exists - * - */ - public function testInitStrict() { - $this->assertFalse(ClassRegistry::init('NonExistent', true)); - } - -/** - * Test that you cannot init() an abstract class. An exception will be raised. - * - * @expectedException Cake\Error\Exception - * @return void - */ - public function testInitAbstractClass() { - ClassRegistry::init(__NAMESPACE__ . '\ClassRegistryAbstractModel'); - } - -/** - * Test that you cannot init() an abstract class. A exception will be raised. - * - * @expectedException Cake\Error\Exception - * @return void - */ - public function testInitInterface() { - ClassRegistry::init(__NAMESPACE__ . '\ClassRegistryInterfaceTest'); - } -} diff --git a/Cake/Test/TestCase/Utility/XmlTest.php b/Cake/Test/TestCase/Utility/XmlTest.php index 83e56687ed0..da9fe45142c 100644 --- a/Cake/Test/TestCase/Utility/XmlTest.php +++ b/Cake/Test/TestCase/Utility/XmlTest.php @@ -17,60 +17,9 @@ namespace Cake\Test\TestCase\Utility; use Cake\Core\Configure; -use Cake\TestSuite\Fixture\TestModel; use Cake\TestSuite\TestCase; use Cake\Utility\Xml; -/** - * Article class - * - */ -class XmlArticle extends TestModel { - -/** - * name property - * - * @var string - */ - public $name = 'Article'; - -/** - * belongsTo property - * - * @var array - */ - public $belongsTo = array( - 'User' => array( - 'className' => 'XmlUser', - 'foreignKey' => 'user_id' - ) - ); -} - -/** - * User class - * - */ -class XmlUser extends TestModel { - -/** - * name property - * - * @var string - */ - public $name = 'User'; - -/** - * hasMany property - * - * @var array - */ - public $hasMany = array( - 'Article' => array( - 'className' => 'XmlArticle' - ) - ); -} /** * XmlTest class diff --git a/Cake/Test/TestCase/View/Helper/FormHelperTest.php b/Cake/Test/TestCase/View/Helper/FormHelperTest.php index ecaa4373ed3..3311a23af90 100644 --- a/Cake/Test/TestCase/View/Helper/FormHelperTest.php +++ b/Cake/Test/TestCase/View/Helper/FormHelperTest.php @@ -20,10 +20,9 @@ use Cake\Core\App; use Cake\Core\Configure; use Cake\Core\Plugin; -use Cake\Model\Model; use Cake\Network\Request; +use Cake\ORM\Table; use Cake\Routing\Router; -use Cake\TestSuite\Fixture\TestModel; use Cake\TestSuite\TestCase; use Cake\Utility\ClassRegistry; use Cake\Utility\Security; @@ -49,14 +48,7 @@ class ContactTestController extends Controller { * Contact class * */ -class Contact extends TestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class ContactsTable extends Table { /** * Default schema @@ -149,14 +141,7 @@ public function setSchema($schema) { * ContactTagsContact class * */ -class ContactTagsContact extends TestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class ContactTagsContactsTable extends Table { /** * Default schema @@ -185,7 +170,7 @@ public function setSchema($schema) { * ContactNonStandardPk class * */ -class ContactNonStandardPk extends Contact { +class ContactNonStandardPk extends ContactsTable { /** * primaryKey property @@ -212,14 +197,7 @@ public function schema($field = false) { * ContactTag class * */ -class ContactTag extends Model { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class ContactTagsTable extends Table { /** * schema definition @@ -238,14 +216,7 @@ class ContactTag extends Model { * UserForm class * */ -class UserForm extends TestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class UserFormsTable extends Table { /** * hasMany property @@ -277,14 +248,7 @@ class UserForm extends TestModel { * OpenidUrl class * */ -class OpenidUrl extends TestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class OpenidUrlsTable extends Table { /** * belongsTo property @@ -331,14 +295,7 @@ public function beforeValidate($options = array()) { * ValidateUser class * */ -class ValidateUser extends TestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class ValidateUsersTable extends Table { /** * hasOne property @@ -380,7 +337,7 @@ public function beforeValidate($options = array()) { * ValidateProfile class * */ -class ValidateProfile extends TestModel { +class ValidateProfilesTable extends Table { /** * useTable property @@ -438,14 +395,7 @@ public function beforeValidate($options = array()) { * ValidateItem class * */ -class ValidateItem extends TestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class ValidateItemsTable extends Table { /** * schema property @@ -486,14 +436,7 @@ public function beforeValidate($options = array()) { * TestMail class * */ -class TestMail extends TestModel { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class TestMailsTable extends Table { } diff --git a/Cake/Test/TestCase/View/HelperTest.php b/Cake/Test/TestCase/View/HelperTest.php index d2e6bd23c88..1b1b47f0445 100644 --- a/Cake/Test/TestCase/View/HelperTest.php +++ b/Cake/Test/TestCase/View/HelperTest.php @@ -19,11 +19,10 @@ use Cake\Core\App; use Cake\Core\Configure; use Cake\Core\Plugin; -use Cake\Model\Model; use Cake\Network\Request; +use Cake\ORM\Table; use Cake\Routing\Router; use Cake\TestSuite\TestCase; -use Cake\Utility\ClassRegistry; use Cake\View\Helper; use Cake\View\View; @@ -31,14 +30,7 @@ * HelperTestPost class * */ -class HelperTestPost extends Model { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class HelperTestPostsTable extends Table { /** * schema method @@ -70,14 +62,7 @@ public function schema($field = false) { * HelperTestComment class * */ -class HelperTestComment extends Model { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class HelperTestCommentsTable extends Table { /** * schema method @@ -103,14 +88,7 @@ public function schema($field = false) { * HelperTestTag class * */ -class HelperTestTag extends Model { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class HelperTestTagsTable extends Table { /** * schema method @@ -133,14 +111,7 @@ public function schema($field = false) { * HelperTestPostsTag class * */ -class HelperTestPostsTag extends Model { - -/** - * useTable property - * - * @var boolean - */ - public $useTable = false; +class HelperTestPostsTagsTable extends Table { /** * schema method @@ -205,16 +176,11 @@ class HelperTest extends TestCase { public function setUp() { parent::setUp(); - ClassRegistry::flush(); Router::reload(); $null = null; $this->View = new View($null); $this->Helper = new Helper($this->View); $this->Helper->request = new Request(); - - ClassRegistry::addObject('HelperTestPost', new HelperTestPost()); - ClassRegistry::addObject('HelperTestComment', new HelperTestComment()); - ClassRegistry::addObject('HelperTestTag', new HelperTestTag()); } /** diff --git a/Cake/Test/TestCase/View/ScaffoldViewTest.php b/Cake/Test/TestCase/View/ScaffoldViewTest.php deleted file mode 100644 index a555bef775d..00000000000 --- a/Cake/Test/TestCase/View/ScaffoldViewTest.php +++ /dev/null @@ -1,309 +0,0 @@ - - * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The MIT License - * Redistributions of files must retain the above copyright notice - * - * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests - * @since CakePHP(tm) v 2.0 - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) - */ -namespace Cake\Test\TestCase\View; - -use Cake\Controller\Controller; -use Cake\Controller\Scaffold; -use Cake\Core\App; -use Cake\Core\Configure; -use Cake\Core\Plugin; -use Cake\Network\Request; -use Cake\Routing\Router; -use Cake\TestSuite\TestCase; -use Cake\View\ScaffoldView; -use TestApp\Controller\ScaffoldArticlesController; - -require_once dirname(__DIR__) . DS . 'Model' . DS . 'models.php'; - -if (!class_exists('Cake\Model\ScaffoldMock')) { - class_alias('Cake\Test\TestCase\Model\ScaffoldMock', 'Cake\Model\ScaffoldMock'); -} - -/** - * TestScaffoldView class - * - */ -class TestScaffoldView extends ScaffoldView { - -/** - * testGetFilename method - * - * @param string $action - * @return void - */ - public function testGetFilename($action) { - return $this->_getViewFileName($action); - } - -} - - -/** - * ScaffoldViewTest class - * - */ -class ScaffoldViewTest extends TestCase { - -/** - * fixtures property - * - * @var array - */ - public $fixtures = [ - 'core.article', - 'core.user', - 'core.comment', - 'core.articles_tag', - 'core.tag' - ]; - -/** - * setUp method - * - * @return void - */ - public function setUp() { - parent::setUp(); - $this->markTestIncomplete('Need to revisit once models work again.'); - Configure::write('App.namespace', 'TestApp'); - - Router::connect('/:controller/:action/*'); - Router::connect('/:controller', ['action' => 'index']); - - $this->request = new Request(); - $this->Controller = new ScaffoldArticlesController($this->request); - $this->Controller->response = $this->getMock('Cake\Network\Response', array('_sendHeader')); - - Plugin::load('TestPlugin'); - } - -/** - * tearDown method - * - * @return void - */ - public function tearDown() { - unset($this->Controller, $this->request); - parent::tearDown(); - } - -/** - * testGetViewFilename method - * - * @return void - */ - public function testGetViewFilename() { - Configure::write('Routing.prefixes', array('admin')); - - $this->Controller->request->params['action'] = 'index'; - $ScaffoldView = new TestScaffoldView($this->Controller); - $result = $ScaffoldView->testGetFilename('index'); - $expected = CAKE . 'View' . DS . 'Scaffold' . DS . 'index.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('edit'); - $expected = CAKE . 'View' . DS . 'Scaffold' . DS . 'form.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('add'); - $expected = CAKE . 'View' . DS . 'Scaffold' . DS . 'form.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('view'); - $expected = CAKE . 'View' . DS . 'Scaffold' . DS . 'view.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('admin_index'); - $expected = CAKE . 'View' . DS . 'Scaffold' . DS . 'index.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('admin_view'); - $expected = CAKE . 'View' . DS . 'Scaffold' . DS . 'view.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('admin_edit'); - $expected = CAKE . 'View' . DS . 'Scaffold' . DS . 'form.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('admin_add'); - $expected = CAKE . 'View' . DS . 'Scaffold' . DS . 'form.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('error'); - $expected = CAKE . 'View' . DS . 'Error' . DS . 'scaffold_error.ctp'; - $this->assertEquals($expected, $result); - - $Controller = new ScaffoldArticlesController($this->request); - $Controller->scaffold = 'admin'; - $Controller->viewPath = 'Posts'; - $Controller->request['action'] = 'admin_edit'; - - $ScaffoldView = new TestScaffoldView($Controller); - $result = $ScaffoldView->testGetFilename('admin_edit'); - $expected = CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('edit'); - $expected = CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp'; - $this->assertEquals($expected, $result); - - $Controller = new ScaffoldArticlesController($this->request); - $Controller->scaffold = 'admin'; - $Controller->viewPath = 'Tests'; - $Controller->request->addParams(array( - 'plugin' => 'test_plugin', - 'action' => 'admin_add', - 'admin' => true - )); - $Controller->plugin = 'TestPlugin'; - - $ScaffoldView = new TestScaffoldView($Controller); - $pluginPath = CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin' . DS . 'TestPlugin' . DS; - - $result = $ScaffoldView->testGetFilename('admin_add'); - $expected = $pluginPath . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp'; - $this->assertEquals($expected, $result); - - $result = $ScaffoldView->testGetFilename('add'); - $expected = $pluginPath . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp'; - $this->assertEquals($expected, $result); - } - -/** - * test getting the view file name for themed scaffolds. - * - * @return void - */ - public function testGetViewFileNameWithTheme() { - $this->Controller->request['action'] = 'index'; - $this->Controller->viewPath = 'Posts'; - $this->Controller->theme = 'TestTheme'; - $ScaffoldView = new TestScaffoldView($this->Controller); - $themePath = CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS; - - $result = $ScaffoldView->testGetFilename('index'); - $expected = $themePath . 'Posts' . DS . 'scaffold.index.ctp'; - $this->assertEquals($expected, $result); - } - -/** - * test default index scaffold generation - * - * @return void - */ - public function testIndexScaffold() { - $params = [ - 'plugin' => null, - 'pass' => [], - 'controller' => 'articles', - 'action' => 'index', - ]; - $this->Controller->request->addParams($params); - $this->Controller->request->webroot = '/'; - $this->Controller->request->base = ''; - $this->Controller->request->here = '/articles/index'; - - Router::pushRequest($this->Controller->request); - - $this->Controller->constructClasses(); - ob_start(); - new Scaffold($this->Controller, $this->Controller->request); - $this->Controller->response->send(); - $result = ob_get_clean(); - - $this->assertRegExp('#

Articles

#', $result); - $this->assertRegExp('##', $result); - - $this->assertRegExp('#1#', $result); //belongsTo links - $this->assertRegExp('#
  • New Article
  • #', $result); - $this->assertRegExp('#
  • List Users
  • #', $result); - $this->assertRegExp('#
  • New Comment
  • #', $result); - } - -/** - * test default view scaffold generation - * - * @return void - */ - public function testViewScaffold() { - $this->Controller->request->base = ''; - $this->Controller->request->webroot = '/'; - $params = [ - 'plugin' => null, - 'pass' => [1], - 'controller' => 'articles', - 'action' => 'view', - ]; - $this->Controller->request->addParams($params); - - //set router. - Router::pushRequest($this->Controller->request); - $this->Controller->constructClasses(); - - ob_start(); - new Scaffold($this->Controller, $this->Controller->request); - $this->Controller->response->send(); - $result = ob_get_clean(); - - $this->assertRegExp('#

    View Article

    #', $result); - $this->assertRegExp('#
    #', $result); - - $this->assertRegExp('#1#', $result); //belongsTo links - $this->assertRegExp('#
  • Edit Article\s*
  • #', $result); - $this->assertRegExp('#\s*

    Related Comments

    \s*
    #', $result); - $this->assertRegExp('#
  • New Comment
  • #', $result); - $this->assertNotRegExp('##', $result); - } - -/** - * test default edit scaffold generation - * - * @return void - */ - public function testEditScaffold() { - $this->Controller->request->base = ''; - $this->Controller->request->webroot = '/'; - $this->Controller->request->here = '/articles/edit/1'; - - $params = [ - 'plugin' => null, - 'pass' => [1], - 'controller' => 'articles', - 'action' => 'edit', - ]; - $this->Controller->request->addParams($params); - - //set router. - Router::pushRequest($this->Controller->request); - $this->Controller->constructClasses(); - - ob_start(); - new Scaffold($this->Controller, $this->Controller->request); - $this->Controller->response->send(); - $result = ob_get_clean(); - - $this->assertContains('assertContains('Edit Article', $result); - - $this->assertContains('input type="hidden" name="Article[id]" value="1" id="ArticleId"', $result); - $this->assertContains('select name="Article[user_id]" id="ArticleUserId"', $result); - $this->assertContains('input name="Article[title]" maxlength="255" type="text" value="First Article" id="ArticleTitle"', $result); - $this->assertContains('input name="Article[published]" maxlength="1" type="text" value="Y" id="ArticlePublished"', $result); - $this->assertContains('textarea name="Article[body]" cols="30" rows="6" id="ArticleBody"', $result); - $this->assertRegExp('/_config[$type]); - } elseif (empty($param) && is_string($type)) { - return isset($_this->_config[$type]) ? $_this->_config[$type] : null; - } - if (isset($_this->_config[$type]['testing'])) { - $param['testing'] = true; - } - $_this->_config[$type] = $param; - } - -/** - * Checks to see if $alias is a duplicate $class Object - * - * @param string $alias - * @param string $class - * @return boolean - */ - protected function &_duplicate($alias, $class) { - $duplicate = false; - if ($this->isKeySet($alias)) { - $model = $this->getObject($alias); - if (is_object($model) && ($model instanceof $class || $model->alias === $class)) { - $duplicate = $model; - } - unset($model); - } - return $duplicate; - } - -/** - * Add a key name pair to the registry to map name to class in the registry. - * - * @param string $key Key to include in map - * @param string $name Key that is being mapped - * @return void - */ - public static function map($key, $name) { - $_this = ClassRegistry::getInstance(); - $key = Inflector::underscore($key); - $name = Inflector::underscore($name); - if (!isset($_this->_map[$key])) { - $_this->_map[$key] = $name; - } - } - -/** - * Get all keys from the map in the registry. - * - * @return array Keys of registry's map - */ - public static function mapKeys() { - return array_keys(ClassRegistry::getInstance()->_map); - } - -/** - * Return the name of a class in the registry. - * - * @param string $key Key to find in map - * @return string Mapped value - */ - protected function _getMap($key) { - if (isset($this->_map[$key])) { - return $this->_map[$key]; - } - } - -/** - * Flushes all objects from the ClassRegistry. - * - * @return void - */ - public static function flush() { - $_this = ClassRegistry::getInstance(); - $_this->_objects = array(); - $_this->_map = array(); - } - -} diff --git a/Cake/View/Helper.php b/Cake/View/Helper.php index caf77d44174..e56b89330dd 100644 --- a/Cake/View/Helper.php +++ b/Cake/View/Helper.php @@ -20,7 +20,6 @@ use Cake\Core\Plugin; use Cake\Event\EventListener; use Cake\Routing\Router; -use Cake\Utility\ClassRegistry; use Cake\Utility\Hash; use Cake\Utility\Inflector; @@ -690,11 +689,6 @@ public function value($options = array(), $field = null, $key = 'value') { $habtmKey = $this->field(); if (empty($result) && isset($data[$habtmKey][$habtmKey]) && is_array($data[$habtmKey])) { $result = $data[$habtmKey][$habtmKey]; - } elseif (empty($result) && isset($data[$habtmKey]) && is_array($data[$habtmKey])) { - if (ClassRegistry::isKeySet($habtmKey)) { - $model = ClassRegistry::getObject($habtmKey); - $result = $this->_selectedArray($data[$habtmKey], $model->primaryKey); - } } if (is_array($options)) { diff --git a/Cake/View/Helper/FormHelper.php b/Cake/View/Helper/FormHelper.php index fe7fa9133e1..8bf47a8f9a3 100644 --- a/Cake/View/Helper/FormHelper.php +++ b/Cake/View/Helper/FormHelper.php @@ -16,7 +16,7 @@ use Cake\Core\Configure; use Cake\Error; -use Cake\Utility\ClassRegistry; +use Cake\ORM\TableRegistry; use Cake\Utility\Hash; use Cake\Utility\Inflector; use Cake\Utility\Security; @@ -142,30 +142,14 @@ protected function _getModel($model) { return $this->_models[$model]; } - if (ClassRegistry::isKeySet($model)) { - $object = ClassRegistry::getObject($model); - } elseif (isset($this->request->params['models'][$model])) { - $plugin = $this->request->params['models'][$model]['plugin']; - $plugin .= ($plugin) ? '.' : null; - $object = ClassRegistry::init(array( - 'class' => $plugin . $this->request->params['models'][$model]['className'], - 'alias' => $model - )); - } elseif (ClassRegistry::isKeySet($this->defaultModel)) { - $defaultObject = ClassRegistry::getObject($this->defaultModel); - if ($defaultObject && in_array($model, array_keys($defaultObject->getAssociated()), true) && isset($defaultObject->{$model})) { - $object = $defaultObject->{$model}; - } - } else { - $object = ClassRegistry::init($model, true); - } + $object = TableRegistry::get($model); $this->_models[$model] = $object; if (!$object) { return null; } - $this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey, 'validates' => null); + $this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey(), 'validates' => null); return $object; } diff --git a/Cake/View/Scaffold/form.ctp b/Cake/View/Scaffold/form.ctp deleted file mode 100644 index bf9bdd49ce7..00000000000 --- a/Cake/View/Scaffold/form.ctp +++ /dev/null @@ -1,58 +0,0 @@ - -
    -Form->create(); - echo $this->Form->inputs($scaffoldFields, array('created', 'modified', 'updated')); - echo $this->Form->end(__d('cake', 'Submit')); -?> -
    -
    -

    -
      -request->action !== 'add'): ?> -
    • Form->postLink( - __d('cake', 'Delete'), - array('action' => 'delete', $this->Form->value($modelClass . '.' . $primaryKey)), - array(), - __d('cake', 'Are you sure you want to delete # %s?', $this->Form->value($modelClass . '.' . $primaryKey))); - ?>
    • - -
    • Html->link(__d('cake', 'List') . ' ' . $pluralHumanName, array('action' => 'index')); ?>
    • - $_data) { - foreach ($_data as $_alias => $_details) { - list(, $_details['controller']) = namespaceSplit($_details['controller']); - if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) { - echo "\t\t
    • " . $this->Html->link( - __d('cake', 'List %s', Inflector::humanize($_details['controller'])), - array('plugin' => $_details['plugin'], 'controller' => $_details['controller'], 'action' => 'index') - ) . "
    • \n"; - echo "\t\t
    • " . $this->Html->link( - __d('cake', 'New %s', Inflector::humanize(Inflector::underscore($_alias))), - array('plugin' => $_details['plugin'], 'controller' => $_details['controller'], 'action' => 'add') - ) . "
    • \n"; - $done[] = $_details['controller']; - } - } - } -?> -
    -
    diff --git a/Cake/View/Scaffold/index.ctp b/Cake/View/Scaffold/index.ctp deleted file mode 100644 index e7163097a7c..00000000000 --- a/Cake/View/Scaffold/index.ctp +++ /dev/null @@ -1,106 +0,0 @@ - -
    -

    -
    JoinThing
    - - - - - - -'; - foreach ($scaffoldFields as $_field) { - $isKey = false; - if (!empty($associations['belongsTo'])) { - foreach ($associations['belongsTo'] as $_alias => $_details) { - list(, $_details['controller']) = namespaceSplit($_details['controller']); - if ($_field === $_details['foreignKey']) { - $isKey = true; - echo ''; - break; - } - } - } - if ($isKey !== true) { - echo ''; - } - } - - echo ''; - echo ''; - -endforeach; - -?> -
    Paginator->sort($_field); ?>
    ' . $this->Html->link(${$singularVar}[$_alias][$_details['displayField']], array('controller' => $_details['controller'], 'action' => 'view', ${$singularVar}[$_alias][$_details['primaryKey']])) . '' . h(${$singularVar}[$modelClass][$_field]) . ''; - echo $this->Html->link(__d('cake', 'View'), array('action' => 'view', ${$singularVar}[$modelClass][$primaryKey])); - echo ' ' . $this->Html->link(__d('cake', 'Edit'), array('action' => 'edit', ${$singularVar}[$modelClass][$primaryKey])); - echo ' ' . $this->Form->postLink( - __d('cake', 'Delete'), - array('action' => 'delete', ${$singularVar}[$modelClass][$primaryKey]), - array(), - __d('cake', 'Are you sure you want to delete # %s?', ${$singularVar}[$modelClass][$primaryKey]) - ); - echo '
    -

    Paginator->counter(array( - 'format' => __d('cake', 'Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}') - )); - ?>

    -
    - Paginator->prev('< ' . __d('cake', 'previous'), array(), null, array('class' => 'prev disabled')); - echo $this->Paginator->numbers(array('separator' => '')); - echo $this->Paginator->next(__d('cake', 'next') .' >', array(), null, array('class' => 'next disabled')); - ?> -
    - -
    -

    -
      -
    • Html->link(__d('cake', 'New %s', $singularHumanName), array('action' => 'add')); ?>
    • - $_data) { - foreach ($_data as $_alias => $_details) { - list(, $_details['controller']) = namespaceSplit($_details['controller']); - if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) { - echo '
    • '; - echo $this->Html->link( - __d('cake', 'List %s', Inflector::humanize($_details['controller'])), - array('plugin' => $_details['plugin'], 'controller' => $_details['controller'], 'action' => 'index') - ); - echo '
    • '; - - echo '
    • '; - echo $this->Html->link( - __d('cake', 'New %s', Inflector::humanize(Inflector::underscore($_alias))), - array('plugin' => $_details['plugin'], 'controller' => $_details['controller'], 'action' => 'add') - ); - echo '
    • '; - $done[] = $_details['controller']; - } - } - } -?> -
    -
    diff --git a/Cake/View/Scaffold/view.ctp b/Cake/View/Scaffold/view.ctp deleted file mode 100644 index 8ade1835002..00000000000 --- a/Cake/View/Scaffold/view.ctp +++ /dev/null @@ -1,199 +0,0 @@ - -
    -

    -
    - $_details) { - list(, $_details['controller']) = namespaceSplit($_details['controller']); - if ($_field === $_details['foreignKey']) { - $isKey = true; - echo "\t\t
    " . Inflector::humanize($_alias) . "
    \n"; - echo "\t\t
    \n\t\t\t"; - echo $this->Html->link( - ${$singularVar}[$_alias][$_details['displayField']], - array('plugin' => $_details['plugin'], 'controller' => $_details['controller'], 'action' => 'view', ${$singularVar}[$_alias][$_details['primaryKey']]) - ); - echo "\n\t\t 
    \n"; - break; - } - } - } - if ($isKey !== true) { - echo "\t\t
    " . Inflector::humanize($_field) . "
    \n"; - echo "\t\t
    " . h(${$singularVar}[$modelClass][$_field]) . " 
    \n"; - } -} -?> -
    -
    -
    -

    -
      -"; - echo $this->Html->link(__d('cake', 'Edit %s', $singularHumanName), array('action' => 'edit', ${$singularVar}[$modelClass][$primaryKey])); - echo " \n"; - - echo "\t\t
    • "; - echo $this->Form->postLink(__d('cake', 'Delete %s', $singularHumanName), array('action' => 'delete', ${$singularVar}[$modelClass][$primaryKey]), array(), __d('cake', 'Are you sure you want to delete # %s?', ${$singularVar}[$modelClass][$primaryKey])); - echo "
    • \n"; - - echo "\t\t
    • "; - echo $this->Html->link(__d('cake', 'List %s', $pluralHumanName), array('action' => 'index')); - echo "
    • \n"; - - echo "\t\t
    • "; - echo $this->Html->link(__d('cake', 'New %s', $singularHumanName), array('action' => 'add')); - echo "
    • \n"; - - $done = array(); - foreach ($associations as $_type => $_data) { - foreach ($_data as $_alias => $_details) { - list(, $_details['controller']) = namespaceSplit($_details['controller']); - if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) { - echo "\t\t
    • "; - echo $this->Html->link( - __d('cake', 'List %s', Inflector::humanize($_details['controller'])), - array('plugin' => $_details['plugin'], 'controller' => $_details['controller'], 'action' => 'index') - ); - echo "
    • \n"; - echo "\t\t
    • "; - echo $this->Html->link( - __d('cake', 'New %s', Inflector::humanize(Inflector::underscore($_alias))), - array('plugin' => $_details['plugin'], 'controller' => $_details['controller'], 'action' => 'add') - ); - echo "
    • \n"; - $done[] = $_details['controller']; - } - } - } -?> -
    -
    - $_details): ?> - - $_details): -list(, $_details['controller']) = namespaceSplit($_details['controller']); -$otherSingularVar = Inflector::variable($_alias); -?> - - diff --git a/Cake/View/ScaffoldView.php b/Cake/View/ScaffoldView.php deleted file mode 100644 index f420be005b3..00000000000 --- a/Cake/View/ScaffoldView.php +++ /dev/null @@ -1,93 +0,0 @@ -action; - } - $name = Inflector::underscore($name); - $prefixes = Configure::read('Routing.prefixes'); - - if (!empty($prefixes)) { - foreach ($prefixes as $prefix) { - if (strpos($name, $prefix . '_') !== false) { - $name = substr($name, strlen($prefix) + 1); - break; - } - } - } - - if ($name === 'add' || $name === 'edit') { - $name = 'form'; - } else { - $name = str_replace('/', DS, $name); - } - - $scaffoldAction = 'scaffold.' . $name; - - if ($this->subDir !== null) { - $subDir = strtolower($this->subDir) . DS; - } else { - $subDir = null; - } - - $names[] = $this->viewPath . DS . $subDir . $scaffoldAction; - $names[] = 'Scaffold' . DS . $subDir . $name; - - $paths = $this->_paths($this->plugin); - $exts = array($this->ext); - if ($this->ext !== '.ctp') { - $exts[] = '.ctp'; - } - foreach ($exts as $ext) { - foreach ($paths as $path) { - foreach ($names as $name) { - if (file_exists($path . $name . $ext)) { - return $path . $name . $ext; - } - } - } - } - - if ($name === 'Scaffold' . DS . $subDir . 'error') { - return CAKE . 'View' . DS . 'Error' . DS . 'scaffold_error.ctp'; - } - - throw new Error\MissingViewException($paths[0] . $name . $this->ext); - } - -} diff --git a/lib/Cake/Test/Case/TestSuite/Fixture/CakeFixtureManagerTest.php b/lib/Cake/Test/Case/TestSuite/Fixture/CakeFixtureManagerTest.php deleted file mode 100644 index d33f2340629..00000000000 --- a/lib/Cake/Test/Case/TestSuite/Fixture/CakeFixtureManagerTest.php +++ /dev/null @@ -1,103 +0,0 @@ -fixtureManager = new CakeFixtureManager(); - } - -/** - * tearDown - * - * @return void - */ - public function tearDown() { - parent::tearDown(); - unset($this->fixtureManager); - } - -/** - * testLoadTruncatesTable - * - * @return void - */ - public function testLoadTruncatesTable() { - $MockFixture = $this->getMock('UuidFixture', array('truncate')); - $MockFixture - ->expects($this->once()) - ->method('truncate') - ->will($this->returnValue(true)); - - $fixtureManager = $this->fixtureManager; - $fixtureManagerReflection = new ReflectionClass($fixtureManager); - - $loadedProperty = $fixtureManagerReflection->getProperty('_loaded'); - $loadedProperty->setAccessible(true); - $loadedProperty->setValue($fixtureManager, array('core.uuid' => $MockFixture)); - - $TestCase = $this->getMock('CakeTestCase'); - $TestCase->fixtures = array('core.uuid'); - $TestCase->autoFixtures = true; - $TestCase->dropTables = false; - - $fixtureManager->load($TestCase); - } - -/** - * testLoadSingleTruncatesTable - * - * @return void - */ - public function testLoadSingleTruncatesTable() { - $MockFixture = $this->getMock('UuidFixture', array('truncate')); - $MockFixture - ->expects($this->once()) - ->method('truncate') - ->will($this->returnValue(true)); - - $fixtureManager = $this->fixtureManager; - $fixtureManagerReflection = new ReflectionClass($fixtureManager); - - $fixtureMapProperty = $fixtureManagerReflection->getProperty('_fixtureMap'); - $fixtureMapProperty->setAccessible(true); - $fixtureMapProperty->setValue($fixtureManager, array('UuidFixture' => $MockFixture)); - - $dboMethods = array_diff(get_class_methods('DboSource'), array('enabled')); - $dboMethods[] = 'connect'; - $db = $this->getMock('DboSource', $dboMethods); - $db->config['prefix'] = ''; - - $fixtureManager->loadSingle('Uuid', $db, false); - } -}