TreeNotes.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. declare(strict_types = 1);
  3. // {{{ License
  4. // This file is part of GNU social - https://www.gnu.org/software/social
  5. //
  6. // GNU social is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // GNU social is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  18. // }}}
  19. namespace Plugin\TreeNotes;
  20. use App\Core\Modules\Plugin;
  21. use App\Entity\Note;
  22. class TreeNotes extends Plugin
  23. {
  24. /**
  25. * Format the given $notes_in_trees_out in a list of reply trees
  26. */
  27. public function onFormatNoteList(array $notes_in, ?array &$notes_out)
  28. {
  29. $roots = array_filter($notes_in, static fn (Note $note) => is_null($note->getReplyTo()));
  30. $notes_out = $this->build_tree($roots, $notes_in);
  31. }
  32. private function build_tree(array $parents, array $notes)
  33. {
  34. $subtree = [];
  35. foreach ($parents as $p) {
  36. $subtree[] = $this->build_subtree($p, $notes);
  37. }
  38. return $subtree;
  39. }
  40. private function build_subtree(Note $parent, array $notes)
  41. {
  42. $children = array_filter($notes, fn (Note $note) => $note->getReplyTo() === $parent->getId());
  43. return ['note' => $parent, 'replies' => $this->build_tree($children, $notes)];
  44. }
  45. }