TreeHelper.php 17 KB

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