TreeHelper.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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) {
  156. $this->_markUnrelatedAsHidden($data, $treePath);
  157. } elseif ($hideUnrelated && is_callable($hideUnrelated)) {
  158. call_user_func($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. $elementData = array(
  226. 'data' => $result,
  227. 'depth' => $depth ? $depth : count($stack),
  228. 'hasChildren' => $hasChildren,
  229. 'numberOfDirectChildren' => $numberOfDirectChildren,
  230. 'numberOfTotalChildren' => $numberOfTotalChildren,
  231. 'firstChild' => $firstChild,
  232. 'lastChild' => $lastChild,
  233. 'hasVisibleChildren' => $hasVisibleChildren,
  234. 'activePathElement' => $activePathElement,
  235. );
  236. $this->_settings = array_merge($this->_settings, $elementData);
  237. if ($this->_settings['fullSettings']) {
  238. $elementData = $this->_settings;
  239. }
  240. /* Main Content */
  241. if ($element) {
  242. $content = $this->_View->element($element, $elementData);
  243. } elseif ($callback) {
  244. list($content) = array_map($callback, array($elementData));
  245. } else {
  246. $content = $row[$alias];
  247. }
  248. if (!$content) {
  249. continue;
  250. }
  251. $whiteSpace = str_repeat("\t", $depth);
  252. if ($indent && strpos($content, "\r\n", 1)) {
  253. $content = str_replace("\r\n", "\n" . $whiteSpace . "\t", $content);
  254. }
  255. /* Prefix */
  256. if ($addType) {
  257. if ($indent) {
  258. $return .= "\r\n" . $whiteSpace;
  259. }
  260. if ($type) {
  261. $typeAttributes = $this->_attributes($type, array('data' => $elementData));
  262. $return .= '<' . $type . $typeAttributes . '>';
  263. }
  264. }
  265. if ($indent) {
  266. $return .= "\r\n" . $whiteSpace . "\t";
  267. }
  268. if ($itemType) {
  269. $itemAttributes = $this->_attributes($itemType, $elementData);
  270. $return .= '<' . $itemType . $itemAttributes . '>';
  271. }
  272. $return .= $content;
  273. /* Suffix */
  274. $addType = false;
  275. if ($hasVisibleChildren) {
  276. if ($numberOfDirectChildren) {
  277. $settings['depth'] = $depth + 1;
  278. $return .= $this->_suffix();
  279. $return .= $this->generate($result['children'], $settings);
  280. if ($itemType) {
  281. if ($indent) {
  282. $return .= $whiteSpace . "\t";
  283. }
  284. $return .= '</' . $itemType . '>';
  285. }
  286. } elseif ($numberOfTotalChildren) {
  287. $addType = true;
  288. $stack[] = $row[$right];
  289. }
  290. } else {
  291. if ($itemType) {
  292. $return .= '</' . $itemType . '>';
  293. }
  294. $return .= $this->_suffix();
  295. }
  296. }
  297. /* Cleanup */
  298. while ($stack) {
  299. array_pop($stack);
  300. if ($indent) {
  301. $whiteSpace = str_repeat("\t", count($stack));
  302. $return .= "\r\n" . $whiteSpace . "\t";
  303. }
  304. if ($type) {
  305. $return .= '</' . $type . '>';
  306. }
  307. if ($itemType) {
  308. $return .= '</' . $itemType . '>';
  309. }
  310. }
  311. if ($return && $indent) {
  312. $return .= "\r\n";
  313. }
  314. if ($return && $type) {
  315. if ($indent) {
  316. $return .= $whiteSpace;
  317. }
  318. $return .= '</' . $type . '>';
  319. if ($indent) {
  320. $return .= "\r\n";
  321. }
  322. }
  323. return $return;
  324. }
  325. /**
  326. * addItemAttribute function
  327. *
  328. * Called to modify the attributes of the next <item> to be processed
  329. * Note that the content of a 'node' is processed before generating its wrapping <item> tag
  330. *
  331. * @param string $id
  332. * @param string $key
  333. * @param mixed $value
  334. * @return void
  335. */
  336. public function addItemAttribute($id = '', $key = '', $value = null) {
  337. if ($value !== null) {
  338. $this->_itemAttributes[$id][$key] = $value;
  339. } elseif (!(isset($this->_itemAttributes[$id]) && in_array($key, $this->_itemAttributes[$id]))) {
  340. $this->_itemAttributes[$id][] = $key;
  341. }
  342. }
  343. /**
  344. * addTypeAttribute function
  345. *
  346. * Called to modify the attributes of the next <type> to be processed
  347. * Note that the content of a 'node' is processed before generating its wrapping <type> tag (if appropriate)
  348. * An 'interesting' case is that of a first child with children. To generate the output
  349. * <ul> (1)
  350. * <li>XYZ (3)
  351. * <ul> (2)
  352. * <li>ABC...
  353. * ...
  354. * </ul>
  355. * ...
  356. * The processing order is indicated by the numbers in brackets.
  357. * attributes are allways applied to the next type (2) to be generated
  358. * to set properties of the holding type - pass 'previous' for the 4th param
  359. * i.e.
  360. * // Hide children (2)
  361. * $tree->addTypeAttribute('style', 'display', 'hidden');
  362. * // give top level type (1) a class
  363. * $tree->addTypeAttribute('class', 'hasHiddenGrandChildren', null, 'previous');
  364. *
  365. * @param string $id
  366. * @param string $key
  367. * @param mixed $value
  368. * @return void
  369. */
  370. public function addTypeAttribute($id = '', $key = '', $value = null, $previousOrNext = 'next') {
  371. $var = '_typeAttributes';
  372. $firstChild = isset($this->_settings['firstChild']) ? $this->_settings['firstChild'] : true;
  373. if ($previousOrNext === 'next' && $firstChild) {
  374. $var = '_typeAttributesNext';
  375. }
  376. if ($value !== null) {
  377. $this->{$var}[$id][$key] = $value;
  378. } elseif (!(isset($this->{$var}[$id]) && in_array($key, $this->{$var}[$id]))) {
  379. $this->{$var}[$id][] = $key;
  380. }
  381. }
  382. /**
  383. * supressChildren method
  384. *
  385. * @return void
  386. */
  387. public function supressChildren() {
  388. }
  389. /**
  390. * Suffix method.
  391. *
  392. * Used to close and reopen a ul/ol to allow easier listings
  393. *
  394. * @return void
  395. */
  396. protected function _suffix($reset = false) {
  397. static $_splitCount = 0;
  398. static $_splitCounter = 0;
  399. if ($reset) {
  400. $_splitCount = 0;
  401. $_splitCounter = 0;
  402. }
  403. extract($this->_settings);
  404. if ($splitDepth || $splitCount) {
  405. if (!$splitDepth) {
  406. $_splitCount = $totalNodes / $splitCount;
  407. $rounded = (int)$_splitCount;
  408. if ($rounded < $_splitCount) {
  409. $_splitCount = $rounded + 1;
  410. }
  411. } elseif ($depth == $splitDepth - 1) {
  412. $total = $numberOfDirectChildren ? $numberOfDirectChildren : $numberOfTotalChildren;
  413. if ($total) {
  414. $_splitCounter = 0;
  415. $_splitCount = $total / $splitCount;
  416. $rounded = (int)$_splitCount;
  417. if ($rounded < $_splitCount) {
  418. $_splitCount = $rounded + 1;
  419. }
  420. }
  421. }
  422. if (!$splitDepth || $depth == $splitDepth) {
  423. $_splitCounter++;
  424. if ($type && ($_splitCounter % $_splitCount) === 0 && !$lastChild) {
  425. unset ($this->_settings['callback']);
  426. return '</' . $type . '><' . $type . '>';
  427. }
  428. }
  429. }
  430. }
  431. /**
  432. * Attributes function.
  433. *
  434. * Logic to apply styles to tags.
  435. *
  436. * @param mixed $rType
  437. * @param array $elementData
  438. * @return void
  439. */
  440. protected function _attributes($rType, $elementData = array(), $clear = true) {
  441. extract($this->_settings);
  442. if ($rType == $type) {
  443. $attributes = $this->_typeAttributes;
  444. if ($clear) {
  445. $this->_typeAttributes = $this->_typeAttributesNext;
  446. $this->_typeAttributesNext = array();
  447. }
  448. } else {
  449. $attributes = $this->_itemAttributes;
  450. if ($clear) {
  451. $this->_itemAttributes = array();
  452. }
  453. }
  454. if ($rType == $itemType && $elementData['activePathElement']) {
  455. if ($elementData['activePathElement'] === true) {
  456. $attributes['class'][] = $autoPath[2];
  457. } else {
  458. $attributes['class'][] = $elementData['activePathElement'];
  459. }
  460. }
  461. if (!$attributes) {
  462. return '';
  463. }
  464. foreach ($attributes as $type => $values) {
  465. foreach ($values as $key => $val) {
  466. if (is_array($val)) {
  467. $attributes[$type][$key] = '';
  468. foreach ($val as $vKey => $v) {
  469. $attributes[$type][$key][$vKey] .= $vKey . ':' . $v;
  470. }
  471. $attributes[$type][$key] = implode(';', $attributes[$type][$key]);
  472. }
  473. if (is_string($key)) {
  474. $attributes[$type][$key] = $key . ':' . $val . ';';
  475. }
  476. }
  477. $attributes[$type] = $type . '="' . implode(' ', $attributes[$type]) . '"';
  478. }
  479. return ' ' . implode(' ', $attributes);
  480. }
  481. /**
  482. * Mark unrelated records as hidden using `'hide' => 1`
  483. * In the callback or element you can then return early in this case
  484. *
  485. * @param array $tree
  486. * @param array $treePath
  487. * @param integer $level
  488. * @return void
  489. */
  490. protected function _markUnrelatedAsHidden(&$tree, $path, $level = 0) {
  491. extract($this->_settings);
  492. $siblingIsActive = false;
  493. foreach ($tree as $key => &$subTree) {
  494. if (!isset($subTree['children'])) {
  495. throw new CakeException('Only workes with threaded (nested children) results');
  496. }
  497. if (!empty($path[$level]) && $subTree[$model]['id'] == $path[$level][$model]['id']) {
  498. $subTree[$model]['show'] = 1;
  499. $siblingIsActive = true;
  500. }
  501. if (!empty($subTree[$model]['show'])) {
  502. foreach ($subTree['children'] as &$v) {
  503. $v[$model]['parent_show'] = 1;
  504. }
  505. }
  506. }
  507. foreach ($tree as $key => &$subTree) {
  508. if ($level && !$siblingIsActive && !isset($subTree[$model]['parent_show'])) {
  509. $subTree[$model]['hide'] = 1;
  510. }
  511. $this->_markUnrelatedAsHidden($subTree['children'], $path, $level + 1);
  512. }
  513. }
  514. }