diff options
Diffstat (limited to 'classes/Model.php')
-rw-r--r-- | classes/Model.php | 36 |
1 files changed, 28 insertions, 8 deletions
diff --git a/classes/Model.php b/classes/Model.php index 6ee7821..3b1c49e 100644 --- a/classes/Model.php +++ b/classes/Model.php @@ -45,15 +45,21 @@ class ModelSetFailedException extends Exception { abstract class Model { /** * @var string $table The database table + * @var string $primary_key The table's primary key * @var string[] $protected_columns Columns that cannot be edited * @var string[] $fillable_columns Columns that can be edited - * @var string $primary_key The table's primary key + * @var string[] $timestamps Columns that are TIMESTAMPs (special treatment in accessor and mutator) + * @var string[] $dates Columns that are DATEs (special treatment in accessor and mutator) + * @var string[] $booleans Columns that are BOOLEANs (special treatment in accessor and mutator) */ public $table = '', + $primary_key = 'id', $protected_columns = ['id'], $fillable_columns = [], - $primary_key = 'id'; + $timestamps = [], + $dates = [], + $booleans = []; /** * @var PDO $pdo A PDO instance for database communication @@ -91,7 +97,7 @@ abstract class Model { */ public function __set($key, $value) { if (!in_array($key, $this->fillable_columns)) { - throw new ModelIllegalAccessException("Column $key cannot be edited."); + throw new ModelIllegalAccessException("Column `{$this->table()}`.`$key` cannot be edited."); } if ($this->data[$key] == $value) { return; @@ -102,7 +108,7 @@ abstract class Model { $this->data[$this->primary_key] ]); if ($stmt->rowCount() != 1) { - throw new ModelEditFailedException(); + throw new ModelEditFailedException("Failed to update `{$this->table()}`.`$key` to '$value'."); } $this->data[$key] = $value; } @@ -124,10 +130,18 @@ abstract class Model { * @param string $key The column * @param string $value The value * - * @return mixed The modified value (default: $value) + * @return mixed The modified value */ protected function accessor($key, $value) { - return $value; + if (is_null($value)) { + return null; + } elseif (in_array($key, $this->booleans)) { + return (bool) $value; + } elseif (in_array($key, $this->dates) || in_array($key, $this->timestamps)) { + return strtotime($value); + } else { + return $value; + } } /** @@ -136,10 +150,16 @@ abstract class Model { * @param string $key The column * @param mixed $value The value * - * @return string The modified value (default: $value casted to string) + * @return string The modified value */ protected function mutator($key, $value) { - return (string) $value; + if (in_array($key, $this->dates) && is_int($value)) { + return date('Y-m-d', $value); + } elseif (in_array($key, $this->timestamps) && is_int($value)) { + return date('Y-m-d H:i:s', $value); + } else { + return (string) $value; + } } /** |