|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Abrouter\RelatedUsers\Collections; |
| 6 | + |
| 7 | +class RelatedUsersCollection |
| 8 | +{ |
| 9 | + private array $relatedUsers; |
| 10 | + |
| 11 | + public function __construct(array $initial = []) |
| 12 | + { |
| 13 | + $this->relatedUsers = $initial; |
| 14 | + } |
| 15 | + |
| 16 | + public function append(string $userId, string $relatedUserId): self |
| 17 | + { |
| 18 | + $this->appendTo($userId, $relatedUserId); |
| 19 | + $this->handleChilds($userId, $relatedUserId); |
| 20 | + |
| 21 | + //updating child's |
| 22 | + foreach ($this->relatedUsers as $key => $childs) { |
| 23 | + foreach ($childs as $child) { |
| 24 | + $this->handleChilds($key, $child); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + return $this; |
| 29 | + } |
| 30 | + |
| 31 | + private function handleChilds(string $userId, string $relatedUserId): void |
| 32 | + { |
| 33 | + foreach ($this->relatedUsers[$userId] as $childId) { |
| 34 | + $this->appendTo($childId, $userId); |
| 35 | + $this->appendTo($childId, $relatedUserId); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private function appendTo(string $userId, $relatedUserId): void |
| 40 | + { |
| 41 | + if ($userId === $relatedUserId) { |
| 42 | + return ; |
| 43 | + } |
| 44 | + |
| 45 | + if (!isset($this->relatedUsers[$relatedUserId])) { |
| 46 | + $this->relatedUsers[$relatedUserId] = [$userId]; |
| 47 | + } else { |
| 48 | + $this->relatedUsers[$relatedUserId][] = $userId; |
| 49 | + $this->relatedUsers[$relatedUserId] = array_unique($this->relatedUsers[$relatedUserId]); |
| 50 | + } |
| 51 | + |
| 52 | + if (!isset($this->relatedUsers[$userId])) { |
| 53 | + $this->relatedUsers[$userId] = [$relatedUserId]; |
| 54 | + } else { |
| 55 | + $this->relatedUsers[$userId][] = $relatedUserId; |
| 56 | + $this->relatedUsers[$userId] = array_unique($this->relatedUsers[$userId]); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + public function getByUserId(string $userId): ?array |
| 61 | + { |
| 62 | + return $this->relatedUsers[$userId] ?? null; |
| 63 | + } |
| 64 | + |
| 65 | + public function getAll(): array |
| 66 | + { |
| 67 | + return $this->relatedUsers; |
| 68 | + } |
| 69 | +} |
0 commit comments