From 411f03fb4643cdf7afd9ef1a3fcc2142ad86f1bf Mon Sep 17 00:00:00 2001 From: Camil Staps Date: Wed, 27 Jul 2016 17:28:46 +0200 Subject: Model: __set() cannot return a value, new exception instead --- classes/Model.php | 20 ++++++++++++++++---- include/clients-edit.php | 9 ++------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/classes/Model.php b/classes/Model.php index 3e99856..792027c 100644 --- a/classes/Model.php +++ b/classes/Model.php @@ -33,6 +33,12 @@ class ModelNotFoundException extends Exception { class ModelIllegalAccessException extends Exception { } +/** + * Thrown in Model when a call to __set() fails + */ +class ModelSetFailedException { +} + /** * An abstract interface to a database table */ @@ -82,17 +88,23 @@ abstract class Model { * @param mixed $value The value * * @throws PDOException Database error - * - * @return bool True iff the value has been changed */ public function __set($key, $value) { if (!in_array($key, $this->fillable_columns)) { throw new ModelIllegalAccessException("Column $key cannot be edited."); } + if ($this->data[$key] == $value) { + return; + } $stmt = $this->pdo->prepare("UPDATE `".$this->table()."` SET `$key`=? WHERE `{$this->primary_key}`=?"); - $stmt->execute([$this->mutator($value), $this->data[$this->primary_key]]); + $stmt->execute([ + $this->mutator($key, $value), + $this->data[$this->primary_key] + ]); + if ($stmt->rowCount() != 1) { + throw new ModelEditFailedException(); + } $this->data[$key] = $value; - return $this->rowCount() != 0; } /** diff --git a/include/clients-edit.php b/include/clients-edit.php index 00961aa..ded72d2 100644 --- a/include/clients-edit.php +++ b/include/clients-edit.php @@ -24,13 +24,8 @@ $response = new Response(); try { $client = new Client($_pdo, $_REQUEST['pk']); - if ($client->setName($_REQUEST['value'])) { - $response->success = true; - } else { - $response->http_response_code(500); - $response->success = false; - $response->message = "The client could not be edited due to an error."; - } + $client->name = $_REQUEST['value']; + $response->success = true; } catch (PDOException $e) { $response->http_response_code(500); $response->success = false; -- cgit v1.2.3