TreeHelper.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. * @throws CakeException
  116. */
  117. public function generate($data, $settings = array()) {
  118. if (!$data) {
  119. return '';
  120. }
  121. $this->_settings = array_merge($this->_defaults, (array)$settings);
  122. if ($this->_settings['autoPath'] && !isset($this->_settings['autoPath'][2])) {
  123. $this->_settings['autoPath'][2] = 'active';
  124. }
  125. extract($this->_settings);
  126. if ($indent === null && Configure::read('debug')) {
  127. $indent = true;
  128. }
  129. if ($model === null && $this->_View->params['models']) {
  130. foreach ($this->_View->params['models'] as $model => $value) {
  131. break;
  132. }
  133. }
  134. if ($model === null) {
  135. foreach ($data as $key => $value) {
  136. foreach ($value as $model => $array) {
  137. break;
  138. }
  139. }
  140. }
  141. $this->_settings['model'] = $model;
  142. $this->_itemAttributes = $this->_typeAttributes = $this->_typeAttributesNext = array();
  143. $stack = array();
  144. if ($depth == 0) {
  145. if ($class) {
  146. $this->addTypeAttribute('class', $class, null, 'previous');
  147. }
  148. if ($id) {
  149. $this->addTypeAttribute('id', $id, null, 'previous');
  150. }
  151. }
  152. $return = '';
  153. $addType = true;
  154. $this->_settings['totalNodes'] = count($data);
  155. $keys = array_keys($data);
  156. if ($hideUnrelated === true || is_numeric($hideUnrelated)) {
  157. $this->_markUnrelatedAsHidden($data, $treePath);
  158. } elseif ($hideUnrelated && is_callable($hideUnrelated)) {
  159. call_user_func($hideUnrelated, $data, $treePath);
  160. }
  161. foreach ($data as $i => &$result) {
  162. /* Allow 2d data arrays */
  163. if ($model && isset($result[$model])) {
  164. $row =& $result[$model];
  165. } else {
  166. $row =& $result;
  167. }
  168. /* Close open items as appropriate */
  169. // @codingStandardsIgnoreStart
  170. while ($stack && ($stack[count($stack)-1] < $row[$right])) {
  171. // @codingStandardsIgnoreEnd
  172. array_pop($stack);
  173. if ($indent) {
  174. $whiteSpace = str_repeat("\t", count($stack));
  175. $return .= "\r\n" . $whiteSpace . "\t";
  176. }
  177. if ($type) {
  178. $return .= '</' . $type . '>';
  179. }
  180. if ($itemType) {
  181. $return .= '</' . $itemType . '>';
  182. }
  183. }
  184. /* Some useful vars */
  185. $hasChildren = $firstChild = $lastChild = $hasVisibleChildren = false;
  186. $numberOfDirectChildren = $numberOfTotalChildren = null;
  187. if (isset($result['children'])) {
  188. if ($result['children'] && $depth < $maxDepth) {
  189. $hasChildren = $hasVisibleChildren = true;
  190. $numberOfDirectChildren = count($result['children']);
  191. }
  192. $key = array_search($i, $keys);
  193. if ($key === 0) {
  194. $firstChild = true;
  195. }
  196. if ($key == count($keys) - 1) {
  197. $lastChild = true;
  198. }
  199. } elseif (isset($row[$left])) {
  200. if ($row[$left] != ($row[$right] - 1) && $depth < $maxDepth) {
  201. $hasChildren = true;
  202. $numberOfTotalChildren = ($row[$right] - $row[$left] - 1) / 2;
  203. if (isset($data[$i + 1]) && $data[$i + 1][$model][$right] < $row[$right]) {
  204. $hasVisibleChildren = true;
  205. }
  206. }
  207. if (!isset($data[$i - 1]) || ($data[$i - 1][$model][$left] == ($row[$left] - 1))) {
  208. $firstChild = true;
  209. }
  210. if (!isset($data[$i + 1]) || ($stack && $stack[count($stack) - 1] == ($row[$right] + 1))) {
  211. $lastChild = true;
  212. }
  213. } else {
  214. throw new CakeException('Invalid Tree Structure');
  215. }
  216. $activePathElement = null;
  217. if ($autoPath) {
  218. if ($result[$model][$left] <= $autoPath[0] && $result[$model][$right] >= $autoPath[1]) {
  219. $activePathElement = true;
  220. } elseif (isset($autoPath[3]) && $result[$model][$left] == $autoPath[0]) {
  221. $activePathElement = $autoPath[3];
  222. } else {
  223. $activePathElement = false;
  224. }
  225. }
  226. $depth = $depth ? $depth : count($stack);
  227. $elementData = array(
  228. 'data' => $result,
  229. 'depth' => $depth,
  230. 'hasChildren' => $hasChildren,
  231. 'numberOfDirectChildren' => $numberOfDirectChildren,
  232. 'numberOfTotalChildren' => $numberOfTotalChildren,
  233. 'firstChild' => $firstChild,
  234. 'lastChild' => $lastChild,
  235. 'hasVisibleChildren' => $hasVisibleChildren,
  236. 'activePathElement' => $activePathElement,
  237. 'isSibling' => ($depth == 0 && !$activePathElement) ? true : false,
  238. );
  239. if ($elementData['isSibling'] && $hideUnrelated) {
  240. $result['children'] = array();
  241. }
  242. $this->_settings = array_merge($this->_settings, $elementData);
  243. if ($this->_settings['fullSettings']) {
  244. $elementData = $this->_settings;
  245. }
  246. /* Main Content */
  247. if ($element) {
  248. $content = $this->_View->element($element, $elementData);
  249. } elseif ($callback) {
  250. list($content) = array_map($callback, array($elementData));
  251. } else {
  252. $content = $row[$alias];
  253. }
  254. if (!$content) {
  255. continue;
  256. }
  257. $whiteSpace = str_repeat("\t", $depth);
  258. if ($indent && strpos($content, "\r\n", 1)) {
  259. $content = str_replace("\r\n", "\n" . $whiteSpace . "\t", $content);
  260. }
  261. /* Prefix */
  262. if ($addType) {
  263. if ($indent) {
  264. $return .= "\r\n" . $whiteSpace;
  265. }
  266. if ($type) {
  267. $typeAttributes = $this->_attributes($type, array('data' => $elementData));
  268. $return .= '<' . $type . $typeAttributes . '>';
  269. }
  270. }
  271. if ($indent) {
  272. $return .= "\r\n" . $whiteSpace . "\t";
  273. }
  274. if ($itemType) {
  275. $itemAttributes = $this->_attributes($itemType, $elementData);
  276. $return .= '<' . $itemType . $itemAttributes . '>';
  277. }
  278. $return .= $content;
  279. /* Suffix */
  280. $addType = false;
  281. if ($hasVisibleChildren) {
  282. if ($numberOfDirectChildren) {
  283. $settings['depth'] = $depth + 1;
  284. $return .= $this->_suffix();
  285. $return .= $this->generate($result['children'], $settings);
  286. if ($itemType) {
  287. if ($indent) {
  288. $return .= $whiteSpace . "\t";
  289. }
  290. $return .= '</' . $itemType . '>';
  291. }
  292. } elseif ($numberOfTotalChildren) {
  293. $addType = true;
  294. $stack[] = $row[$right];
  295. }
  296. } else {
  297. if ($itemType) {
  298. $return .= '</' . $itemType . '>';
  299. }
  300. $return .= $this->_suffix();
  301. }
  302. }
  303. /* Cleanup */
  304. while ($stack) {
  305. array_pop($stack);
  306. if ($indent) {
  307. $whiteSpace = str_repeat("\t", count($stack));
  308. $return .= "\r\n" . $whiteSpace . "\t";
  309. }
  310. if ($type) {
  311. $return .= '</' . $type . '>';
  312. }
  313. if ($itemType) {
  314. $return .= '</' . $itemType . '>';
  315. }
  316. }
  317. if ($return && $indent) {
  318. $return .= "\r\n";
  319. }
  320. if ($return && $type) {
  321. if ($indent) {
  322. $return .= $whiteSpace;
  323. }
  324. $return .= '</' . $type . '>';
  325. if ($indent) {
  326. $return .= "\r\n";
  327. }
  328. }
  329. return $return;
  330. }
  331. /**
  332. * AddItemAttribute function
  333. *
  334. * Called to modify the attributes of the next <item> to be processed
  335. * Note that the content of a 'node' is processed before generating its wrapping <item> tag
  336. *
  337. * @param string $id
  338. * @param string $key
  339. * @param mixed $value
  340. * @return void
  341. */
  342. public function addItemAttribute($id = '', $key = '', $value = null) {
  343. if ($value !== null) {
  344. $this->_itemAttributes[$id][$key] = $value;
  345. } elseif (!(isset($this->_itemAttributes[$id]) && in_array($key, $this->_itemAttributes[$id]))) {
  346. $this->_itemAttributes[$id][] = $key;
  347. }
  348. }
  349. /**
  350. * AddTypeAttribute function
  351. *
  352. * Called to modify the attributes of the next <type> to be processed
  353. * Note that the content of a 'node' is processed before generating its wrapping <type> tag (if appropriate)
  354. * An 'interesting' case is that of a first child with children. To generate the output
  355. * <ul> (1)
  356. * <li>XYZ (3)
  357. * <ul> (2)
  358. * <li>ABC...
  359. * ...
  360. * </ul>
  361. * ...
  362. * The processing order is indicated by the numbers in brackets.
  363. * attributes are allways applied to the next type (2) to be generated
  364. * to set properties of the holding type - pass 'previous' for the 4th param
  365. * i.e.
  366. * // Hide children (2)
  367. * $tree->addTypeAttribute('style', 'display', 'hidden');
  368. * // give top level type (1) a class
  369. * $tree->addTypeAttribute('class', 'hasHiddenGrandChildren', null, 'previous');
  370. *
  371. * @param string $id
  372. * @param string $key
  373. * @param mixed $value
  374. * @return void
  375. */
  376. public function addTypeAttribute($id = '', $key = '', $value = null, $previousOrNext = 'next') {
  377. $var = '_typeAttributes';
  378. $firstChild = isset($this->_settings['firstChild']) ? $this->_settings['firstChild'] : true;
  379. if ($previousOrNext === 'next' && $firstChild) {
  380. $var = '_typeAttributesNext';
  381. }
  382. if ($value !== null) {
  383. $this->{$var}[$id][$key] = $value;
  384. } elseif (!(isset($this->{$var}[$id]) && in_array($key, $this->{$var}[$id]))) {
  385. $this->{$var}[$id][] = $key;
  386. }
  387. }
  388. /**
  389. * SupressChildren method
  390. *
  391. * @return void
  392. */
  393. public function supressChildren() {
  394. }
  395. /**
  396. * Suffix method.
  397. *
  398. * Used to close and reopen a ul/ol to allow easier listings
  399. *
  400. * @return void
  401. */
  402. protected function _suffix($reset = false) {
  403. static $_splitCount = 0;
  404. static $_splitCounter = 0;
  405. if ($reset) {
  406. $_splitCount = 0;
  407. $_splitCounter = 0;
  408. }
  409. extract($this->_settings);
  410. if ($splitDepth || $splitCount) {
  411. if (!$splitDepth) {
  412. $_splitCount = $totalNodes / $splitCount;
  413. $rounded = (int)$_splitCount;
  414. if ($rounded < $_splitCount) {
  415. $_splitCount = $rounded + 1;
  416. }
  417. } elseif ($depth == $splitDepth - 1) {
  418. $total = $numberOfDirectChildren ? $numberOfDirectChildren : $numberOfTotalChildren;
  419. if ($total) {
  420. $_splitCounter = 0;
  421. $_splitCount = $total / $splitCount;
  422. $rounded = (int)$_splitCount;
  423. if ($rounded < $_splitCount) {
  424. $_splitCount = $rounded + 1;
  425. }
  426. }
  427. }
  428. if (!$splitDepth || $depth == $splitDepth) {
  429. $_splitCounter++;
  430. if ($type && ($_splitCounter % $_splitCount) === 0 && !$lastChild) {
  431. unset ($this->_settings['callback']);
  432. return '</' . $type . '><' . $type . '>';
  433. }
  434. }
  435. }
  436. }
  437. /**
  438. * Attributes function.
  439. *
  440. * Logic to apply styles to tags.
  441. *
  442. * @param mixed $rType
  443. * @param array $elementData
  444. * @return void
  445. */
  446. protected function _attributes($rType, $elementData = array(), $clear = true) {
  447. extract($this->_settings);
  448. if ($rType == $type) {
  449. $attributes = $this->_typeAttributes;
  450. if ($clear) {
  451. $this->_typeAttributes = $this->_typeAttributesNext;
  452. $this->_typeAttributesNext = array();
  453. }
  454. } else {
  455. $attributes = $this->_itemAttributes;
  456. $this->_itemAttributes = array();
  457. if ($clear) {
  458. $this->_itemAttributes = array();
  459. }
  460. }
  461. if ($rType == $itemType && $elementData['activePathElement']) {
  462. if ($elementData['activePathElement'] === true) {
  463. $attributes['class'][] = $autoPath[2];
  464. } else {
  465. $attributes['class'][] = $elementData['activePathElement'];
  466. }
  467. }
  468. if (!$attributes) {
  469. return '';
  470. }
  471. foreach ($attributes as $type => $values) {
  472. foreach ($values as $key => $val) {
  473. if (is_array($val)) {
  474. $attributes[$type][$key] = '';
  475. foreach ($val as $vKey => $v) {
  476. $attributes[$type][$key][$vKey] .= $vKey . ':' . $v;
  477. }
  478. $attributes[$type][$key] = implode(';', $attributes[$type][$key]);
  479. }
  480. if (is_string($key)) {
  481. $attributes[$type][$key] = $key . ':' . $val . ';';
  482. }
  483. }
  484. $attributes[$type] = $type . '="' . implode(' ', $attributes[$type]) . '"';
  485. }
  486. return ' ' . implode(' ', $attributes);
  487. }
  488. /**
  489. * Mark unrelated records as hidden using `'hide' => 1`.
  490. * In the callback or element you can then return early in this case.
  491. *
  492. * @param array $tree
  493. * @param array $treePath
  494. * @param integer $level
  495. * @return void
  496. * @throws CakeException
  497. */
  498. protected function _markUnrelatedAsHidden(&$tree, $path, $level = 0) {
  499. extract($this->_settings);
  500. $siblingIsActive = false;
  501. foreach ($tree as $key => &$subTree) {
  502. if (!isset($subTree['children'])) {
  503. throw new CakeException('Only workes with threaded (nested children) results');
  504. }
  505. if (!empty($path[$level]) && $subTree[$model]['id'] == $path[$level][$model]['id']) {
  506. $subTree[$model]['show'] = 1;
  507. $siblingIsActive = true;
  508. }
  509. if (!empty($subTree[$model]['show'])) {
  510. foreach ($subTree['children'] as &$v) {
  511. $v[$model]['parent_show'] = 1;
  512. }
  513. }
  514. if (is_numeric($hideUnrelated) && $hideUnrelated > $level) {
  515. $siblingIsActive = true;
  516. }
  517. }
  518. foreach ($tree as $key => &$subTree) {
  519. if ($level && !$siblingIsActive && !isset($subTree[$model]['parent_show'])) {
  520. $subTree[$model]['hide'] = 1;
  521. }
  522. $this->_markUnrelatedAsHidden($subTree['children'], $path, $level + 1);
  523. }
  524. }
  525. }