TreeHelper.php 16 KB

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