diff options
Diffstat (limited to 'src/DTS/BookmarkRepository.php')
| -rw-r--r-- | src/DTS/BookmarkRepository.php | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/src/DTS/BookmarkRepository.php b/src/DTS/BookmarkRepository.php new file mode 100644 index 0000000..deb188c --- /dev/null +++ b/src/DTS/BookmarkRepository.php @@ -0,0 +1,87 @@ +<?php + +declare(strict_types=1); + +namespace DTS; + +class BookmarkRepository implements \Iterator +{ + private string $pathToRepository; + + private array $repository = []; + + private int $position = 0; + + function __construct(string $pathToRepository) + { + $this->pathToRepository = $pathToRepository; + } + + public function load(): void + { + if (!is_file($this->pathToRepository) || !is_readable($this->pathToRepository)) { + throw new \Exception("Unable to locate repository {$this->pathToRepository}"); + } + + if (($fp = fopen($this->pathToRepository, 'r')) === FALSE) { + throw new \Exception("Unable to read from repository {$this->pathToRepository}"); + } + + while (($data = fgetcsv($fp)) !== FALSE) { + $this->repository[] = new Bookmark( + $data[0], // Id. + $data[1], // Url. + $data[2], // Tag. + $data[3], // Added At. + (bool)$data[4], // Read. + ); + } + + fclose($fp); + } + + public function sort(bool $asc = true): BookmarkRepository + { + usort($this->repository, function ($a, $b) use ($asc) { + return $asc ? $a->addedAt <=> $b->addedAt + : $b->addedAt <=> $a->addedAt; + }); + + return $this; + } + + public function filter(string $tag): BookmarkRepository + { + $this->repository = array_filter( + $this->repository, + fn($bookmark) => $bookmark->tag === $tag + ); + + return $this; + } + + public function current(): mixed + { + return $this->repository[$this->position]; + } + + public function key(): mixed + { + return $this->position; + } + + public function next(): void + { + ++$this->position; + } + + public function rewind(): void + { + $this->position = 0; + } + + public function valid(): bool + { + return isset($this->repository[$this->position]); + } +} |
