TreeHelper.php 15 KB

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