chore: Compartimentalize AnkiService a little into different functions

This commit is contained in:
Dendy 2025-02-06 15:09:14 +09:00
parent 4d58b2d299
commit ea472e6afb
1 changed files with 26 additions and 8 deletions

View File

@ -13,7 +13,7 @@ class AnkiService
private function request(string $action, array $params): mixed private function request(string $action, array $params): mixed
{ {
$res = $this->client->request( ['error' => $error, 'result' => $result] = $this->client->request(
'POST', 'POST',
'http://localhost:8765', 'http://localhost:8765',
['json' => [ ['json' => [
@ -23,19 +23,37 @@ class AnkiService
]] ]]
)->toArray(); )->toArray();
throw new \Exception('AnkiConnect returned error: ' . $res['error']); if ($error != null) {
throw new \Exception('AnkiConnect returned error: ' . $error);
}
return $res['result']; return $result;
} }
public function getLatestNote(): Note public function getAllNoteIds(): array
{ {
$latestId = max($this->request( return $this->request(
'findNotes', 'findNotes',
['aquery' => 'added:1 "note:Japanese sentences"'] ['query' => '"note:Japanese sentences"']
)); );
}
$noteInfo = $this->request('notesInfo', ['notes' => [$latestId]])[0]; public function getNotesInfo(array $noteIds): array
{
return $this->request('notesInfo', ['notes' => $noteIds]);
}
public function getNoteInfo(int $noteId): array
{
return $this->getNotesInfo([$noteId])[0];
}
public function getLatestNote(): ?Note
{
// NoteIDs are just timestamps in milliseconds, so the latest is just
// the biggest numerically
$latestId = max($this->getAllNoteIds());
$noteInfo = $this->getNoteInfo($latestId);
return Note::fromAnki($noteInfo); return Note::fromAnki($noteInfo);
} }