TreeHelper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. * @link www.ad7six.com
  17. * @package cake-base
  18. * @subpackage cake-base.app.views.helpers
  19. * @since v 1.0
  20. * @version $Revision: 205 $
  21. * @modifiedBy $LastChangedBy: ad7six $
  22. * @lastModified $Date: 2008-08-13 16:13:32 +0200 (Wed, 13 Aug 2008) $
  23. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  24. */
  25. App::uses('AppHelper', 'View/Helper');
  26. /**
  27. * Tree helper
  28. *
  29. * Helper to generate tree representations of MPTT or recursively nested data
  30. */
  31. class TreeHelper extends AppHelper {
  32. /**
  33. * settings property
  34. *
  35. * @var array
  36. * @access private
  37. */
  38. public $_settings = array();
  39. /**
  40. * typeAttributes property
  41. *
  42. * @var array
  43. * @access private
  44. */
  45. public $_typeAttributes = array();
  46. /**
  47. * typeAttributesNext property
  48. *
  49. * @var array
  50. * @access private
  51. */
  52. public $_typeAttributesNext = array();
  53. /**
  54. * itemAttributes property
  55. *
  56. * @var array
  57. * @access private
  58. */
  59. public $_itemAttributes = array();
  60. /**
  61. * helpers variable
  62. *
  63. * @var array
  64. * @access public
  65. */
  66. public $helpers = array('Html');
  67. /**
  68. * Tree generation method.
  69. *
  70. * Accepts the results of
  71. * find('all', array('fields' => array('lft', 'rght', 'whatever'), 'order' => 'lft ASC'));
  72. * children(); // if you have the tree behavior of course!
  73. * or findAllThreaded(); and generates a tree structure of the data.
  74. *
  75. * Settings (2nd parameter):
  76. * 'model' => name of the model (key) to look for in the data array. defaults to the first model for the current
  77. * controller. If set to false 2d arrays will be allowed/expected.
  78. * 'alias' => the array key to output for a simple ul (not used if element or callback is specified)
  79. * 'type' => type of output defaults to ul
  80. * 'itemType => type of item output default to li
  81. * 'id' => id for top level 'type'
  82. * 'class' => class for top level 'type'
  83. * 'element' => path to an element to render to get node contents.
  84. * 'callback' => callback to use to get node contents. e.g. array(&$anObject, 'methodName') or 'floatingMethod'
  85. * 'autoPath' => array($left, $right [$classToAdd = 'active']) if set any item in the path will have the class $classToAdd added. MPTT only.
  86. * 'left' => name of the 'lft' field if not lft. only applies to MPTT data
  87. * 'right' => name of the 'rght' field if not lft. only applies to MPTT data
  88. * 'depth' => used internally when running recursively, can be used to override the depth in either mode.
  89. * 'firstChild' => used internally when running recursively.
  90. * 'splitDepth' => if multiple "parallel" types are required, instead of one big type, nominate the depth to do so here
  91. * 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
  92. * style/float them.
  93. * 'splitCount' => the number of "parallel" types. defaults to 3
  94. *
  95. * @param array $data data to loop on
  96. * @param array $settings
  97. * @return string html representation of the passed data
  98. * @access public
  99. */
  100. public function generate($data, $settings = array()) {
  101. $this->_settings = array_merge(array(
  102. 'model' => null,
  103. 'alias' => 'name',
  104. 'type' => 'ul',
  105. 'itemType' => 'li',
  106. 'id' => false,
  107. 'class' => false,
  108. 'element' => false,
  109. 'callback' => false,
  110. 'autoPath' => false,
  111. 'left' => 'lft',
  112. 'right' => 'rght',
  113. 'depth' => 0,
  114. 'firstChild' => true,
  115. 'indent' => null,
  116. 'splitDepth' => false,
  117. 'splitCount' => 3,
  118. ), (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) {
  127. //$model = Inflector::classify($this->_View->params['models'][0]);
  128. }
  129. if (!$model) {
  130. $model = '_NULL_';
  131. }
  132. $stack = array();
  133. if ($depth == 0) {
  134. if ($class) {
  135. $this->addTypeAttribute('class', $class, null, 'previous');
  136. }
  137. if ($id) {
  138. $this->addTypeAttribute('id', $id, null, 'previous');
  139. }
  140. }
  141. $return = '';
  142. if ($indent) {
  143. $return = "\r\n";
  144. }
  145. $_addType = true;
  146. foreach ($data as $i => $result) {
  147. /* Allow 2d data arrays */
  148. if ($model == '_NULL_') {
  149. $_result = $result;
  150. $result[$model] = $_result;
  151. }
  152. /* BulletProof */
  153. if (!isset($result[$model][$left]) && !isset($result['children'])) {
  154. $result['children'] = array();
  155. }
  156. /* Close open items as appropriate */
  157. while ($stack && ($stack[count($stack) - 1] < $result[$model][$right])) {
  158. array_pop($stack);
  159. if ($indent) {
  160. $whiteSpace = str_repeat("\t", count($stack));
  161. $return .= "\r\n" . $whiteSpace . "\t";
  162. }
  163. if ($type) {
  164. $return .= '</' . $type . '>';
  165. }
  166. if ($itemType) {
  167. $return .= '</' . $itemType . '>';
  168. }
  169. }
  170. /* Some useful vars */
  171. $hasChildren = $firstChild = $lastChild = $hasVisibleChildren = false;
  172. $numberOfDirectChildren = $numberOfTotalChildren = null;
  173. if (isset($result['children'])) {
  174. if ($result['children']) {
  175. $hasChildren = $hasVisibleChildren = true;
  176. $numberOfDirectChildren = count($result['children']);
  177. }
  178. $prevRow = prev($data);
  179. if (!$prevRow) {
  180. $firstChild = true;
  181. }
  182. next($data);
  183. $nextRow = next($data);
  184. if (!$nextRow) {
  185. $lastChild = true;
  186. }
  187. prev($data);
  188. } elseif (isset($result[$model][$left])) {
  189. if ($result[$model][$left] != ($result[$model][$right] - 1)) {
  190. $hasChildren = true;
  191. $numberOfTotalChildren = ($result[$model][$right] - $result[$model][$left] - 1) / 2;
  192. if (isset($data[$i + 1]) && $data[$i + 1][$model][$right] < $result[$model][$right]) {
  193. $hasVisibleChildren = true;
  194. }
  195. }
  196. if (!isset($data[$i - 1]) || ($data[$i - 1][$model][$left] == ($result[$model][$left] - 1))) {
  197. $firstChild = true;
  198. }
  199. if (!isset($data[$i + 1]) || ($stack && $stack[count($stack) - 1] == ($result[$model][$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. $this->_settings = array_merge($this->_settings, $elementData);
  213. /* Main Content */
  214. if ($element) {
  215. $content = $this->_View->element($element, $elementData);
  216. } elseif ($callback) {
  217. list($content) = array_map($callback, array($elementData));
  218. } else {
  219. $content = $result[$model][$alias];
  220. }
  221. if (!$content) {
  222. continue;
  223. }
  224. $whiteSpace = str_repeat("\t", $depth);
  225. if ($indent && strpos($content, "\r\n", 1)) {
  226. $content = str_replace("\r\n", "\n" . $whiteSpace . "\t", $content);
  227. }
  228. /* Prefix */
  229. if ($_addType) {
  230. if ($indent) {
  231. $return .= "\r\n" . $whiteSpace;
  232. }
  233. if ($type) {
  234. $typeAttributes = $this->_attributes($type, array('data' => $elementData));
  235. $return .= '<' . $type . $typeAttributes . '>';
  236. }
  237. }
  238. if ($indent) {
  239. $return .= "\r\n" . $whiteSpace . "\t";
  240. }
  241. if ($itemType) {
  242. $itemAttributes = $this->_attributes($itemType, $elementData);
  243. $return .= '<' . $itemType . $itemAttributes . '>';
  244. }
  245. $return .= $content;
  246. /* Suffix */
  247. $_addType = false;
  248. if ($hasVisibleChildren) {
  249. if ($numberOfDirectChildren) {
  250. $settings['depth'] = $depth + 1;
  251. $return .= $this->_suffix();
  252. $return .= $this->generate($result['children'], $settings);
  253. if ($itemType) {
  254. $return .= '</' . $itemType . '>';
  255. }
  256. } elseif ($numberOfTotalChildren) {
  257. $_addType = true;
  258. $stack[] = $result[$model][$right];
  259. }
  260. } else {
  261. if ($itemType) {
  262. $return .= '</' . $itemType . '>';
  263. }
  264. $return .= $this->_suffix();
  265. }
  266. }
  267. /* Cleanup */
  268. while ($stack) {
  269. array_pop($stack);
  270. if ($indent) {
  271. $whiteSpace = str_repeat("\t", count($stack));
  272. $return .= "\r\n" . $whiteSpace . "\t";
  273. }
  274. if ($type) {
  275. $return .= '</' . $type . '>';
  276. }
  277. if ($itemType) {
  278. $return .= '</' . $itemType . '>';
  279. }
  280. }
  281. if ($indent) {
  282. $return .= "\r\n";
  283. }
  284. if ($type) {
  285. $return .= '</' . $type . '>';
  286. if ($indent) {
  287. $return .= "\r\n";
  288. }
  289. }
  290. return $return;
  291. }
  292. /**
  293. * addItemAttribute function
  294. *
  295. * Called to modify the attributes of the next <item> to be processed
  296. * Note that the content of a 'node' is processed before generating its wrapping <item> tag
  297. *
  298. * @param string $id
  299. * @param string $key
  300. * @param mixed $value
  301. * @access public
  302. * @return void
  303. */
  304. public function addItemAttribute($id = '', $key = '', $value = null) {
  305. if (!is_null($value)) {
  306. $this->_itemAttributes[$id][$key] = $value;
  307. } elseif (!(isset($this->_itemAttributes[$id]) && in_array($key, $this->_itemAttributes[$id]))) {
  308. $this->_itemAttributes[$id][] = $key;
  309. }
  310. }
  311. /**
  312. * addTypeAttribute function
  313. *
  314. * Called to modify the attributes of the next <type> to be processed
  315. * Note that the content of a 'node' is processed before generating its wrapping <type> tag (if appropriate)
  316. * An 'interesting' case is that of a first child with children. To generate the output
  317. * <ul> (1)
  318. * <li>XYZ (3)
  319. * <ul> (2)
  320. * <li>ABC...
  321. * ...
  322. * </ul>
  323. * ...
  324. * The processing order is indicated by the numbers in brackets.
  325. * attributes are allways applied to the next type (2) to be generated
  326. * to set properties of the holding type - pass 'previous' for the 4th param
  327. * i.e.
  328. * // Hide children (2)
  329. * $this->Tree->addTypeAttribute('style', 'display', 'hidden');
  330. * // give top level type (1) a class
  331. * $this->Tree->addTypeAttribute('class', 'hasHiddenGrandChildren', null, 'previous');
  332. *
  333. * @param string $id
  334. * @param string $key
  335. * @param mixed $value
  336. * @access public
  337. * @return void
  338. */
  339. public function addTypeAttribute($id = '', $key = '', $value = null, $previousOrNext = 'next') {
  340. $var = '__typeAttributes';
  341. $firstChild = isset($this->_settings['firstChild']) ? $this->_settings['firstChild'] : true;
  342. if ($previousOrNext == 'next' && $firstChild) {
  343. $var = '__typeAttributesNext';
  344. }
  345. if (!is_null($value)) {
  346. $this->{$var}[$id][$key] = $value;
  347. } elseif (!(isset($this->{$var}[$id]) && in_array($key, $this->{$var}[$id]))) {
  348. $this->{$var}[$id][] = $key;
  349. }
  350. }
  351. /**
  352. * supressChildren method
  353. *
  354. * @return void
  355. * @access public
  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. * @access private
  365. * @return void
  366. */
  367. public function _suffix() {
  368. static $_splitCount = 0;
  369. static $_splitCounter = 0;
  370. extract($this->_settings);
  371. if ($splitDepth) {
  372. if ($depth == $splitDepth - 1) {
  373. $total = $numberOfDirectChildren ? $numberOfDirectChildren : $numberOfTotalChildren;
  374. if ($total) {
  375. $_splitCounter = 0;
  376. $_splitCount = $total / $splitCount;
  377. $rounded = (int)$_splitCount;
  378. if ($rounded < $_splitCount) {
  379. $_splitCount = $rounded + 1;
  380. }
  381. }
  382. }
  383. if ($depth == $splitDepth) {
  384. $_splitCounter++;
  385. if ($type && ($_splitCounter % $_splitCount) == 0) {
  386. return '</' . $type . '><' . $type . '>';
  387. }
  388. }
  389. }
  390. return;
  391. }
  392. /**
  393. * attributes function
  394. *
  395. * Logic to apply styles to tags.
  396. *
  397. * @param mixed $rType
  398. * @param array $elementData
  399. * @access private
  400. * @return void
  401. */
  402. public function _attributes($rType, $elementData = array(), $clear = true) {
  403. extract($this->_settings);
  404. if ($rType == $type) {
  405. $attributes = $this->_typeAttributes;
  406. if ($clear) {
  407. $this->_typeAttributes = $this->_typeAttributesNext;
  408. $this->_typeAttributesNext = array();
  409. }
  410. } else {
  411. $attributes = $this->_itemAttributes;
  412. $this->_itemAttributes = array();
  413. if ($clear) {
  414. $this->_itemAttributes = array();
  415. }
  416. }
  417. if ($autoPath && $depth) {
  418. if ($this->_settings['data'][$model][$left] < $autoPath[0] && $this->_settings['data'][$model][$right] > $autoPath[1]) {
  419. $attributes['class'][] = $autoPath[2];
  420. } elseif (isset($autoPath[3]) && $this->_settings['data'][$model][$left] == $autoPath[0]) {
  421. $attributes['class'][] = $autoPath[3];
  422. }
  423. }
  424. if ($attributes) {
  425. foreach ($attributes as $type => $values) {
  426. foreach ($values as $key => $val) {
  427. if (is_array($val)) {
  428. $attributes[$type][$key] = '';
  429. foreach ($val as $vKey => $v) {
  430. $attributes[$type][$key][$vKey] .= $vKey . ':' . $v;
  431. }
  432. $attributes[$type][$key] = implode(';', $attributes[$type][$key]);
  433. }
  434. if (is_string($key)) {
  435. $attributes[$type][$key] = $key . ':' . $val . ';';
  436. }
  437. }
  438. $attributes[$type] = $type . '="' . implode(' ', $attributes[$type]) . '"';
  439. }
  440. return ' ' . implode(' ', $attributes);
  441. }
  442. return '';
  443. }
  444. }