diff options
Diffstat (limited to 'src/DTS/BookmarkRepository.php')
| -rw-r--r-- | src/DTS/BookmarkRepository.php | 69 |
1 files changed, 56 insertions, 13 deletions
diff --git a/src/DTS/BookmarkRepository.php b/src/DTS/BookmarkRepository.php index ab54594..d673338 100644 --- a/src/DTS/BookmarkRepository.php +++ b/src/DTS/BookmarkRepository.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace DTS; +use DTS\Bookmark; + class BookmarkRepository implements \Iterator { private string $pathToRepository; @@ -61,24 +63,32 @@ class BookmarkRepository implements \Iterator return $this; } + public function find(string $id): ?Bookmark + { + $index = $this->findBookmarkIndex($id); + + return $this->repository[$index] ?? null; + } + public function add(Bookmark $bookmark): bool { - if (($fp = fopen($this->pathToRepository, 'a')) === FALSE) { - throw new \Exception("Unable to open repository {$this->pathToRepository}"); - } + $this->repository[] = $bookmark; - $saved = fputcsv($fp, [ - $bookmark->id, - $bookmark->url, - $bookmark->title, - $bookmark->tag, - $bookmark->addedAt, - (int)$bookmark->unread, - ]); + return $this->store(); + } - fclose($fp); + public function update(Bookmark $bookmark): bool + { + $index = $this->findBookmarkIndex($bookmark->id); + + if ($index !== null) { + $this->repository[$index] = $bookmark; + print_r($bookmark); - return $saved !== false; + return $this->store(); + } + + return false; } public function current(): mixed @@ -105,4 +115,37 @@ class BookmarkRepository implements \Iterator { return isset($this->repository[$this->position]); } + + private function findBookmarkIndex(string $id): ?int + { + foreach ($this->repository as $index => $bookmark) { + if ($bookmark->id == $id) { + return $index; + } + } + + return null; + } + + public function store(): bool + { + if (($fp = fopen($this->pathToRepository, 'w')) === FALSE) { + throw new \Exception("Unable to open repository {$this->pathToRepository}"); + } + + foreach ($this->repository as $bookmark) { + fputcsv($fp, [ + $bookmark->id, + $bookmark->url, + $bookmark->title, + $bookmark->tag, + $bookmark->addedAt, + (int)$bookmark->unread, + ]); + } + + fclose($fp); + + return true; + } } |
