Skip to content

Commit

Permalink
A stake in the ground for model validation
Browse files Browse the repository at this point in the history
First we add a little validation to Event. In the final version we'll want to
hoover up all errors at once and display inline with the redisplayed form, but
this is better than a 500 from a DatabaseException for now.
  • Loading branch information
bakert committed Nov 11, 2024
1 parent 4eb4a55 commit 90c5a51
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
2 changes: 1 addition & 1 deletion gatherling/Exceptions/ValidationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ class ValidationException extends BadRequestException
{
public function getUserMessage(): string
{
return 'The request was invalid';
return $this->getMessage();
}
}
41 changes: 38 additions & 3 deletions gatherling/Models/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,42 @@ public static function createEvent(
return $event;
}

private function validate(): void
{
try {
strtotime($this->start);
} catch (DatetimeException $e) {
throw new ValidationException("Invalid start date {$this->start}");
}
try {
db()->int('SELECT 1 FROM formats WHERE name = :name', ['name' => $this->format]);
} catch (DatabaseException $e) {
throw new ValidationException("Invalid format {$this->format}");
}
try {
db()->int('SELECT 1 FROM players WHERE name = :name', ['name' => $this->host]);
} catch (DatabaseException $e) {
throw new ValidationException("Invalid host {$this->host}");
}
if ($this->cohost !== null) {
try {
db()->int('SELECT 1 FROM players WHERE name = :name', ['name' => $this->cohost]);
} catch (DatabaseException $e) {
throw new ValidationException("Invalid cohost {$this->cohost}");
}
}
try {
db()->int('SELECT 1 FROM series WHERE name = :name', ['name' => $this->series]);
} catch (DatabaseException $e) {
throw new ValidationException("Invalid series {$this->series}");
}
try {
db()->int('SELECT 1 FROM clients WHERE id = :id', ['id' => $this->client]);
} catch (DatabaseException $e) {
throw new ValidationException("Invalid client {$this->client}");
}
}

public function save(): void
{
if ($this->cohost == '') {
Expand All @@ -279,10 +315,9 @@ public function save(): void
$this->active = 0;
}

$this->validate();

if ($this->new) {
if (!$this->series) {
throw new ValidationException("Series is required for a new event");
}
$sql = '
INSERT INTO events (name, start, format, host, cohost, kvalue, number, season, series, threadurl, reporturl,
metaurl, prereg_allowed, finalized, player_reportable, prereg_cap, player_editdecks,
Expand Down

0 comments on commit 90c5a51

Please sign in to comment.