TreeHelper.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. <?php
  2. /**
  3. * PHP versions 5
  4. *
  5. * Copyright (c) 2008, Andy Dawson
  6. *
  7. * Licensed under The MIT License
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) 2008, Andy Dawson
  11. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  12. */
  13. App::uses('AppHelper', 'View/Helper');
  14. /**
  15. * Helper to generate tree representations of MPTT or recursively nested data.
  16. *
  17. * @author Andy Dawson
  18. * @author Mark Scherer
  19. * @link http://www.dereuromark.de/2013/02/17/cakephp-and-tree-structures/
  20. */
  21. class TreeHelper extends AppHelper {
  22. /**
  23. * Default settings
  24. *
  25. * @var array
  26. */
  27. protected $_defaults = array(
  28. 'model' => null,
  29. 'alias' => 'name',
  30. 'type' => 'ul',
  31. 'itemType' => 'li',
  32. 'id' => false,
  33. 'class' => false,
  34. 'element' => false,
  35. 'callback' => false,
  36. 'autoPath' => false,
  37. 'hideUnrelated' => false,
  38. 'treePath' => array(),
  39. 'left' => 'lft',
  40. 'right' => 'rght',
  41. 'depth' => 0,
  42. 'maxDepth' => 999,
  43. 'firstChild' => true,
  44. 'indent' => null,
  45. 'splitDepth' => false,
  46. 'splitCount' => null,
  47. 'totalNodes' => null,
  48. 'fullSettings' => false,
  49. );
  50. /**
  51. * Settings property
  52. *
  53. * @var array
  54. */
  55. protected $_settings = array();
  56. /**
  57. * typeAttributes property
  58. *
  59. * @var array
  60. */
  61. protected $_typeAttributes = array();
  62. /**
  63. * typeAttributesNext property
  64. *
  65. * @var array
  66. */
  67. protected $_typeAttributesNext = array();
  68. /**
  69. * itemAttributes property
  70. *
  71. * @var array
  72. */
  73. protected $_itemAttributes = array();
  74. /**
  75. * Helpers variable
  76. *
  77. * @var array
  78. */
  79. public $helpers = array('Html');
  80. /**
  81. * Tree generation method.
  82. *
  83. * Accepts the results of
  84. * find('all', array('fields' => array('lft', 'rght', 'whatever'), 'order' => 'lft ASC'));
  85. * children(); // if you have the tree behavior of course!
  86. * or find('threaded'); and generates a tree structure of the data.
  87. *
  88. * Settings (2nd parameter):
  89. * 'model' => name of the model (key) to look for in the data array. defaults to the first model for the current
  90. * controller. If set to false 2d arrays will be allowed/expected.
  91. * 'alias' => the array key to output for a simple ul (not used if element or callback is specified)
  92. * 'type' => type of output defaults to ul
  93. * 'itemType => type of item output default to li
  94. * 'id' => id for top level 'type'
  95. * 'class' => class for top level 'type'
  96. * 'element' => path to an element to render to get node contents.
  97. * 'callback' => callback to use to get node contents. e.g. array(&$anObject, 'methodName') or 'floatingMethod'
  98. * 'autoPath' => array($left, $right [$classToAdd = 'active']) if set any item in the path will have the class $classToAdd added. MPTT only.
  99. * 'hideUnrelated' => if unrelated (not children, not siblings) should be hidden, needs 'treePath', true/false or array/string for callback
  100. * 'treePath' => treePath to insert into callback/element
  101. * 'left' => name of the 'lft' field if not lft. only applies to MPTT data
  102. * 'right' => name of the 'rght' field if not rght. only applies to MPTT data
  103. * 'depth' => used internally when running recursively, can be used to override the depth in either mode.
  104. * 'maxDepth' => used to control the depth upto which to generate tree
  105. * 'firstChild' => used internally when running recursively.
  106. * 'splitDepth' => if multiple "parallel" types are required, instead of one big type, nominate the depth to do so here
  107. * example: useful if you have 30 items to display, and you'd prefer they appeared in the source as 3 lists of 10 to be able to
  108. * style/float them.
  109. * 'splitCount' => the number of "parallel" types. defaults to null (disabled) set the splitCount,
  110. * and optionally set the splitDepth to get parallel lists
  111. *
  112. * @param array $data data to loop on
  113. * @param array $settings
  114. * @return string html representation of the passed data
  115. */
  116. public function generate($data, $settings = array()) {
  117. if (!$data) {
  118. return '';
  119. }
  120. $this->_settings = array_merge($this->_defaults, (array)$settings);
  121. if ($this->_settings['autoPath'] && !isset($this->_settings['autoPath'][2])) {
  122. $this->_settings['autoPath'][2] = 'active';
  123. }
  124. extract($this->_settings);
  125. if ($indent === null && Configure::read('debug')) {
  126. $indent = true;
  127. }
  128. if ($model === null && $this->_View->params['models']) {
  129. foreach ($this->_View->params['models'] as $model => $value) {
  130. break;
  131. }
  132. }
  133. if ($model === null) {
  134. foreach ($data as $key => $value) {
  135. foreach ($value as $model => $array) {
  136. break;
  137. }
  138. }
  139. }
  140. $this->_settings['model'] = $model;
  141. $this->_itemAttributes = $this->_typeAttributes = $this->_typeAttributesNext = array();
  142. $stack = array();
  143. if ($depth == 0) {
  144. if ($class) {
  145. $this->addTypeAttribute('class', $class, null, 'previous');
  146. }
  147. if ($id) {
  148. $this->addTypeAttribute('id', $id, null, 'previous');
  149. }
  150. }
  151. $return = '';
  152. $addType = true;
  153. $this->_settings['totalNodes'] = count($data);
  154. $keys = array_keys($data);
  155. if ($hideUnrelated === true || is_numeric($hideUnrelated)) {
  156. $this->_markUnrelatedAsHidden($data, $treePath);
  157. } elseif ($hideUnrelated && is_callable($hideUnrelated)) {
  158. call_user_func($hideUnrelated, $data, $treePath);
  159. }
  160. foreach ($data as $i => &$result) {
  161. /* Allow 2d data arrays */
  162. if ($model && isset($result[$model])) {
  163. $row =& $result[$model];
  164. } else {
  165. $row =& $result;
  166. }
  167. /* Close open items as appropriate */
  168. // @codingStandardsIgnoreStart
  169. while ($stack && ($stack[count($stack)-1] < $row[$right])) {
  170. // @codingStandardsIgnoreEnd
  171. array_pop($stack);
  172. if ($indent) {
  173. $whiteSpace = str_repeat("\t", count($stack));
  174. $return .= "\r\n" . $whiteSpace . "\t";
  175. }
  176. if ($type) {
  177. $return .= '</' . $type . '>';
  178. }
  179. if ($itemType) {
  180. $return .= '</' . $itemType . '>';
  181. }
  182. }
  183. /* Some useful vars */
  184. $hasChildren = $firstChild = $lastChild = $hasVisibleChildren = false;
  185. $numberOfDirectChildren = $numberOfTotalChildren = null;
  186. if (isset($result['children'])) {
  187. if ($result['children'] && $depth < $maxDepth) {
  188. $hasChildren = $hasVisibleChildren = true;
  189. $numberOfDirectChildren = count($result['children']);
  190. }
  191. $key = array_search($i, $keys);
  192. if ($key === 0) {
  193. $firstChild = true;
  194. }
  195. if ($key == count($keys) - 1) {
  196. $lastChild = true;
  197. }
  198. } elseif (isset($row[$left])) {
  199. if ($row[$left] != ($row[$right] - 1) && $depth < $maxDepth) {
  200. $hasChildren = true;
  201. $numberOfTotalChildren = ($row[$right] - $row[$left] - 1) / 2;
  202. if (isset($data[$i + 1]) && $data[$i + 1][$model][$right] < $row[$right]) {
  203. $hasVisibleChildren = true;
  204. }
  205. }
  206. if (!isset($data[$i - 1]) || ($data[$i - 1][$model][$left] == ($row[$left] - 1))) {
  207. $firstChild = true;
  208. }
  209. if (!isset($data[$i + 1]) || ($stack && $stack[count($stack) - 1] == ($row[$right] + 1))) {
  210. $lastChild = true;
  211. }
  212. } else {
  213. throw new CakeException('Invalid Tree Structure');
  214. }
  215. $activePathElement = null;
  216. if ($autoPath) {
  217. if ($result[$model][$left] <= $autoPath[0] && $result[$model][$right] >= $autoPath[1]) {
  218. $activePathElement = true;
  219. } elseif (isset($autoPath[3]) && $result[$model][$left] == $autoPath[0]) {
  220. $activePathElement = $autoPath[3];
  221. } else {
  222. $activePathElement = false;
  223. }
  224. }
  225. $depth = $depth ? $depth : count($stack);
  226. $elementData = array(
  227. 'data' => $result,
  228. 'depth' => $depth,
  229. 'hasChildren' => $hasChildren,
  230. 'numberOfDirectChildren' => $numberOfDirectChildren,
  231. 'numberOfTotalChildren' => $numberOfTotalChildren,
  232. 'firstChild' => $firstChild,
  233. 'lastChild' => $lastChild,
  234. 'hasVisibleChildren' => $hasVisibleChildren,
  235. 'activePathElement' => $activePathElement,
  236. 'isSibling' => ($depth == 0 && !$activePathElement) ? true : false,
  237. );
  238. if ($elementData['isSibling'] && $hideUnrelated) {
  239. $result['children'] = array();
  240. }
  241. $this->_settings = array_merge($this->_settings, $elementData);
  242. if ($this->_settings['fullSettings']) {
  243. $elementData = $this->_settings;
  244. }
  245. /* Main Content */
  246. if ($element) {
  247. $content = $this->_View->element($element, $elementData);
  248. } elseif ($callback) {
  249. list($content) = array_map($callback, array($elementData));
  250. } else {
  251. $content = $row[$alias];
  252. }
  253. if (!$content) {
  254. continue;
  255. }
  256. $whiteSpace = str_repeat("\t", $depth);
  257. if ($indent && strpos($content, "\r\n", 1)) {
  258. $content = str_replace("\r\n", "\n" . $whiteSpace . "\t", $content);
  259. }
  260. /* Prefix */
  261. if ($addType) {
  262. if ($indent) {
  263. $return .= "\r\n" . $whiteSpace;
  264. }
  265. if ($type) {
  266. $typeAttributes = $this->_attributes($type, array('data' => $elementData));
  267. $return .= '<' . $type . $typeAttributes . '>';
  268. }
  269. }
  270. if ($indent) {
  271. $return .= "\r\n" . $whiteSpace . "\t";
  272. }
  273. if ($itemType) {
  274. $itemAttributes = $this->_attributes($itemType, $elementData);
  275. $return .= '<' . $itemType . $itemAttributes . '>';
  276. }
  277. $return .= $content;
  278. /* Suffix */
  279. $addType = false;
  280. if ($hasVisibleChildren) {
  281. if ($numberOfDirectChildren) {
  282. $settings['depth'] = $depth + 1;
  283. $return .= $this->_suffix();
  284. $return .= $this->generate($result['children'], $settings);
  285. if ($itemType) {
  286. if ($indent) {
  287. $return .= $whiteSpace . "\t";
  288. }
  289. $return .= '</' . $itemType . '>';
  290. }
  291. } elseif ($numberOfTotalChildren) {
  292. $addType = true;
  293. $stack[] = $row[$right];
  294. }
  295. } else {
  296. if ($itemType) {
  297. $return .= '</' . $itemType . '>';
  298. }
  299. $return .= $this->_suffix();
  300. }
  301. }
  302. /* Cleanup */
  303. while ($stack) {
  304. array_pop($stack);
  305. if ($indent) {
  306. $whiteSpace = str_repeat("\t", count($stack));
  307. $return .= "\r\n" . $whiteSpace . "\t";
  308. }
  309. if ($type) {
  310. $return .= '</' . $type . '>';
  311. }
  312. if ($itemType) {
  313. $return .= '</' . $itemType . '>';
  314. }
  315. }
  316. if ($return && $indent) {
  317. $return .= "\r\n";
  318. }
  319. if ($return && $type) {
  320. if ($indent) {
  321. $return .= $whiteSpace;
  322. }
  323. $return .= '</' . $type . '>';
  324. if ($indent) {
  325. $return .= "\r\n";
  326. }
  327. }
  328. return $return;
  329. }
  330. /**
  331. * addItemAttribute function
  332. *
  333. * Called to modify the attributes of the next <item> to be processed
  334. * Note that the content of a 'node' is processed before generating its wrapping <item> tag
  335. *
  336. * @param string $id
  337. * @param string $key
  338. * @param mixed $value
  339. * @return void
  340. */
  341. public function addItemAttribute($id = '', $key = '', $value = null) {
  342. if ($value !== null) {
  343. $this->_itemAttributes[$id][$key] = $value;
  344. } elseif (!(isset($this->_itemAttributes[$id]) && in_array($key, $this->_itemAttributes[$id]))) {
  345. $this->_itemAttributes[$id][] = $key;
  346. }
  347. }
  348. /**
  349. * addTypeAttribute function
  350. *
  351. * Called to modify the attributes of the next <type> to be processed
  352. * Note that the content of a 'node' is processed before generating its wrapping <type> tag (if appropriate)
  353. * An 'interesting' case is that of a first child with children. To generate the output
  354. * <ul> (1)
  355. * <li>XYZ (3)
  356. * <ul> (2)
  357. * <li>ABC...
  358. * ...
  359. * </ul>
  360. * ...
  361. * The processing order is indicated by the numbers in brackets.
  362. * attributes are allways applied to the next type (2) to be generated
  363. * to set properties of the holding type - pass 'previous' for the 4th param
  364. * i.e.
  365. * // Hide children (2)
  366. * $tree->addTypeAttribute('style', 'display', 'hidden');
  367. * // give top level type (1) a class
  368. * $tree->addTypeAttribute('class', 'hasHiddenGrandChildren', null, 'previous');
  369. *
  370. * @param string $id
  371. * @param string $key
  372. * @param mixed $value
  373. * @return void
  374. */
  375. public function addTypeAttribute($id = '', $key = '', $value = null, $previousOrNext = 'next') {
  376. $var = '_typeAttributes';
  377. $firstChild = isset($this->_settings['firstChild']) ? $this->_settings['firstChild'] : true;
  378. if ($previousOrNext === 'next' && $firstChild) {
  379. $var = '_typeAttributesNext';
  380. }
  381. if ($value !== null) {
  382. $this->{$var}[$id][$key] = $value;
  383. } elseif (!(isset($this->{$var}[$id]) && in_array($key, $this->{$var}[$id]))) {
  384. $this->{$var}[$id][] = $key;
  385. }
  386. }
  387. /**
  388. * supressChildren method
  389. *
  390. * @return void
  391. */
  392. public function supressChildren() {
  393. }
  394. /**
  395. * Suffix method.
  396. *
  397. * Used to close and reopen a ul/ol to allow easier listings
  398. *
  399. * @return void
  400. */
  401. protected function _suffix($reset = false) {
  402. static $_splitCount = 0;
  403. static $_splitCounter = 0;
  404. if ($reset) {
  405. $_splitCount = 0;
  406. $_splitCounter = 0;
  407. }
  408. extract($this->_settings);
  409. if ($splitDepth || $splitCount) {
  410. if (!$splitDepth) {
  411. $_splitCount = $totalNodes / $splitCount;
  412. $rounded = (int)$_splitCount;
  413. if ($rounded < $_splitCount) {
  414. $_splitCount = $rounded + 1;
  415. }
  416. } elseif ($depth == $splitDepth - 1) {
  417. $total = $numberOfDirectChildren ? $numberOfDirectChildren : $numberOfTotalChildren;
  418. if ($total) {
  419. $_splitCounter = 0;
  420. $_splitCount = $total / $splitCount;
  421. $rounded = (int)$_splitCount;
  422. if ($rounded < $_splitCount) {
  423. $_splitCount = $rounded + 1;
  424. }
  425. }
  426. }
  427. if (!$splitDepth || $depth == $splitDepth) {
  428. $_splitCounter++;
  429. if ($type && ($_splitCounter % $_splitCount) === 0 && !$lastChild) {
  430. unset ($this->_settings['callback']);
  431. return '</' . $type . '><' . $type . '>';
  432. }
  433. }
  434. }
  435. }
  436. /**
  437. * Attributes function.
  438. *
  439. * Logic to apply styles to tags.
  440. *
  441. * @param mixed $rType
  442. * @param array $elementData
  443. * @return void
  444. */
  445. protected function _attributes($rType, $elementData = array(), $clear = true) {
  446. extract($this->_settings);
  447. if ($rType == $type) {
  448. $attributes = $this->_typeAttributes;
  449. if ($clear) {
  450. $this->_typeAttributes = $this->_typeAttributesNext;
  451. $this->_typeAttributesNext = array();
  452. }
  453. } else {
  454. $attributes = $this->_itemAttributes;
  455. $this->_itemAttributes = array();
  456. if ($clear) {
  457. $this->_itemAttributes = array();
  458. }
  459. }
  460. if ($rType == $itemType && $elementData['activePathElement']) {
  461. if ($elementData['activePathElement'] === true) {
  462. $attributes['class'][] = $autoPath[2];
  463. } else {
  464. $attributes['class'][] = $elementData['activePathElement'];
  465. }
  466. }
  467. if (!$attributes) {
  468. return '';
  469. }
  470. foreach ($attributes as $type => $values) {
  471. foreach ($values as $key => $val) {
  472. if (is_array($val)) {
  473. $attributes[$type][$key] = '';
  474. foreach ($val as $vKey => $v) {
  475. $attributes[$type][$key][$vKey] .= $vKey . ':' . $v;
  476. }
  477. $attributes[$type][$key] = implode(';', $attributes[$type][$key]);
  478. }
  479. if (is_string($key)) {
  480. $attributes[$type][$key] = $key . ':' . $val . ';';
  481. }
  482. }
  483. $attributes[$type] = $type . '="' . implode(' ', $attributes[$type]) . '"';
  484. }
  485. return ' ' . implode(' ', $attributes);
  486. }
  487. /**
  488. * Mark unrelated records as hidden using `'hide' => 1`.
  489. * In the callback or element you can then return early in this case.
  490. *
  491. * @param array $tree
  492. * @param array $treePath
  493. * @param integer $level
  494. * @return void
  495. */
  496. protected function _markUnrelatedAsHidden(&$tree, $path, $level = 0) {
  497. extract($this->_settings);
  498. $siblingIsActive = false;
  499. foreach ($tree as $key => &$subTree) {
  500. if (!isset($subTree['children'])) {
  501. throw new CakeException('Only workes with threaded (nested children) results');
  502. }
  503. if (!empty($path[$level]) && $subTree[$model]['id'] == $path[$level][$model]['id']) {
  504. $subTree[$model]['show'] = 1;
  505. $siblingIsActive = true;
  506. }
  507. if (!empty($subTree[$model]['show'])) {
  508. foreach ($subTree['children'] as &$v) {
  509. $v[$model]['parent_show'] = 1;
  510. }
  511. }
  512. if (is_numeric($hideUnrelated) && $hideUnrelated > $level) {
  513. $siblingIsActive = true;
  514. }
  515. }
  516. foreach ($tree as $key => &$subTree) {
  517. if ($level && !$siblingIsActive && !isset($subTree[$model]['parent_show'])) {
  518. $subTree[$model]['hide'] = 1;
  519. }
  520. $this->_markUnrelatedAsHidden($subTree['children'], $path, $level + 1);
  521. }
  522. }
  523. }