taxonomylist.php 2.4 KB

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