Skip to content

Commit

Permalink
throw exception in save() method instead of returning false
Browse files Browse the repository at this point in the history
  • Loading branch information
creme332 committed Jul 17, 2024
1 parent 59b40d8 commit 020af46
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
28 changes: 14 additions & 14 deletions src/models/Review.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,34 +217,34 @@ public function setCreatedDate(DateTime $created_date): void
/**
* Saves review to database if attributes are valid. review_id and created_date attributes
* are automatically set by database and any set values are ignored.
* The review_id of the current object is updated after a successful insertion.
* @return bool
* @throws Exception
*/
public function save(): bool
{
// If attributes of the object are invalid, exit
if (count($this->validate()) > 0) {
return false;
$validation_errors = $this->validate();
if (count($validation_errors) > 0) {
throw new Exception(json_encode($validation_errors));
}

// Get data to be inserted into the review table
$reviewData = $this->toArray();

// Remove review_id as it is auto-incremented in database
// let database handle review_id and creation date
unset($reviewData['review_id']);

unset($reviewData['created_date']); // let database handle creation date
unset($reviewData['created_date']);

// Perform insertion to the review table
try {
$inserted_id = $this->insert($reviewData, 'review');
if ($inserted_id === null) {
return false;
}
$this->review_id = $inserted_id;
return true;
} catch (Exception) {
return false;
$inserted_id = $this->insert($reviewData, 'review');

if ($inserted_id === null) {
throw new Exception("Insertion failed for some unknown reason");
}

$this->review_id = $inserted_id;
return true;
}

public function validate(): array
Expand Down
14 changes: 10 additions & 4 deletions tests/models/ReviewTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -270,11 +270,17 @@ public function testSave(string $text, int $rating, DateTime $created_date, arra
created_date: $created_date
);

// Attempt to save the review
$success = $review->save();

// If expectedErrors array is empty, the review should be saved successfully
$this->assertEquals(empty($expectedErrors), $success);
if (empty($expectedErrors)) {
$success = $review->save();
self::assertTrue($success);
} else {
try {
$review->save();
} catch (Exception $e) {
$this->assertEquals($e->getMessage(), json_encode($expectedErrors));
}
}
}

public function testGetNestedComments(): void
Expand Down

0 comments on commit 020af46

Please sign in to comment.