From 923aac957cc28723c622570d46d2a915c75df06f Mon Sep 17 00:00:00 2001 From: Camil Staps Date: Mon, 1 Aug 2016 09:15:36 +0200 Subject: Removed duplicate code --- classes/Assignment.php | 2 +- classes/BusinessAdmin.php | 97 ----------------------------------------------- classes/Client.php | 2 +- classes/Contact.php | 4 +- classes/Discount.php | 2 +- classes/File.php | 23 ++++++++++- classes/Mail.php | 2 +- classes/Mailer.php | 2 +- classes/Model.php | 65 ++++++++++++++++++++++--------- classes/Offer.php | 4 +- classes/Payment.php | 2 +- classes/User.php | 4 +- 12 files changed, 81 insertions(+), 128 deletions(-) (limited to 'classes') diff --git a/classes/Assignment.php b/classes/Assignment.php index af689fb..39850af 100644 --- a/classes/Assignment.php +++ b/classes/Assignment.php @@ -28,7 +28,7 @@ class Assignment extends OfferItem { use StandardCalculatable; /** {@inheritDoc} */ - public + public static $table = 'assignment', $fillable_columns = ['offerId', 'title', 'description', 'hours', 'price_per_hour', 'VAT_percentage']; diff --git a/classes/BusinessAdmin.php b/classes/BusinessAdmin.php index 1ea02ae..f6abe14 100644 --- a/classes/BusinessAdmin.php +++ b/classes/BusinessAdmin.php @@ -331,103 +331,6 @@ class BusinessAdmin { // Other functions //------------------------------------------------------------------------------ - /** - * Create a new client - * - * @param PDO $pdo The database connection - * @param string $name The name for the new client - * - * @throws PDOException If something went wrong with the database - * - * @return client|bool A new instance of the client object, or false on failure - */ - public static function createClient($pdo, $name) { - $stmt = $pdo->prepare("INSERT INTO `".Constants::db_prefix."client` (`name`) VALUES (?)"); - $stmt->execute(array($name)); - if ($stmt->rowCount() == 1) { - return new Client($pdo, $pdo->lastInsertId()); - } else { - return false; - } - } - - /** - * Create a new file - * - * @param PDO $pdo The database connection - * @param string $filename The desired filename - * - * @throws PDOException If something went wrong with the database - * @throws Exception If the file could not be created (due to permissions, file existed already, etc.), or the database record couldn't be added - * - * @return file A new instance of the file object - */ - public static function createFile($pdo, $filename) { - // Check for file existence - if (file_exists(Constants::files_folder . $filename)) { - throw new Exception("$filename already exists."); - } - - // Try to create the file - if (file_put_contents(Constants::files_folder . $filename, '') === false) { - throw new Exception("$filename could not be created. Check the permissions."); - } - - $stmt = $pdo->prepare("INSERT INTO `".Constants::db_prefix."file` (`filename`) VALUES (?)"); - $stmt->execute(array($filename)); - if ($stmt->rowCount() == 1) { - $file = new File($pdo, $pdo->lastInsertId()); - $file->secret_key = File::getRandomSecretKey(); - return $file; - } else { - unlink(Constants::files_folder . $filename); - throw new Exception("$filename could not be added to the database"); - } - } - - /** - * Create a new user - * - * @param PDO $pdo The database connection - * @param string $username The username for the new user - * @param string $password The password for the new user - * - * @throws PDOException If something went wrong with the database - * - * @return user|bool A new instance of the user object, or false on failure - */ - public static function createUser($pdo, $username, $password) { - $stmt = $pdo->prepare("INSERT INTO `".Constants::db_prefix."user` (`username`, `password`) VALUES (?,?)"); - $stmt->execute([$username, user::hash($password)]); - if ($stmt->rowCount() == 1) { - return new User($pdo, $pdo->lastInsertId()); - } else { - return false; - } - } - - /** - * Create a new mail - * - * @param PDO $pdo The database connection - * @param int $contactId The contactId for the new mail - * @param int $offerId The offerId for the new mail - * @param string $subject - * - * @throws PDOException If something went wrong with the database - * - * @return Mail|bool A new instance of the Mail class, or false on failure - */ - public static function createMail($pdo, $contactId, $offerId, $subject) { - $stmt = $pdo->prepare("INSERT INTO `".Constants::db_prefix."mail` (`contactId`, `offerId`, `subject`) VALUES (?,?,?)"); - $stmt->execute([$contactId, $offerId, $subject]); - if ($stmt->rowCount() == 1) { - return new Mail($pdo, $pdo->lastInsertId()); - } else { - return false; - } - } - /** * Format a date nicely * diff --git a/classes/Client.php b/classes/Client.php index 7c9cd1e..acae192 100644 --- a/classes/Client.php +++ b/classes/Client.php @@ -26,7 +26,7 @@ */ class Client extends Model { /** {@inheritDoc} */ - public + public static $table = 'client', $fillable_columns = ['name']; diff --git a/classes/Contact.php b/classes/Contact.php index 4a82ade..7689ef7 100644 --- a/classes/Contact.php +++ b/classes/Contact.php @@ -26,7 +26,7 @@ */ class Contact extends Model { /** {@inheritDoc} */ - public + public static $table = 'contact', $fillable_columns = ['clientId', 'name', 'email', 'address', 'address_2', 'postal_code', 'city', 'country', 'language']; @@ -35,7 +35,7 @@ class Contact extends Model { * @param $key {@inheritDoc} * @param $value {@inheritDoc} */ - protected function mutator($key, $value) { + protected static function mutator($key, $value) { switch ($key) { case 'language': if (!in_array($value, Correspondence::LANGUAGES)) { diff --git a/classes/Discount.php b/classes/Discount.php index f7dcf3b..161c358 100644 --- a/classes/Discount.php +++ b/classes/Discount.php @@ -28,7 +28,7 @@ class Discount extends OfferItem { use StandardCalculatable; /** {@inheritDoc} */ - public + public static $table = 'discount', $fillable_columns = ['offerId', 'title', 'description', 'value', 'VAT_percentage']; diff --git a/classes/File.php b/classes/File.php index e400d25..ad44448 100644 --- a/classes/File.php +++ b/classes/File.php @@ -26,10 +26,31 @@ */ class File extends Model { /** {@inheritDoc} */ - public + public static $table = 'file', $fillable_columns = ['filename', 'secret_key']; + /** {@inheritDoc} */ + public static function create($pdo, $values) { + $filename = $values[0]; + + // Check for file existence + if (file_exists(Constants::files_folder . $filename)) { + throw new Exception("$filename already exists."); + } + + // Try to create the file + if (file_put_contents(Constants::files_folder . $filename, '') === false) { + throw new Exception("$filename could not be created. Check the permissions."); + } + + if (count($values) < count(static::$fillable_columns)) { + $values[] = self::getRandomSecretKey(); + } + + return parent::create($pdo, $values); + } + /** * A random max-63-char string that can be used as secret_key * diff --git a/classes/Mail.php b/classes/Mail.php index 06c2eb6..f223fb8 100644 --- a/classes/Mail.php +++ b/classes/Mail.php @@ -26,7 +26,7 @@ */ class Mail extends Model { /** {@inheritDoc} */ - public + public static $table = 'mail', $fillable_columns = ['contactId', 'offerId', 'subject'], $timestamps = ['date']; diff --git a/classes/Mailer.php b/classes/Mailer.php index 33068b7..f95addc 100644 --- a/classes/Mailer.php +++ b/classes/Mailer.php @@ -95,7 +95,7 @@ class Mailer extends PHPMailer { return false; } - BusinessAdmin::createMail($this->pdo, $this->contactId, $this->offerId, $this->Subject); + Mail::create($this->pdo, [$this->contactId, $this->offerId, $this->Subject]); return true; } diff --git a/classes/Model.php b/classes/Model.php index 3b1c49e..9ad86f8 100644 --- a/classes/Model.php +++ b/classes/Model.php @@ -52,7 +52,7 @@ abstract class Model { * @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 + public static $table = '', $primary_key = 'id', $protected_columns = ['id'], @@ -79,10 +79,10 @@ abstract class Model { public function __construct($pdo, $id) { $this->pdo = $pdo; - $stmt = $this->pdo->prepare("SELECT * FROM `".$this->table()."` WHERE `{$this->primary_key}`=?"); + $stmt = $this->pdo->prepare("SELECT * FROM `".self::table()."` WHERE `".static::$primary_key."`=?"); $stmt->execute([$id]); if ($stmt->rowCount() == 0) { - throw new ModelNotFoundException("The {$this->table} with id '$id' could not be found."); + throw new ModelNotFoundException("The ".static::$table." with id '$id' could not be found."); } $this->data = $stmt->fetch(PDO::FETCH_ASSOC); } @@ -96,19 +96,19 @@ abstract class Model { * @throws PDOException Database error */ public function __set($key, $value) { - if (!in_array($key, $this->fillable_columns)) { - throw new ModelIllegalAccessException("Column `{$this->table()}`.`$key` cannot be edited."); + if (!in_array($key, static::$fillable_columns)) { + throw new ModelIllegalAccessException("Column `".self::table()."`.`$key` cannot be edited."); } if ($this->data[$key] == $value) { return; } - $stmt = $this->pdo->prepare("UPDATE `".$this->table()."` SET `$key`=? WHERE `{$this->primary_key}`=?"); + $stmt = $this->pdo->prepare("UPDATE `".self::table()."` SET `$key`=? WHERE `".static::$primary_key."`=?"); $stmt->execute([ $this->mutator($key, $value), - $this->data[$this->primary_key] + $this->data[static::$primary_key] ]); if ($stmt->rowCount() != 1) { - throw new ModelEditFailedException("Failed to update `{$this->table()}`.`$key` to '$value'."); + throw new ModelEditFailedException("Failed to update `".self::table()."`.`$key` to '$value'."); } $this->data[$key] = $value; } @@ -124,6 +124,35 @@ abstract class Model { return $this->accessor($key, $this->data[$key]); } + /** + * Create a new row + * + * @param PDO $pdo Database connection + * @param mixed[] $values The column values, in the order of $fillable_columns + * + * @throws PDOException Database error + * + * @return self The new item + */ + public static function create($pdo, $values) { + $columns = array_combine(static::$fillable_columns, $values); + $questions = []; + + foreach ($columns as $column => $value) { + $columns[$column] = self::mutator($column, $value); + $questions[] = '?'; + } + + $stmt = $pdo->prepare( + "INSERT INTO `".self::table()."` " . + "(`" . implode('`, `', array_keys($columns)) . "`) " . + "VALUES (" . implode(',', $questions) . ")"); + $stmt->execute(array_values($columns)); + + $class = get_called_class(); + return new $class($pdo, $pdo->lastInsertId()); + } + /** * Post-__get() hook to modify the value * @@ -132,12 +161,12 @@ abstract class Model { * * @return mixed The modified value */ - protected function accessor($key, $value) { + protected static function accessor($key, $value) { if (is_null($value)) { return null; - } elseif (in_array($key, $this->booleans)) { + } elseif (in_array($key, static::$booleans)) { return (bool) $value; - } elseif (in_array($key, $this->dates) || in_array($key, $this->timestamps)) { + } elseif (in_array($key, static::$dates) || in_array($key, static::$timestamps)) { return strtotime($value); } else { return $value; @@ -152,10 +181,10 @@ abstract class Model { * * @return string The modified value */ - protected function mutator($key, $value) { - if (in_array($key, $this->dates) && is_int($value)) { + protected static function mutator($key, $value) { + if (in_array($key, static::$dates) && is_int($value)) { return date('Y-m-d', $value); - } elseif (in_array($key, $this->timestamps) && is_int($value)) { + } elseif (in_array($key, static::$timestamps) && is_int($value)) { return date('Y-m-d H:i:s', $value); } else { return (string) $value; @@ -170,8 +199,8 @@ abstract class Model { * @return bool True iff the row was really deleted */ public function delete() { - $stmt = $this->pdo->prepare("DELETE FROM `{$this->table()}` WHERE `{$this->primary_key}`=?"); - $stmt->execute([$this->data[$this->primary_key]]); + $stmt = $this->pdo->prepare("DELETE FROM `".self::table()."` WHERE `".static::$primary_key."`=?"); + $stmt->execute([$this->data[static::$primary_key]]); return $stmt->rowCount() != 0; } @@ -180,7 +209,7 @@ abstract class Model { * * @return string The database table */ - private function table() { - return Constants::db_prefix . $this->table; + private static function table() { + return Constants::db_prefix . static::$table; } } diff --git a/classes/Offer.php b/classes/Offer.php index 23b1190..7d8e8b8 100644 --- a/classes/Offer.php +++ b/classes/Offer.php @@ -26,7 +26,7 @@ */ class Offer extends Model{ /** {@inheritDoc} */ - public + public static $table = 'offer', $fillable_columns = ['contactId', 'start_date', 'end_date', 'invoice_date', 'accepted', 'invoice_fileId', 'payment_key'], $dates = ['start_date', 'end_date', 'invoice_date'], @@ -395,7 +395,7 @@ class Offer extends Model{ $invoice_nr = date('Y',$this->invoice_date) . str_pad($i++, 2, '0', STR_PAD_LEFT); $filename = 'invoice-' . $invoice_nr . '.pdf'; } while (file_exists(Constants::files_folder . $filename)); - $file = BusinessAdmin::createFile($this->pdo, $filename); + $file = File::create($this->pdo, [$filename]); $this->invoice_fileId = $file->id; } else { diff --git a/classes/Payment.php b/classes/Payment.php index 59dde87..d37bcc9 100644 --- a/classes/Payment.php +++ b/classes/Payment.php @@ -26,7 +26,7 @@ */ class Payment extends Model { /** {@inheritDoc} */ - public + public static $table = 'payment', $fillable_columns = ['offerId', 'date', 'braintree_id', 'braintree_status'], $timestamps = ['date']; diff --git a/classes/User.php b/classes/User.php index 33396db..525a153 100644 --- a/classes/User.php +++ b/classes/User.php @@ -26,7 +26,7 @@ */ class User extends Model { /** {@inheritDoc} */ - public + public static $table = 'user', $fillable_columns = ['username', 'password']; @@ -61,7 +61,7 @@ class User extends Model { * @param $key {@inheritDoc} * @param $value {@inheritDoc} */ - public function mutator($key, $value) { + protected static function mutator($key, $value) { switch ($key) { case 'password': return self::hash($password); -- cgit v1.2.3