TreeHelper.php 16 KB

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