TreeHelper.php 15 KB

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