TreeHelper.php 13 KB

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