Skip to content

Commit

Permalink
task: improve mail service error handling (#454)
Browse files Browse the repository at this point in the history
* MailService: throw exception of database can't be resettet
* MailService: add own function for loading and saving the database
* MailService: validate database path
  • Loading branch information
andi34 authored Nov 11, 2023
1 parent 48f45e2 commit 9824068
Showing 1 changed file with 40 additions and 6 deletions.
46 changes: 40 additions & 6 deletions src/Service/MailService.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,60 @@ class MailService

public function __construct(string $databaseFile)
{
if (!$this->isValidDatabasePath($databaseFile)) {
throw new \Exception('Database or path is not writable: ' . $databaseFile);
}
$this->databaseFile = $databaseFile;
}

public function addRecipientToDatabase(string $recipient): void
private function isValidDatabasePath(string $path): bool
{
if (!file_exists($this->databaseFile)) {
$addresses = [];
if (is_file($path)) {
return is_writable($path);
} else {
return is_writable(dirname($path));
}
}

private function loadDatabase(): array
{
if (is_file($this->databaseFile)) {
$data = file_get_contents($this->databaseFile);
$addresses = json_decode($data, true);
if ($addresses === null) {
throw new \Exception('Failed to decode the database ' . $this->databaseFile);
}
} else {
$addresses = json_decode(file_get_contents($this->databaseFile));
$addresses = [];
}

return $addresses;
}

public function addRecipientToDatabase(string $recipient): void
{
$addresses = $this->loadDatabase();

if (!in_array($recipient, $addresses)) {
$addresses[] = $recipient;
$this->saveDatabase($addresses);
}
}

private function saveDatabase(array $addresses): void
{
$data = json_encode($addresses);
if (file_put_contents($this->databaseFile, $data) === false) {
throw new \Exception('Failed to save the database ' . $this->databaseFile);
}
file_put_contents($this->databaseFile, json_encode($addresses));
}

public function resetDatabase(): void
{
if (is_file($this->databaseFile)) {
unlink($this->databaseFile);
if (!unlink($this->databaseFile)) {
throw new \Exception('Failed to reset the database ' . $this->databaseFile);
}
}
}

Expand Down

0 comments on commit 9824068

Please sign in to comment.