taxonomylist.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Grav\Plugin;
  3. use Grav\Common\Cache;
  4. use Grav\Common\Grav;
  5. use Grav\Common\Page\Interfaces\PageInterface;
  6. class Taxonomylist
  7. {
  8. /**
  9. * @var array
  10. */
  11. protected $taxonomylist;
  12. /**
  13. * Get taxonomy list with all tags of the site.
  14. *
  15. * @return array
  16. */
  17. public function get()
  18. {
  19. if (null === $this->taxonomylist) {
  20. $this->taxonomylist = $this->build(Grav::instance()['taxonomy']->taxonomy());
  21. }
  22. return $this->taxonomylist;
  23. }
  24. /**
  25. * Get taxonomy list with only tags of the child pages.
  26. *
  27. * @return array
  28. */
  29. public function getChildPagesTags()
  30. {
  31. /** @var PageInterface $current */
  32. $current = Grav::instance()['page'];
  33. $taxonomies = [];
  34. foreach ($current->children()->published() as $child) {
  35. if (!$child->isPage()) {
  36. continue;
  37. }
  38. foreach($this->build($child->taxonomy()) as $taxonomyName => $taxonomyValue) {
  39. if (!isset($taxonomies[$taxonomyName])) {
  40. $taxonomies[$taxonomyName] = $taxonomyValue;
  41. } else {
  42. foreach ($taxonomyValue as $value => $count) {
  43. if (!isset($taxonomies[$taxonomyName][$value])) {
  44. $taxonomies[$taxonomyName][$value] = $count;
  45. } else {
  46. $taxonomies[$taxonomyName][$value] += $count;
  47. }
  48. }
  49. }
  50. }
  51. }
  52. return $taxonomies;
  53. }
  54. /**
  55. * @internal
  56. * @param array $taxonomylist
  57. * @return array
  58. */
  59. protected function build(array $taxonomylist)
  60. {
  61. /** @var Cache $cache */
  62. $cache = Grav::instance()['cache'];
  63. $hash = hash('md5', serialize($taxonomylist));
  64. $list = [];
  65. if ($taxonomy = $cache->fetch($hash)) {
  66. return $taxonomy;
  67. }
  68. foreach ($taxonomylist as $taxonomyName => $taxonomyValue) {
  69. $partial = [];
  70. foreach ($taxonomyValue as $key => $value) {
  71. if (is_array($value)) {
  72. $key = (string)$key;
  73. $taxonomyValue[$key] = count($value);
  74. $partial[$key] = count($value);
  75. } else {
  76. $partial[(string)$value] = 1;
  77. }
  78. }
  79. arsort($partial);
  80. $list[$taxonomyName] = $partial;
  81. }
  82. $cache->save($hash, $list);
  83. return $list;
  84. }
  85. }