TreeHelper.php 15 KB

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