TreeHelper.php 15 KB

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