123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- declare(strict_types = 1);
- namespace Plugin\TreeNotes;
- use App\Core\Modules\Plugin;
- use App\Entity\Note;
- use Symfony\Component\HttpFoundation\Request;
- class TreeNotes extends Plugin
- {
-
- public function onFormatNoteList(array $notes_in, array &$notes_out, Request $request)
- {
- if (str_starts_with($request->get('_route'), 'conversation')) {
- $parents = $this->conversationFormat($notes_in);
- $notes_out = $this->conversationFormatTree($parents, $notes_in);
- } else {
- $notes_out = $this->feedFormatTree($notes_in);
- }
- }
-
- private function feedFormatTree(array $notes): array
- {
- $tree = [];
- $notes = array_reverse($notes);
- foreach ($notes as $note) {
- if (!\is_null($children = $note->getReplies())) {
- $notes = array_filter($notes, fn (Note $n) => !\in_array($n, $children));
- $tree[] = [
- 'note' => $note,
- 'replies' => array_map(
- fn ($n) => ['note' => $n, 'replies' => []],
- $children,
- ),
- ];
- } else {
- $tree[] = ['note' => $note, 'replies' => []];
- }
- }
- return array_reverse($tree);
- }
-
- private function conversationFormat(array $notes_in): array
- {
- return array_filter($notes_in, static fn (Note $note) => \is_null($note->getReplyTo()));
- }
- private function conversationFormatTree(array $parents, array $notes): array
- {
- $subtree = [];
- foreach ($parents as $p) {
- $subtree[] = $this->conversationFormatSubTree($p, $notes);
- }
- return $subtree;
- }
- private function conversationFormatSubTree(Note $parent, array $notes)
- {
- $children = array_filter($notes, fn (Note $note) => $note->getReplyTo() === $parent->getId());
- return ['note' => $parent, 'replies' => $this->conversationFormatTree($children, $notes)];
- }
- }
|