CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.10 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.10
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • None

Classes

  • AclBehavior
  • ContainableBehavior
  • TranslateBehavior
  • TreeBehavior
   1: <?php
   2: /**
   3:  * Tree behavior class.
   4:  *
   5:  * Enables a model object to act as a node-based tree.
   6:  *
   7:  * CakePHP :  Rapid Development Framework (https://cakephp.org)
   8:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
   9:  *
  10:  * Licensed under The MIT License
  11:  * For full copyright and license information, please see the LICENSE.txt
  12:  * Redistributions of files must retain the above copyright notice.
  13:  *
  14:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  15:  * @link          https://cakephp.org CakePHP Project
  16:  * @package       Cake.Model.Behavior
  17:  * @since         CakePHP v 1.2.0.4487
  18:  * @license       https://opensource.org/licenses/mit-license.php MIT License
  19:  */
  20: 
  21: App::uses('ModelBehavior', 'Model');
  22: 
  23: /**
  24:  * Tree Behavior.
  25:  *
  26:  * Enables a model object to act as a node-based tree. Using Modified Preorder Tree Traversal
  27:  *
  28:  * @see http://en.wikipedia.org/wiki/Tree_traversal
  29:  * @package       Cake.Model.Behavior
  30:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html
  31:  */
  32: class TreeBehavior extends ModelBehavior {
  33: 
  34: /**
  35:  * Errors
  36:  *
  37:  * @var array
  38:  */
  39:     public $errors = array();
  40: 
  41: /**
  42:  * Defaults
  43:  *
  44:  * @var array
  45:  */
  46:     protected $_defaults = array(
  47:         'parent' => 'parent_id', 'left' => 'lft', 'right' => 'rght', 'level' => null,
  48:         'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1
  49:     );
  50: 
  51: /**
  52:  * Used to preserve state between delete callbacks.
  53:  *
  54:  * @var array
  55:  */
  56:     protected $_deletedRow = array();
  57: 
  58: /**
  59:  * Initiate Tree behavior
  60:  *
  61:  * @param Model $Model using this behavior of model
  62:  * @param array $config array of configuration settings.
  63:  * @return void
  64:  */
  65:     public function setup(Model $Model, $config = array()) {
  66:         if (isset($config[0])) {
  67:             $config['type'] = $config[0];
  68:             unset($config[0]);
  69:         }
  70:         $settings = $config + $this->_defaults;
  71: 
  72:         if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) {
  73:             $data = $Model->getAssociated($settings['scope']);
  74:             $Parent = $Model->{$settings['scope']};
  75:             $settings['scope'] = $Model->escapeField($data['foreignKey']) . ' = ' . $Parent->escapeField();
  76:             $settings['recursive'] = 0;
  77:         }
  78:         $this->settings[$Model->alias] = $settings;
  79:     }
  80: 
  81: /**
  82:  * After save method. Called after all saves
  83:  *
  84:  * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
  85:  * parameters to be saved.
  86:  *
  87:  * @param Model $Model Model using this behavior.
  88:  * @param bool $created indicates whether the node just saved was created or updated
  89:  * @param array $options Options passed from Model::save().
  90:  * @return bool true on success, false on failure
  91:  */
  92:     public function afterSave(Model $Model, $created, $options = array()) {
  93:         extract($this->settings[$Model->alias]);
  94:         if ($created) {
  95:             if ((isset($Model->data[$Model->alias][$parent])) && $Model->data[$Model->alias][$parent]) {
  96:                 return $this->_setParent($Model, $Model->data[$Model->alias][$parent], $created);
  97:             }
  98:         } elseif ($this->settings[$Model->alias]['__parentChange']) {
  99:             $this->settings[$Model->alias]['__parentChange'] = false;
 100:             if ($level) {
 101:                 $this->_setChildrenLevel($Model, $Model->id);
 102:             }
 103:             return $this->_setParent($Model, $Model->data[$Model->alias][$parent]);
 104:         }
 105:     }
 106: 
 107: /**
 108:  * Set level for descendents.
 109:  *
 110:  * @param Model $Model Model using this behavior.
 111:  * @param int|string $id Record ID
 112:  * @return void
 113:  */
 114:     protected function _setChildrenLevel(Model $Model, $id) {
 115:         $settings = $this->settings[$Model->alias];
 116:         $primaryKey = $Model->primaryKey;
 117:         $depths = array($id => (int)$Model->data[$Model->alias][$settings['level']]);
 118: 
 119:         $children = $this->children(
 120:             $Model,
 121:             $id,
 122:             false,
 123:             array($primaryKey, $settings['parent'], $settings['level']),
 124:             $settings['left'],
 125:             null,
 126:             1,
 127:             -1
 128:         );
 129: 
 130:         foreach ($children as $node) {
 131:             $parentIdValue = $node[$Model->alias][$settings['parent']];
 132:             $depth = (int)$depths[$parentIdValue] + 1;
 133:             $depths[$node[$Model->alias][$primaryKey]] = $depth;
 134: 
 135:             $Model->updateAll(
 136:                 array($Model->escapeField($settings['level']) => $depth),
 137:                 array($Model->escapeField($primaryKey) => $node[$Model->alias][$primaryKey])
 138:             );
 139:         }
 140:     }
 141: 
 142: /**
 143:  * Runs before a find() operation
 144:  *
 145:  * @param Model $Model Model using the behavior
 146:  * @param array $query Query parameters as set by cake
 147:  * @return array
 148:  */
 149:     public function beforeFind(Model $Model, $query) {
 150:         if ($Model->findQueryType === 'threaded' && !isset($query['parent'])) {
 151:             $query['parent'] = $this->settings[$Model->alias]['parent'];
 152:         }
 153:         return $query;
 154:     }
 155: 
 156: /**
 157:  * Stores the record about to be deleted.
 158:  *
 159:  * This is used to delete child nodes in the afterDelete.
 160:  *
 161:  * @param Model $Model Model using this behavior.
 162:  * @param bool $cascade If true records that depend on this record will also be deleted
 163:  * @return bool
 164:  */
 165:     public function beforeDelete(Model $Model, $cascade = true) {
 166:         extract($this->settings[$Model->alias]);
 167:         $data = $Model->find('first', array(
 168:             'conditions' => array($Model->escapeField($Model->primaryKey) => $Model->id),
 169:             'fields' => array($Model->escapeField($left), $Model->escapeField($right)),
 170:             'order' => false,
 171:             'recursive' => -1));
 172:         if ($data) {
 173:             $this->_deletedRow[$Model->alias] = current($data);
 174:         }
 175:         return true;
 176:     }
 177: 
 178: /**
 179:  * After delete method.
 180:  *
 181:  * Will delete the current node and all children using the deleteAll method and sync the table
 182:  *
 183:  * @param Model $Model Model using this behavior
 184:  * @return bool true to continue, false to abort the delete
 185:  */
 186:     public function afterDelete(Model $Model) {
 187:         extract($this->settings[$Model->alias]);
 188:         $data = $this->_deletedRow[$Model->alias];
 189:         $this->_deletedRow[$Model->alias] = null;
 190: 
 191:         if (!$data[$right] || !$data[$left]) {
 192:             return true;
 193:         }
 194:         $diff = $data[$right] - $data[$left] + 1;
 195: 
 196:         if ($diff > 2) {
 197:             if (is_string($scope)) {
 198:                 $scope = array($scope);
 199:             }
 200:             $scope[][$Model->escapeField($left) . " BETWEEN ? AND ?"] = array($data[$left] + 1, $data[$right] - 1);
 201:             $Model->deleteAll($scope);
 202:         }
 203:         $this->_sync($Model, $diff, '-', '> ' . $data[$right]);
 204:         return true;
 205:     }
 206: 
 207: /**
 208:  * Before save method. Called before all saves
 209:  *
 210:  * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
 211:  * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by
 212:  * this method bypassing the setParent logic.
 213:  *
 214:  * @param Model $Model Model using this behavior
 215:  * @param array $options Options passed from Model::save().
 216:  * @return bool true to continue, false to abort the save
 217:  * @see Model::save()
 218:  */
 219:     public function beforeSave(Model $Model, $options = array()) {
 220:         extract($this->settings[$Model->alias]);
 221: 
 222:         $this->_addToWhitelist($Model, array($left, $right));
 223:         if ($level) {
 224:             $this->_addToWhitelist($Model, $level);
 225:         }
 226:         $parentIsSet = array_key_exists($parent, $Model->data[$Model->alias]);
 227: 
 228:         if (!$Model->id || !$Model->exists($Model->getID())) {
 229:             if ($parentIsSet && $Model->data[$Model->alias][$parent]) {
 230:                 $parentNode = $this->_getNode($Model, $Model->data[$Model->alias][$parent]);
 231:                 if (!$parentNode) {
 232:                     return false;
 233:                 }
 234: 
 235:                 $Model->data[$Model->alias][$left] = 0;
 236:                 $Model->data[$Model->alias][$right] = 0;
 237:                 if ($level) {
 238:                     $Model->data[$Model->alias][$level] = (int)$parentNode[$Model->alias][$level] + 1;
 239:                 }
 240:                 return true;
 241:             }
 242: 
 243:             $edge = $this->_getMax($Model, $scope, $right, $recursive);
 244:             $Model->data[$Model->alias][$left] = $edge + 1;
 245:             $Model->data[$Model->alias][$right] = $edge + 2;
 246:             if ($level) {
 247:                 $Model->data[$Model->alias][$level] = 0;
 248:             }
 249:             return true;
 250:         }
 251: 
 252:         if ($parentIsSet) {
 253:             if ($Model->data[$Model->alias][$parent] != $Model->field($parent)) {
 254:                 $this->settings[$Model->alias]['__parentChange'] = true;
 255:             }
 256:             if (!$Model->data[$Model->alias][$parent]) {
 257:                 $Model->data[$Model->alias][$parent] = null;
 258:                 $this->_addToWhitelist($Model, $parent);
 259:                 if ($level) {
 260:                     $Model->data[$Model->alias][$level] = 0;
 261:                 }
 262:                 return true;
 263:             }
 264: 
 265:             $values = $this->_getNode($Model, $Model->id);
 266:             if (empty($values)) {
 267:                 return false;
 268:             }
 269:             list($node) = array_values($values);
 270: 
 271:             $parentNode = $this->_getNode($Model, $Model->data[$Model->alias][$parent]);
 272:             if (!$parentNode) {
 273:                 return false;
 274:             }
 275:             list($parentNode) = array_values($parentNode);
 276: 
 277:             if (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
 278:                 return false;
 279:             }
 280:             if ($node[$Model->primaryKey] === $parentNode[$Model->primaryKey]) {
 281:                 return false;
 282:             }
 283:             if ($level) {
 284:                 $Model->data[$Model->alias][$level] = (int)$parentNode[$level] + 1;
 285:             }
 286:         }
 287: 
 288:         return true;
 289:     }
 290: 
 291: /**
 292:  * Returns a single node from the tree from its primary key
 293:  *
 294:  * @param Model $Model Model using this behavior
 295:  * @param int|string $id The ID of the record to read
 296:  * @return array|bool The record read or false
 297:  */
 298:     protected function _getNode(Model $Model, $id) {
 299:         $settings = $this->settings[$Model->alias];
 300:         $fields = array($Model->primaryKey, $settings['parent'], $settings['left'], $settings['right']);
 301:         if ($settings['level']) {
 302:             $fields[] = $settings['level'];
 303:         }
 304: 
 305:         return $Model->find('first', array(
 306:             'conditions' => array($Model->escapeField() => $id),
 307:             'fields' => $fields,
 308:             'recursive' => $settings['recursive'],
 309:             'order' => false,
 310:         ));
 311:     }
 312: 
 313: /**
 314:  * Get the number of child nodes
 315:  *
 316:  * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field)
 317:  * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted.
 318:  *
 319:  * @param Model $Model Model using this behavior
 320:  * @param int|string|bool $id The ID of the record to read or false to read all top level nodes
 321:  * @param bool $direct whether to count direct, or all, children
 322:  * @return int number of child nodes
 323:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::childCount
 324:  */
 325:     public function childCount(Model $Model, $id = null, $direct = false) {
 326:         if (is_array($id)) {
 327:             extract(array_merge(array('id' => null), $id));
 328:         }
 329:         if ($id === null && $Model->id) {
 330:             $id = $Model->id;
 331:         } elseif (!$id) {
 332:             $id = null;
 333:         }
 334:         extract($this->settings[$Model->alias]);
 335: 
 336:         if ($direct) {
 337:             return $Model->find('count', array('conditions' => array($scope, $Model->escapeField($parent) => $id)));
 338:         }
 339: 
 340:         if ($id === null) {
 341:             return $Model->find('count', array('conditions' => $scope));
 342:         } elseif ($Model->id === $id && isset($Model->data[$Model->alias][$left]) && isset($Model->data[$Model->alias][$right])) {
 343:             $data = $Model->data[$Model->alias];
 344:         } else {
 345:             $data = $this->_getNode($Model, $id);
 346:             if (!$data) {
 347:                 return 0;
 348:             }
 349:             $data = $data[$Model->alias];
 350:         }
 351:         return ($data[$right] - $data[$left] - 1) / 2;
 352:     }
 353: 
 354: /**
 355:  * Get the child nodes of the current model
 356:  *
 357:  * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field)
 358:  * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
 359:  *
 360:  * @param Model $Model Model using this behavior
 361:  * @param int|string $id The ID of the record to read
 362:  * @param bool $direct whether to return only the direct, or all, children
 363:  * @param string|array $fields Either a single string of a field name, or an array of field names
 364:  * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order
 365:  * @param int $limit SQL LIMIT clause, for calculating items per page.
 366:  * @param int $page Page number, for accessing paged data
 367:  * @param int $recursive The number of levels deep to fetch associated records
 368:  * @return array Array of child nodes
 369:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::children
 370:  */
 371:     public function children(Model $Model, $id = null, $direct = false, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
 372:         $options = array();
 373:         if (is_array($id)) {
 374:             $options = $this->_getOptions($id);
 375:             extract(array_merge(array('id' => null), $id));
 376:         }
 377:         $overrideRecursive = $recursive;
 378: 
 379:         if ($id === null && $Model->id) {
 380:             $id = $Model->id;
 381:         } elseif (!$id) {
 382:             $id = null;
 383:         }
 384: 
 385:         extract($this->settings[$Model->alias]);
 386: 
 387:         if ($overrideRecursive !== null) {
 388:             $recursive = $overrideRecursive;
 389:         }
 390:         if (!$order) {
 391:             $order = $Model->escapeField($left) . " asc";
 392:         }
 393:         if ($direct) {
 394:             $conditions = array($scope, $Model->escapeField($parent) => $id);
 395:             return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
 396:         }
 397: 
 398:         if (!$id) {
 399:             $conditions = $scope;
 400:         } else {
 401:             $result = array_values((array)$Model->find('first', array(
 402:                 'conditions' => array($scope, $Model->escapeField() => $id),
 403:                 'fields' => array($left, $right),
 404:                 'recursive' => $recursive,
 405:                 'order' => false,
 406:             )));
 407: 
 408:             if (empty($result) || !isset($result[0])) {
 409:                 return array();
 410:             }
 411:             $conditions = array($scope,
 412:                 $Model->escapeField($right) . ' <' => $result[0][$right],
 413:                 $Model->escapeField($left) . ' >' => $result[0][$left]
 414:             );
 415:         }
 416:         $options = array_merge(compact(
 417:             'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
 418:         ), $options);
 419:         return $Model->find('all', $options);
 420:     }
 421: 
 422: /**
 423:  * A convenience method for returning a hierarchical array used for HTML select boxes
 424:  *
 425:  * @param Model $Model Model using this behavior
 426:  * @param string|array $conditions SQL conditions as a string or as an array('field' =>'value',...)
 427:  * @param string $keyPath A string path to the key, i.e. "{n}.Post.id"
 428:  * @param string $valuePath A string path to the value, i.e. "{n}.Post.title"
 429:  * @param string $spacer The character or characters which will be repeated
 430:  * @param int $recursive The number of levels deep to fetch associated records
 431:  * @return array An associative array of records, where the id is the key, and the display field is the value
 432:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::generateTreeList
 433:  */
 434:     public function generateTreeList(Model $Model, $conditions = null, $keyPath = null, $valuePath = null, $spacer = '_', $recursive = null) {
 435:         $overrideRecursive = $recursive;
 436:         extract($this->settings[$Model->alias]);
 437:         if ($overrideRecursive !== null) {
 438:             $recursive = $overrideRecursive;
 439:         }
 440: 
 441:         $fields = null;
 442:         if (!$keyPath && !$valuePath && $Model->hasField($Model->displayField)) {
 443:             $fields = array($Model->primaryKey, $Model->displayField, $left, $right);
 444:         }
 445: 
 446:         $conditions = (array)$conditions;
 447:         if ($scope) {
 448:             $conditions[] = $scope;
 449:         }
 450: 
 451:         $order = $Model->escapeField($left) . ' asc';
 452:         $results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive'));
 453: 
 454:         return $this->formatTreeList($Model, $results, compact('keyPath', 'valuePath', 'spacer'));
 455:     }
 456: 
 457: /**
 458:  * Formats result of a find() call to a hierarchical array used for HTML select boxes.
 459:  *
 460:  * Note that when using your own find() call this expects the order to be "left" field asc in order
 461:  * to generate the same result as using generateTreeList() directly.
 462:  *
 463:  * Options:
 464:  *
 465:  * - 'keyPath': A string path to the key, i.e. "{n}.Post.id"
 466:  * - 'valuePath': A string path to the value, i.e. "{n}.Post.title"
 467:  * - 'spacer': The character or characters which will be repeated
 468:  *
 469:  * @param Model $Model Model using this behavior
 470:  * @param array $results Result array of a find() call
 471:  * @param array $options Options
 472:  * @return array An associative array of records, where the id is the key, and the display field is the value
 473:  */
 474:     public function formatTreeList(Model $Model, array $results, array $options = array()) {
 475:         if (empty($results)) {
 476:             return array();
 477:         }
 478:         $defaults = array(
 479:             'keyPath' => null,
 480:             'valuePath' => null,
 481:             'spacer' => '_'
 482:         );
 483:         $options += $defaults;
 484: 
 485:         extract($this->settings[$Model->alias]);
 486: 
 487:         if (!$options['keyPath']) {
 488:             $options['keyPath'] = '{n}.' . $Model->alias . '.' . $Model->primaryKey;
 489:         }
 490: 
 491:         if (!$options['valuePath']) {
 492:             $options['valuePath'] = array('%s%s', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField);
 493: 
 494:         } elseif (is_string($options['valuePath'])) {
 495:             $options['valuePath'] = array('%s%s', '{n}.tree_prefix', $options['valuePath']);
 496: 
 497:         } else {
 498:             array_unshift($options['valuePath'], '%s' . $options['valuePath'][0], '{n}.tree_prefix');
 499:         }
 500: 
 501:         $stack = array();
 502: 
 503:         foreach ($results as $i => $result) {
 504:             $count = count($stack);
 505:             while ($stack && ($stack[$count - 1] < $result[$Model->alias][$right])) {
 506:                 array_pop($stack);
 507:                 $count--;
 508:             }
 509:             $results[$i]['tree_prefix'] = str_repeat($options['spacer'], $count);
 510:             $stack[] = $result[$Model->alias][$right];
 511:         }
 512: 
 513:         return Hash::combine($results, $options['keyPath'], $options['valuePath']);
 514:     }
 515: 
 516: /**
 517:  * Get the parent node
 518:  *
 519:  * reads the parent id and returns this node
 520:  *
 521:  * @param Model $Model Model using this behavior
 522:  * @param int|string $id The ID of the record to read
 523:  * @param string|array $fields Fields to get
 524:  * @param int $recursive The number of levels deep to fetch associated records
 525:  * @return array|bool Array of data for the parent node
 526:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getParentNode
 527:  */
 528:     public function getParentNode(Model $Model, $id = null, $fields = null, $recursive = null) {
 529:         $options = array();
 530:         if (is_array($id)) {
 531:             $options = $this->_getOptions($id);
 532:             extract(array_merge(array('id' => null), $id));
 533:         }
 534:         $overrideRecursive = $recursive;
 535:         if (empty($id)) {
 536:             $id = $Model->id;
 537:         }
 538:         extract($this->settings[$Model->alias]);
 539:         if ($overrideRecursive !== null) {
 540:             $recursive = $overrideRecursive;
 541:         }
 542:         $parentId = $Model->find('first', array(
 543:             'conditions' => array($Model->primaryKey => $id),
 544:             'fields' => array($parent),
 545:             'order' => false,
 546:             'recursive' => -1
 547:         ));
 548: 
 549:         if ($parentId) {
 550:             $parentId = $parentId[$Model->alias][$parent];
 551:             $options = array_merge(array(
 552:                 'conditions' => array($Model->escapeField() => $parentId),
 553:                 'fields' => $fields,
 554:                 'order' => false,
 555:                 'recursive' => $recursive
 556:             ), $options);
 557:             $parent = $Model->find('first', $options);
 558: 
 559:             return $parent;
 560:         }
 561:         return false;
 562:     }
 563: 
 564: /**
 565:  * Convenience method to create default find() options from $arg when it is an
 566:  * associative array.
 567:  *
 568:  * @param array $arg Array
 569:  * @return array Options array
 570:  */
 571:     protected function _getOptions($arg) {
 572:         return count(array_filter(array_keys($arg), 'is_string')) > 0 ?
 573:             $arg :
 574:             array();
 575:     }
 576: 
 577: /**
 578:  * Get the path to the given node
 579:  *
 580:  * @param Model $Model Model using this behavior
 581:  * @param int|string|null $id The ID of the record to read
 582:  * @param string|array|null $fields Either a single string of a field name, or an array of field names
 583:  * @param int|null $recursive The number of levels deep to fetch associated records
 584:  * @return array Array of nodes from top most parent to current node
 585:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getPath
 586:  */
 587:     public function getPath(Model $Model, $id = null, $fields = null, $recursive = null) {
 588:         $options = array();
 589:         if (is_array($id)) {
 590:             $options = $this->_getOptions($id);
 591:             extract(array_merge(array('id' => null), $id));
 592:         }
 593: 
 594:         if (!empty($options)) {
 595:             $fields = null;
 596:             if (!empty($options['fields'])) {
 597:                 $fields = $options['fields'];
 598:             }
 599:             if (!empty($options['recursive'])) {
 600:                 $recursive = $options['recursive'];
 601:             }
 602:         }
 603:         $overrideRecursive = $recursive;
 604:         if (empty($id)) {
 605:             $id = $Model->id;
 606:         }
 607:         extract($this->settings[$Model->alias]);
 608:         if ($overrideRecursive !== null) {
 609:             $recursive = $overrideRecursive;
 610:         }
 611:         $result = $Model->find('first', array(
 612:             'conditions' => array($Model->escapeField() => $id),
 613:             'fields' => array($left, $right),
 614:             'order' => false,
 615:             'recursive' => $recursive
 616:         ));
 617:         if ($result) {
 618:             $result = array_values($result);
 619:         } else {
 620:             return array();
 621:         }
 622:         $item = $result[0];
 623:         $options = array_merge(array(
 624:             'conditions' => array(
 625:                 $scope,
 626:                 $Model->escapeField($left) . ' <=' => $item[$left],
 627:                 $Model->escapeField($right) . ' >=' => $item[$right],
 628:             ),
 629:             'fields' => $fields,
 630:             'order' => array($Model->escapeField($left) => 'asc'),
 631:             'recursive' => $recursive
 632:         ), $options);
 633:         $results = $Model->find('all', $options);
 634:         return $results;
 635:     }
 636: 
 637: /**
 638:  * Reorder the node without changing the parent.
 639:  *
 640:  * If the node is the last child, or is a top level node with no subsequent node this method will return false
 641:  *
 642:  * @param Model $Model Model using this behavior
 643:  * @param int|string|null $id The ID of the record to move
 644:  * @param int|bool $number how many places to move the node or true to move to last position
 645:  * @return bool true on success, false on failure
 646:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveDown
 647:  */
 648:     public function moveDown(Model $Model, $id = null, $number = 1) {
 649:         if (is_array($id)) {
 650:             extract(array_merge(array('id' => null), $id));
 651:         }
 652:         if (!$number) {
 653:             return false;
 654:         }
 655:         if (empty($id)) {
 656:             $id = $Model->id;
 657:         }
 658:         extract($this->settings[$Model->alias]);
 659:         list($node) = array_values($this->_getNode($Model, $id));
 660:         if ($node[$parent]) {
 661:             list($parentNode) = array_values($this->_getNode($Model, $node[$parent]));
 662:             if (($node[$right] + 1) == $parentNode[$right]) {
 663:                 return false;
 664:             }
 665:         }
 666:         $nextNode = $Model->find('first', array(
 667:             'conditions' => array($scope, $Model->escapeField($left) => ($node[$right] + 1)),
 668:             'fields' => array($Model->primaryKey, $left, $right),
 669:             'order' => false,
 670:             'recursive' => $recursive)
 671:         );
 672:         if ($nextNode) {
 673:             list($nextNode) = array_values($nextNode);
 674:         } else {
 675:             return false;
 676:         }
 677:         $edge = $this->_getMax($Model, $scope, $right, $recursive);
 678:         $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
 679:         $this->_sync($Model, $nextNode[$left] - $node[$left], '-', 'BETWEEN ' . $nextNode[$left] . ' AND ' . $nextNode[$right]);
 680:         $this->_sync($Model, $edge - $node[$left] - ($nextNode[$right] - $nextNode[$left]), '-', '> ' . $edge);
 681: 
 682:         if (is_int($number)) {
 683:             $number--;
 684:         }
 685:         if ($number) {
 686:             $this->moveDown($Model, $id, $number);
 687:         }
 688:         return true;
 689:     }
 690: 
 691: /**
 692:  * Reorder the node without changing the parent.
 693:  *
 694:  * If the node is the first child, or is a top level node with no previous node this method will return false
 695:  *
 696:  * @param Model $Model Model using this behavior
 697:  * @param int|string|null $id The ID of the record to move
 698:  * @param int|bool $number how many places to move the node, or true to move to first position
 699:  * @return bool true on success, false on failure
 700:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveUp
 701:  */
 702:     public function moveUp(Model $Model, $id = null, $number = 1) {
 703:         if (is_array($id)) {
 704:             extract(array_merge(array('id' => null), $id));
 705:         }
 706:         if (!$number) {
 707:             return false;
 708:         }
 709:         if (empty($id)) {
 710:             $id = $Model->id;
 711:         }
 712:         extract($this->settings[$Model->alias]);
 713:         list($node) = array_values($this->_getNode($Model, $id));
 714:         if ($node[$parent]) {
 715:             list($parentNode) = array_values($this->_getNode($Model, $node[$parent]));
 716:             if (($node[$left] - 1) == $parentNode[$left]) {
 717:                 return false;
 718:             }
 719:         }
 720:         $previousNode = $Model->find('first', array(
 721:             'conditions' => array($scope, $Model->escapeField($right) => ($node[$left] - 1)),
 722:             'fields' => array($Model->primaryKey, $left, $right),
 723:             'order' => false,
 724:             'recursive' => $recursive
 725:         ));
 726: 
 727:         if ($previousNode) {
 728:             list($previousNode) = array_values($previousNode);
 729:         } else {
 730:             return false;
 731:         }
 732:         $edge = $this->_getMax($Model, $scope, $right, $recursive);
 733:         $this->_sync($Model, $edge - $previousNode[$left] + 1, '+', 'BETWEEN ' . $previousNode[$left] . ' AND ' . $previousNode[$right]);
 734:         $this->_sync($Model, $node[$left] - $previousNode[$left], '-', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]);
 735:         $this->_sync($Model, $edge - $previousNode[$left] - ($node[$right] - $node[$left]), '-', '> ' . $edge);
 736:         if (is_int($number)) {
 737:             $number--;
 738:         }
 739:         if ($number) {
 740:             $this->moveUp($Model, $id, $number);
 741:         }
 742:         return true;
 743:     }
 744: 
 745: /**
 746:  * Recover a corrupted tree
 747:  *
 748:  * The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data
 749:  * will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode
 750:  * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction
 751:  * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present.
 752:  *
 753:  * @param Model $Model Model using this behavior
 754:  * @param string $mode parent or tree
 755:  * @param string|int|null $missingParentAction 'return' to do nothing and return, 'delete' to
 756:  * delete, or the id of the parent to set as the parent_id
 757:  * @return bool true on success, false on failure
 758:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::recover
 759:  */
 760:     public function recover(Model $Model, $mode = 'parent', $missingParentAction = null) {
 761:         if (is_array($mode)) {
 762:             extract(array_merge(array('mode' => 'parent'), $mode));
 763:         }
 764:         extract($this->settings[$Model->alias]);
 765:         $Model->recursive = $recursive;
 766:         if ($mode === 'parent') {
 767:             $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
 768:                 'className' => $Model->name,
 769:                 'foreignKey' => $parent,
 770:                 'fields' => array($Model->primaryKey, $left, $right, $parent),
 771:             ))));
 772:             $missingParents = $Model->find('list', array(
 773:                 'recursive' => 0,
 774:                 'conditions' => array($scope, array(
 775:                     'NOT' => array($Model->escapeField($parent) => null), $Model->VerifyParent->escapeField() => null
 776:                 )),
 777:                 'order' => false,
 778:             ));
 779:             $Model->unbindModel(array('belongsTo' => array('VerifyParent')));
 780:             if ($missingParents) {
 781:                 if ($missingParentAction === 'return') {
 782:                     foreach ($missingParents as $id => $display) {
 783:                         $this->errors[] = 'cannot find the parent for ' . $Model->alias . ' with id ' . $id . '(' . $display . ')';
 784:                     }
 785:                     return false;
 786:                 } elseif ($missingParentAction === 'delete') {
 787:                     $Model->deleteAll(array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)), false);
 788:                 } else {
 789:                     $Model->updateAll(array($Model->escapeField($parent) => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)));
 790:                 }
 791:             }
 792: 
 793:             $this->_recoverByParentId($Model);
 794:         } else {
 795:             $db = ConnectionManager::getDataSource($Model->useDbConfig);
 796:             foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
 797:                 $path = $this->getPath($Model, $array[$Model->alias][$Model->primaryKey]);
 798:                 $parentId = null;
 799:                 if (count($path) > 1) {
 800:                     $parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey];
 801:                 }
 802:                 $Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey]));
 803:             }
 804:         }
 805:         return true;
 806:     }
 807: 
 808: /**
 809:  * _recoverByParentId
 810:  *
 811:  * Recursive helper function used by recover
 812:  *
 813:  * @param Model $Model Model instance.
 814:  * @param int $counter Counter
 815:  * @param int|string|null $parentId Parent record Id
 816:  * @return int counter
 817:  */
 818:     protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = null) {
 819:         $params = array(
 820:             'conditions' => array(
 821:                 $this->settings[$Model->alias]['parent'] => $parentId
 822:             ),
 823:             'fields' => array($Model->primaryKey),
 824:             'page' => 1,
 825:             'limit' => 100,
 826:             'order' => array($Model->primaryKey)
 827:         );
 828: 
 829:         $scope = $this->settings[$Model->alias]['scope'];
 830:         if ($scope && ($scope !== '1 = 1' && $scope !== true)) {
 831:             $params['conditions'][] = $scope;
 832:         }
 833: 
 834:         $children = $Model->find('all', $params);
 835:         $hasChildren = (bool)$children;
 836: 
 837:         if ($parentId !== null) {
 838:             if ($hasChildren) {
 839:                 $Model->updateAll(
 840:                     array($this->settings[$Model->alias]['left'] => $counter),
 841:                     array($Model->escapeField() => $parentId)
 842:                 );
 843:                 $counter++;
 844:             } else {
 845:                 $Model->updateAll(
 846:                     array(
 847:                         $this->settings[$Model->alias]['left'] => $counter,
 848:                         $this->settings[$Model->alias]['right'] => $counter + 1
 849:                     ),
 850:                     array($Model->escapeField() => $parentId)
 851:                 );
 852:                 $counter += 2;
 853:             }
 854:         }
 855: 
 856:         while ($children) {
 857:             foreach ($children as $row) {
 858:                 $counter = $this->_recoverByParentId($Model, $counter, $row[$Model->alias][$Model->primaryKey]);
 859:             }
 860: 
 861:             if (count($children) !== $params['limit']) {
 862:                 break;
 863:             }
 864:             $params['page']++;
 865:             $children = $Model->find('all', $params);
 866:         }
 867: 
 868:         if ($parentId !== null && $hasChildren) {
 869:             $Model->updateAll(
 870:                 array($this->settings[$Model->alias]['right'] => $counter),
 871:                 array($Model->escapeField() => $parentId)
 872:             );
 873:             $counter++;
 874:         }
 875: 
 876:         return $counter;
 877:     }
 878: 
 879: /**
 880:  * Reorder method.
 881:  *
 882:  * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters.
 883:  * This method does not change the parent of any node.
 884:  *
 885:  * Requires a valid tree, by default it verifies the tree before beginning.
 886:  *
 887:  * Options:
 888:  *
 889:  * - 'id' id of record to use as top node for reordering
 890:  * - 'field' Which field to use in reordering defaults to displayField
 891:  * - 'order' Direction to order either DESC or ASC (defaults to ASC)
 892:  * - 'verify' Whether or not to verify the tree before reorder. defaults to true.
 893:  *
 894:  * @param Model $Model Model using this behavior
 895:  * @param array $options array of options to use in reordering.
 896:  * @return bool true on success, false on failure
 897:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::reorder
 898:  */
 899:     public function reorder(Model $Model, $options = array()) {
 900:         $options += array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true);
 901:         extract($options);
 902:         if ($verify && !$this->verify($Model)) {
 903:             return false;
 904:         }
 905:         $verify = false;
 906:         extract($this->settings[$Model->alias]);
 907:         $fields = array($Model->primaryKey, $field, $left, $right);
 908:         $sort = $field . ' ' . $order;
 909:         $nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive);
 910: 
 911:         $cacheQueries = $Model->cacheQueries;
 912:         $Model->cacheQueries = false;
 913:         if ($nodes) {
 914:             foreach ($nodes as $node) {
 915:                 $id = $node[$Model->alias][$Model->primaryKey];
 916:                 $this->moveDown($Model, $id, true);
 917:                 if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) {
 918:                     $this->reorder($Model, compact('id', 'field', 'order', 'verify'));
 919:                 }
 920:             }
 921:         }
 922:         $Model->cacheQueries = $cacheQueries;
 923:         return true;
 924:     }
 925: 
 926: /**
 927:  * Remove the current node from the tree, and reparent all children up one level.
 928:  *
 929:  * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted
 930:  * after the children are reparented.
 931:  *
 932:  * @param Model $Model Model using this behavior
 933:  * @param int|string|null $id The ID of the record to remove
 934:  * @param bool $delete whether to delete the node after reparenting children (if any)
 935:  * @return bool true on success, false on failure
 936:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::removeFromTree
 937:  */
 938:     public function removeFromTree(Model $Model, $id = null, $delete = false) {
 939:         if (is_array($id)) {
 940:             extract(array_merge(array('id' => null), $id));
 941:         }
 942:         extract($this->settings[$Model->alias]);
 943: 
 944:         list($node) = array_values($this->_getNode($Model, $id));
 945: 
 946:         if ($node[$right] == $node[$left] + 1) {
 947:             if ($delete) {
 948:                 return $Model->delete($id);
 949:             }
 950:             $Model->id = $id;
 951:             return $Model->saveField($parent, null);
 952:         } elseif ($node[$parent]) {
 953:             list($parentNode) = array_values($this->_getNode($Model, $node[$parent]));
 954:         } else {
 955:             $parentNode[$right] = $node[$right] + 1;
 956:         }
 957: 
 958:         $db = ConnectionManager::getDataSource($Model->useDbConfig);
 959:         $Model->updateAll(
 960:             array($parent => $db->value($node[$parent], $parent)),
 961:             array($Model->escapeField($parent) => $node[$Model->primaryKey])
 962:         );
 963:         $this->_sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1));
 964:         $this->_sync($Model, 2, '-', '> ' . ($node[$right]));
 965:         $Model->id = $id;
 966: 
 967:         if ($delete) {
 968:             $Model->updateAll(
 969:                 array(
 970:                     $Model->escapeField($left) => 0,
 971:                     $Model->escapeField($right) => 0,
 972:                     $Model->escapeField($parent) => null
 973:                 ),
 974:                 array($Model->escapeField() => $id)
 975:             );
 976:             return $Model->delete($id);
 977:         }
 978:         $edge = $this->_getMax($Model, $scope, $right, $recursive);
 979:         if ($node[$right] == $edge) {
 980:             $edge = $edge - 2;
 981:         }
 982:         $Model->id = $id;
 983:         return $Model->save(
 984:             array($left => $edge + 1, $right => $edge + 2, $parent => null),
 985:             array('callbacks' => false, 'validate' => false)
 986:         );
 987:     }
 988: 
 989: /**
 990:  * Check if the current tree is valid.
 991:  *
 992:  * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
 993:  *
 994:  * @param Model $Model Model using this behavior
 995:  * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node],
 996:  *  [incorrect left/right index,node id], message)
 997:  * @link https://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::verify
 998:  */
 999:     public function verify(Model $Model) {
1000:         extract($this->settings[$Model->alias]);
1001:         if (!$Model->find('count', array('conditions' => $scope))) {
1002:             return true;
1003:         }
1004:         $min = $this->_getMin($Model, $scope, $left, $recursive);
1005:         $edge = $this->_getMax($Model, $scope, $right, $recursive);
1006:         $errors = array();
1007: 
1008:         for ($i = $min; $i <= $edge; $i++) {
1009:             $count = $Model->find('count', array('conditions' => array(
1010:                 $scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i)
1011:             )));
1012:             if ($count != 1) {
1013:                 if (!$count) {
1014:                     $errors[] = array('index', $i, 'missing');
1015:                 } else {
1016:                     $errors[] = array('index', $i, 'duplicate');
1017:                 }
1018:             }
1019:         }
1020:         $node = $Model->find('first', array(
1021:             'conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)),
1022:             'order' => false,
1023:             'recursive' => 0
1024:         ));
1025:         if ($node) {
1026:             $errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.');
1027:         }
1028: 
1029:         $Model->bindModel(array('belongsTo' => array('VerifyParent' => array(
1030:             'className' => $Model->name,
1031:             'foreignKey' => $parent,
1032:             'fields' => array($Model->primaryKey, $left, $right, $parent)
1033:         ))));
1034: 
1035:         $rows = $Model->find('all', array('conditions' => $scope, 'recursive' => 0));
1036:         foreach ($rows as $instance) {
1037:             if ($instance[$Model->alias][$left] === null || $instance[$Model->alias][$right] === null) {
1038:                 $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
1039:                     'has invalid left or right values');
1040:             } elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) {
1041:                 $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
1042:                     'left and right values identical');
1043:             } elseif ($instance[$Model->alias][$parent]) {
1044:                 if (!$instance['VerifyParent'][$Model->primaryKey]) {
1045:                     $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
1046:                         'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist');
1047:                 } elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) {
1048:                     $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
1049:                         'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
1050:                 } elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) {
1051:                     $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey],
1052:                         'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').');
1053:                 }
1054:             } elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) {
1055:                 $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent');
1056:             }
1057:         }
1058:         if ($errors) {
1059:             return $errors;
1060:         }
1061:         return true;
1062:     }
1063: 
1064: /**
1065:  * Returns the depth level of a node in the tree.
1066:  *
1067:  * @param Model $Model Model using this behavior
1068:  * @param int|string|null $id The primary key for record to get the level of.
1069:  * @return int|bool Integer of the level or false if the node does not exist.
1070:  */
1071:     public function getLevel(Model $Model, $id = null) {
1072:         if ($id === null) {
1073:             $id = $Model->id;
1074:         }
1075: 
1076:         $node = $Model->find('first', array(
1077:             'conditions' => array($Model->escapeField() => $id),
1078:             'order' => false,
1079:             'recursive' => -1
1080:         ));
1081: 
1082:         if (empty($node)) {
1083:             return false;
1084:         }
1085: 
1086:         extract($this->settings[$Model->alias]);
1087: 
1088:         return $Model->find('count', array(
1089:             'conditions' => array(
1090:                 $scope,
1091:                 $left . ' <' => $node[$Model->alias][$left],
1092:                 $right . ' >' => $node[$Model->alias][$right]
1093:             ),
1094:             'order' => false,
1095:             'recursive' => -1
1096:         ));
1097:     }
1098: 
1099: /**
1100:  * Sets the parent of the given node
1101:  *
1102:  * The force parameter is used to override the "don't change the parent to the current parent" logic in the event
1103:  * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this
1104:  * method could be private, since calling save with parent_id set also calls setParent
1105:  *
1106:  * @param Model $Model Model using this behavior
1107:  * @param int|string|null $parentId Parent record Id
1108:  * @param bool $created True if newly created record else false.
1109:  * @return bool true on success, false on failure
1110:  */
1111:     protected function _setParent(Model $Model, $parentId = null, $created = false) {
1112:         extract($this->settings[$Model->alias]);
1113:         list($node) = array_values($this->_getNode($Model, $Model->id));
1114:         $edge = $this->_getMax($Model, $scope, $right, $recursive, $created);
1115: 
1116:         if (empty($parentId)) {
1117:             $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
1118:             $this->_sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created);
1119:         } else {
1120:             $values = $this->_getNode($Model, $parentId);
1121: 
1122:             if ($values === false) {
1123:                 return false;
1124:             }
1125:             $parentNode = array_values($values);
1126: 
1127:             if (empty($parentNode) || empty($parentNode[0])) {
1128:                 return false;
1129:             }
1130:             $parentNode = $parentNode[0];
1131: 
1132:             if (($Model->id === $parentId)) {
1133:                 return false;
1134:             } elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) {
1135:                 return false;
1136:             }
1137:             if (empty($node[$left]) && empty($node[$right])) {
1138:                 $this->_sync($Model, 2, '+', '>= ' . $parentNode[$right], $created);
1139:                 $result = $Model->save(
1140:                     array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId),
1141:                     array('validate' => false, 'callbacks' => false)
1142:                 );
1143:                 $Model->data = $result;
1144:             } else {
1145:                 $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created);
1146:                 $diff = $node[$right] - $node[$left] + 1;
1147: 
1148:                 if ($node[$left] > $parentNode[$left]) {
1149:                     if ($node[$right] < $parentNode[$right]) {
1150:                         $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
1151:                         $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
1152:                     } else {
1153:                         $this->_sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created);
1154:                         $this->_sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created);
1155:                     }
1156:                 } else {
1157:                     $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created);
1158:                     $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created);
1159:                 }
1160:             }
1161:         }
1162:         return true;
1163:     }
1164: 
1165: /**
1166:  * get the maximum index value in the table.
1167:  *
1168:  * @param Model $Model Model Instance.
1169:  * @param string $scope Scoping conditions.
1170:  * @param string $right Right value
1171:  * @param int $recursive Recursive find value.
1172:  * @param bool $created Whether it's a new record.
1173:  * @return int
1174:  */
1175:     protected function _getMax(Model $Model, $scope, $right, $recursive = -1, $created = false) {
1176:         $db = ConnectionManager::getDataSource($Model->useDbConfig);
1177:         if ($created) {
1178:             if (is_string($scope)) {
1179:                 $scope .= " AND " . $Model->escapeField() . " <> ";
1180:                 $scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey));
1181:             } else {
1182:                 $scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
1183:             }
1184:         }
1185:         $name = $Model->escapeField($right);
1186:         list($edge) = array_values($Model->find('first', array(
1187:             'conditions' => $scope,
1188:             'fields' => $db->calculate($Model, 'max', array($name, $right)),
1189:             'recursive' => $recursive,
1190:             'order' => false,
1191:             'callbacks' => false
1192:         )));
1193:         return (empty($edge[$right])) ? 0 : $edge[$right];
1194:     }
1195: 
1196: /**
1197:  * get the minimum index value in the table.
1198:  *
1199:  * @param Model $Model Model instance.
1200:  * @param string $scope Scoping conditions.
1201:  * @param string $left Left value.
1202:  * @param int $recursive Recurursive find value.
1203:  * @return int
1204:  */
1205:     protected function _getMin(Model $Model, $scope, $left, $recursive = -1) {
1206:         $db = ConnectionManager::getDataSource($Model->useDbConfig);
1207:         $name = $Model->escapeField($left);
1208:         list($edge) = array_values($Model->find('first', array(
1209:             'conditions' => $scope,
1210:             'fields' => $db->calculate($Model, 'min', array($name, $left)),
1211:             'recursive' => $recursive,
1212:             'order' => false,
1213:             'callbacks' => false
1214:         )));
1215:         return (empty($edge[$left])) ? 0 : $edge[$left];
1216:     }
1217: 
1218: /**
1219:  * Table sync method.
1220:  *
1221:  * Handles table sync operations, Taking account of the behavior scope.
1222:  *
1223:  * @param Model $Model Model instance.
1224:  * @param int $shift Shift by.
1225:  * @param string $dir Direction.
1226:  * @param array $conditions Conditions.
1227:  * @param bool $created Whether it's a new record.
1228:  * @param string $field Field type.
1229:  * @return void
1230:  */
1231:     protected function _sync(Model $Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') {
1232:         $ModelRecursive = $Model->recursive;
1233:         extract($this->settings[$Model->alias]);
1234:         $Model->recursive = $recursive;
1235: 
1236:         if ($field === 'both') {
1237:             $this->_sync($Model, $shift, $dir, $conditions, $created, $left);
1238:             $field = $right;
1239:         }
1240:         if (is_string($conditions)) {
1241:             $conditions = array($Model->escapeField($field) . " {$conditions}");
1242:         }
1243:         if (($scope !== '1 = 1' && $scope !== true) && $scope) {
1244:             $conditions[] = $scope;
1245:         }
1246:         if ($created) {
1247:             $conditions['NOT'][$Model->escapeField()] = $Model->id;
1248:         }
1249:         $Model->updateAll(array($Model->escapeField($field) => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions);
1250:         $Model->recursive = $ModelRecursive;
1251:     }
1252: 
1253: }
1254: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs