pathToRepository = $pathToRepository; $this->load(); } 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 find(string $id): ?Bookmark { return $this->repository[$id] ?? null; } public function add(Bookmark $bookmark): bool { $this->repository[] = $bookmark; return $this->save(); } public function update(Bookmark $bookmark): bool { if (array_key_exists($bookmark->id, $this->repository)) { $this->repository[$bookmark->id] = $bookmark; return $this->save(); } return false; } public function delete(Bookmark $bookmark): bool { if (array_key_exists($bookmark->id, $this->repository)) { unset($this->repository[$bookmark->id]); return $this->save(); } return false; } public function tags(): array { return $this->tags; } 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]); } private 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}"); } $id = 0; while (($data = fgetcsv($fp)) !== FALSE) { $bookmark = new Bookmark(); $bookmark->id = $id++; $bookmark->url = $data[0]; $bookmark->title = $data[1]; $bookmark->tag = $data[2]; $bookmark->addedAt = $data[3]; $this->repository[] = $bookmark; $this->tags[] = $bookmark->tag; } $this->tags = array_filter(array_unique($this->tags)); sort($this->tags); fclose($fp); } private function save(): bool { if (($fp = fopen($this->pathToRepository, 'w')) === FALSE) { throw new \Exception("Unable to open repository {$this->pathToRepository}"); } $success = true; foreach ($this->repository as $bookmark) { $success = $success && fputcsv($fp, [ $bookmark->url, $bookmark->title, $bookmark->tag, $bookmark->addedAt, ]) !== false; } fclose($fp); return $success; } }