1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
<?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], // Title.
$data[3], // Tag.
$data[4], // 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 add(Bookmark $bookmark): bool
{
if (($fp = fopen($this->pathToRepository, 'a')) === FALSE) {
throw new \Exception("Unable to open repository {$this->pathToRepository}");
}
$saved = fputcsv($fp, [
$bookmark->id,
$bookmark->url,
$bookmark->title,
$bookmark->tag,
$bookmark->addedAt,
(int)$bookmark->unread,
]);
fclose($fp);
return $saved !== false;
}
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]);
}
}
|