TreeHelper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. /**
  3. * Tree Helper.
  4. *
  5. * Used the generate nested representations of hierarchial data
  6. *
  7. * PHP versions 4 and 5
  8. *
  9. * Copyright (c) 2008, Andy Dawson
  10. *
  11. * Licensed under The MIT License
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @filesource
  15. * @copyright Copyright (c) 2008, Andy Dawson
  16. * @modifiedBy $LastChangedBy: 2013-02-05 ms
  17. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  18. */
  19. App::uses('AppHelper', 'View/Helper');
  20. /**
  21. * Tree helper
  22. *
  23. * Helper to generate tree representations of MPTT or recursively nested data
  24. */
  25. class TreeHelper extends AppHelper {
  26. /**
  27. * settings property
  28. *
  29. * @var array
  30. * @access private
  31. */
  32. protected $_settings = array();
  33. /**
  34. * typeAttributes property
  35. *
  36. * @var array
  37. * @access private
  38. */
  39. protected $_typeAttributes = array();
  40. /**
  41. * typeAttributesNext property
  42. *
  43. * @var array
  44. * @access private
  45. */
  46. protected $_typeAttributesNext = array();
  47. /**
  48. * itemAttributes property
  49. *
  50. * @var array
  51. * @access private
  52. */
  53. protected $_itemAttributes = array();
  54. /**
  55. * helpers variable
  56. *
  57. * @var array
  58. * @access public
  59. */
  60. public $helpers = array('Html');
  61. /**
  62. * Tree generation method.
  63. *
  64. * Accepts the results of
  65. * find('all', array('fields' => array('lft', 'rght', 'whatever'), 'order' => 'lft ASC'));
  66. * children(); // if you have the tree behavior of course!
  67. * or findAllThreaded(); and generates a tree structure of the data.
  68. *
  69. * Settings (2nd parameter):
  70. * 'model' => name of the model (key) to look for in the data array. defaults to the first model for the current
  71. * controller. If set to false 2d arrays will be allowed/expected.
  72. * 'alias' => the array key to output for a simple ul (not used if element or callback is specified)
  73. * 'type' => type of output defaults to ul
  74. * 'itemType => type of item output default to li
  75. * 'id' => id for top level 'type'
  76. * 'class' => class for top level 'type'
  77. * 'element' => path to an element to render to get node contents.
  78. * 'callback' => callback to use to get node contents. e.g. array(&$anObject, 'methodName') or 'floatingMethod'
  79. * 'autoPath' => array($left, $right [$classToAdd = 'active']) if set any item in the path will have the class $classToAdd added. MPTT only.
  80. * 'left' => name of the 'lft' field if not lft. only applies to MPTT data
  81. * 'right' => name of the 'rght' field if not lft. only applies to MPTT data
  82. * 'depth' => used internally when running recursively, can be used to override the depth in either mode.
  83. * 'firstChild' => used internally when running recursively.
  84. * 'splitDepth' => if multiple "parallel" types are required, instead of one big type, nominate the depth to do so here
  85. * 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
  86. * style/float them.
  87. * 'splitCount' => the number of "parallel" types. defaults to 3
  88. *
  89. * @param array $data data to loop on
  90. * @param array $settings
  91. * @return string html representation of the passed data
  92. * @access public
  93. */
  94. public function generate($data, $settings = array()) {
  95. $this->_settings = array_merge(array(
  96. 'model' => null,
  97. 'alias' => 'name',
  98. 'type' => 'ul',
  99. 'itemType' => 'li',
  100. 'id' => false,
  101. 'class' => false,
  102. 'element' => false,
  103. 'callback' => false,
  104. 'autoPath' => false,
  105. 'left' => 'lft',
  106. 'right' => 'rght',
  107. 'depth' => 0,
  108. 'firstChild' => true,
  109. 'indent' => null,
  110. 'splitDepth' => false,
  111. 'splitCount' => 3,
  112. ), (array )$settings);
  113. if ($this->_settings['autoPath'] && !isset($this->_settings['autoPath'][2])) {
  114. $this->_settings['autoPath'][2] = 'active';
  115. }
  116. extract($this->_settings);
  117. if ($indent === null && Configure::read('debug')) {
  118. $indent = true;
  119. }
  120. if ($model === null && $this->_View->params['models']) {
  121. foreach ($this->_View->params['models'] as $model => $value) {
  122. break;
  123. }
  124. }
  125. if ($model === null) {
  126. foreach ($data as $key => $value) {
  127. foreach ($value as $model => $array) {
  128. break;
  129. }
  130. }
  131. }
  132. if (!$model) {
  133. $model = '_NULL_';
  134. }
  135. $this->_settings['model'] = $model;
  136. $stack = array();
  137. if ($depth == 0) {
  138. if ($class) {
  139. $this->addTypeAttribute('class', $class, null, 'previous');
  140. }
  141. if ($id) {
  142. $this->addTypeAttribute('id', $id, null, 'previous');
  143. }
  144. }
  145. $return = '';
  146. $_addType = true;
  147. foreach ($data as $i => $result) {
  148. /* Allow 2d data arrays */
  149. if ($model === '_NULL_') {
  150. $_result = $result;
  151. $result[$model] = $_result;
  152. }
  153. /* BulletProof */
  154. if (!isset($result[$model][$left]) && !isset($result['children'])) {
  155. $result['children'] = array();
  156. }
  157. /* Close open items as appropriate */
  158. while ($stack && ($stack[count($stack) - 1] < $result[$model][$right])) {
  159. array_pop($stack);
  160. if ($indent) {
  161. $whiteSpace = str_repeat("\t", count($stack));
  162. $return .= "\r\n" . $whiteSpace . "\t";
  163. }
  164. if ($type) {
  165. $return .= '</' . $type . '>';
  166. }
  167. if ($itemType) {
  168. $return .= '</' . $itemType . '>';
  169. }
  170. }
  171. /* Some useful vars */
  172. $hasChildren = $firstChild = $lastChild = $hasVisibleChildren = false;
  173. $numberOfDirectChildren = $numberOfTotalChildren = null;
  174. if (isset($result['children'])) {
  175. if ($result['children']) {
  176. $hasChildren = $hasVisibleChildren = true;
  177. $numberOfDirectChildren = count($result['children']);
  178. }
  179. $prevRow = prev($data);
  180. if (!$prevRow) {
  181. $firstChild = true;
  182. }
  183. next($data);
  184. $nextRow = next($data);
  185. if (!$nextRow) {
  186. $lastChild = true;
  187. }
  188. prev($data);
  189. } elseif (isset($result[$model][$left])) {
  190. if ($result[$model][$left] != ($result[$model][$right] - 1)) {
  191. $hasChildren = true;
  192. $numberOfTotalChildren = ($result[$model][$right] - $result[$model][$left] - 1) / 2;
  193. if (isset($data[$i + 1]) && $data[$i + 1][$model][$right] < $result[$model][$right]) {
  194. $hasVisibleChildren = true;
  195. }
  196. }
  197. if (!isset($data[$i - 1]) || ($data[$i - 1][$model][$left] == ($result[$model][$left] - 1))) {
  198. $firstChild = true;
  199. }
  200. if (!isset($data[$i + 1]) || ($stack && $stack[count($stack) - 1] == ($result[$model][$right] + 1))) {
  201. $lastChild = true;
  202. }
  203. }
  204. $elementData = array(
  205. 'data' => $result,
  206. 'depth' => $depth ? $depth : count($stack),
  207. 'hasChildren' => $hasChildren,
  208. 'numberOfDirectChildren' => $numberOfDirectChildren,
  209. 'numberOfTotalChildren' => $numberOfTotalChildren,
  210. 'firstChild' => $firstChild,
  211. 'lastChild' => $lastChild,
  212. 'hasVisibleChildren' => $hasVisibleChildren);
  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 = $result[$model][$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[] = $result[$model][$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. * $this->Tree->addTypeAttribute('style', 'display', 'hidden');
  331. * // give top level type (1) a class
  332. * $this->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. */
  357. public function supressChildren() {
  358. }
  359. /**
  360. * suffix method
  361. *
  362. * Used to close and reopen a ul/ol to allow easier listings
  363. *
  364. * @return void
  365. */
  366. protected function _suffix() {
  367. static $_splitCount = 0;
  368. static $_splitCounter = 0;
  369. extract($this->_settings);
  370. if ($splitDepth) {
  371. if ($depth == $splitDepth - 1) {
  372. $total = $numberOfDirectChildren ? $numberOfDirectChildren : $numberOfTotalChildren;
  373. if ($total) {
  374. $_splitCounter = 0;
  375. $_splitCount = $total / $splitCount;
  376. $rounded = (int)$_splitCount;
  377. if ($rounded < $_splitCount) {
  378. $_splitCount = $rounded + 1;
  379. }
  380. }
  381. }
  382. if ($depth == $splitDepth) {
  383. $_splitCounter++;
  384. if ($type && ($_splitCounter % $_splitCount) === 0) {
  385. return '</' . $type . '><' . $type . '>';
  386. }
  387. }
  388. }
  389. return;
  390. }
  391. /**
  392. * attributes function
  393. *
  394. * Logic to apply styles to tags.
  395. *
  396. * @param mixed $rType
  397. * @param array $elementData
  398. * @return void
  399. */
  400. protected function _attributes($rType, $elementData = array(), $clear = true) {
  401. extract($this->_settings);
  402. if ($rType == $type) {
  403. $attributes = $this->_typeAttributes;
  404. if ($clear) {
  405. $this->_typeAttributes = $this->_typeAttributesNext;
  406. $this->_typeAttributesNext = array();
  407. }
  408. } else {
  409. $attributes = $this->_itemAttributes;
  410. $this->_itemAttributes = array();
  411. if ($clear) {
  412. $this->_itemAttributes = array();
  413. }
  414. }
  415. if ($autoPath && $depth) {
  416. if ($this->_settings['data'][$model][$left] < $autoPath[0] && $this->_settings['data'][$model][$right] > $autoPath[1]) {
  417. $attributes['class'][] = $autoPath[2];
  418. } elseif (isset($autoPath[3]) && $this->_settings['data'][$model][$left] == $autoPath[0]) {
  419. $attributes['class'][] = $autoPath[3];
  420. }
  421. }
  422. if ($attributes) {
  423. foreach ($attributes as $type => $values) {
  424. foreach ($values as $key => $val) {
  425. if (is_array($val)) {
  426. $attributes[$type][$key] = '';
  427. foreach ($val as $vKey => $v) {
  428. $attributes[$type][$key][$vKey] .= $vKey . ':' . $v;
  429. }
  430. $attributes[$type][$key] = implode(';', $attributes[$type][$key]);
  431. }
  432. if (is_string($key)) {
  433. $attributes[$type][$key] = $key . ':' . $val . ';';
  434. }
  435. }
  436. $attributes[$type] = $type . '="' . implode(' ', $attributes[$type]) . '"';
  437. }
  438. return ' ' . implode(' ', $attributes);
  439. }
  440. return '';
  441. }
  442. }