TreeHelper.php 16 KB

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