SHARE
TWEET

Untitled

a guest Apr 19th, 2019 94 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. namespace App\Models;
  4.  
  5. class DatabaseException extends \ErrorException {
  6.     protected $stactrace;
  7.     /**
  8.      * DatabaseException constructor.
  9.      *
  10.      * @param string $message
  11.      * @param string $stacktrace
  12.      */
  13.     public function __construct($message, $stacktrace) {
  14.         parent::__construct($message);
  15.         $this->stacktrace = $stacktrace;
  16.     }
  17.     public function getDatabaseResponse() {
  18.         return $this->stacktrace;
  19.     }
  20. }
  21.  
  22. class Model {
  23.  
  24.     protected static $fields = [];
  25.     protected static $connection;
  26.  
  27.     /**
  28.      * Model constructor.
  29.      *
  30.      * This is the constructor. In general it is empty but if you want to create a new
  31.      * entry you can use this constructor to pass some fields while cration already.
  32.      *
  33.      * Example:
  34.      *   $user = new UserModel([ 'username' => 'somefancyname']);
  35.      *   $user->save();
  36.      *   echo('Created new user ' . $user->username . ' with ID ' . $user->id);
  37.      *
  38.      * @param array $data
  39.      * @throws DatabaseException
  40.      */
  41.     public function __construct($data = []) {
  42.         foreach ($data as $key => $value) {
  43.             if (in_array($key, static::fields(static::$table))) {
  44.                 $this->{$key} = $value;
  45.             }
  46.         }
  47.         $this->id = intval($this->id);
  48.     }
  49.  
  50.     /**
  51.      * Returns the fields available or updates them in the static variable if not set
  52.      *
  53.      * @return array
  54.      * @throws DatabaseException
  55.      */
  56.     public static function fields() {
  57.         if (!static::$fields[static::$table]) {
  58.             $query = static::
  59.         tion()->query("SELECT * FROM " . static::$table . " LIMIT 0");
  60.             $fields = [];
  61.             foreach ($query->fetch_fields() as $field) {
  62.                 $fields[] = $field->name;
  63.             }
  64.             static::$fields[static::$table] = $fields;
  65.         }
  66.         return static::$fields[static::$table];
  67.     }
  68.  
  69.     /**
  70.      * Gets a row by id (primary key)
  71.      *
  72.      * Example:
  73.      *   $user = UserModel::find(1);
  74.      *   echo('User with ID 1: ' . $user->username);
  75.      *
  76.      * @param integer $id
  77.      * @return Model
  78.      * @throws DatabaseException
  79.      */
  80.     public static function find($id) {
  81.         $id = intval($id);
  82.         $c = static::getConnection();
  83.         $result = $c->query("SELECT * FROM " . static::$table . " WHERE `id`=" . static::escape($id));
  84.         if (!$result) {
  85.             throw new DatabaseException("MySQL: Unable to execute query", $c->error);
  86.         }
  87.         $t = '\\App\\Models\\' . ucfirst(static::$table) . 'Model';
  88.         return new $t($result->fetch_array(MYSQLI_ASSOC));
  89.     }
  90.  
  91.     /**
  92.      * Gets a row by fields (where)
  93.      * Also supports some kind of join as second argument (only over n to m relations)
  94.      *
  95.      * Example:
  96.      *   $user = AdvertModel::where([['advert_id', $this->id]]);
  97.      *
  98.      * @param integer $id
  99.      * @return Model[]
  100.      * @throws DatabaseException
  101.      */
  102.     public static function where($where = [], $joins = []) {
  103.         $c = static::getConnection();
  104.         $qry = [];
  105.         foreach ($where as $w) {
  106.             $qry[] = $w[0] . " = " . (is_numeric($w[1]) ? $w[1] : "\"" . static::escape($w[1]) . "\"");
  107.         }
  108.         $qry = implode(" AND ", $qry);
  109.        
  110.         $sqlJoins = [];
  111.         foreach($joins as $join) {
  112.             $sqlJoins[] = "INNER JOIN " . $join["using"] . " ON " . static::$table . ".id = " . $join["using"] . "." . static::$table . "_id";
  113.             $sqlJoins[] = "INNER JOIN " . $join["name"] . " ON " . $join["name"] . ".id = " . $join["using"] . "." . $join["name"] . "_id";
  114.         }
  115.         $sqlJoins = implode(" ", $sqlJoins);
  116.         $sel = static::$table . '.' . implode(', ' . static::$table . '.', static::fields());
  117.         $result = $c->query("SELECT " . $sel . " FROM " . static::$table . " " . $sqlJoins . " WHERE " . $qry);
  118.         if (!$result) {
  119.             throw new DatabaseException("MySQL: Unable to execute query", $c->error);
  120.         }
  121.         $r = [];
  122.         while ($data = $result->fetch_array(MYSQLI_ASSOC)) {
  123.             $res = [];
  124.             foreach($data as $key => $value) {
  125.                 $res[str_replace(static::$table . '.', '', $key)] = $value;
  126.             }
  127.             $r[] = new static($res);
  128.         }
  129.         return $r;
  130.     }
  131.  
  132.     /**
  133.      * Get all rows
  134.      * Returns all rows as object, so you can use them directly with the regular model features.
  135.      *
  136.      * @return Model[]
  137.      * @throws DatabaseException
  138.      */
  139.     public static function all() {
  140.         $c = static::getConnection();
  141.         $r = $c->query("SELECT * FROM " . static::$table);
  142.         if (!$r) {
  143.             throw new DatabaseException("MySQL: Unable to execute query", $c->error);
  144.         }
  145.         $result = [];
  146.         while ($data = $r->fetch_array(MYSQLI_ASSOC)) {
  147.             $result[] = new static($data);
  148.         }
  149.         return $result;
  150.     }
  151.  
  152.     /**
  153.      * Deletes a row
  154.      *
  155.      * Deletes an entry of the database.
  156.      *
  157.      * Example:
  158.      *   $user = UserModel::find(1);
  159.      *   $user->delete();
  160.      *
  161.      * @return bool
  162.      * @throws DatabaseException
  163.      */
  164.     public function delete() {
  165.         if (!$this->id) {
  166.             return false;
  167.         }
  168.         return static::getConnection()->query("DELETE FROM " . static::$table . " WHERE `id`=" . $this->id);
  169.     }
  170.  
  171.     /**
  172.      * Write changes to the database
  173.      *
  174.      * This function saves all changes made to the database.
  175.      *
  176.      * Example:
  177.      *   $user = UserModel::find(1);
  178.      *   $user->username = 'somename';
  179.      *   $user->save();
  180.      *
  181.      * @return Model
  182.      * @throws DatabaseException
  183.      */
  184.     public function save() {
  185.         $query = "INSERT INTO " . static::$table . " (";
  186.         $query .= implode(',', static::fields());
  187.         $query .= ') VALUES (';
  188.         $update = [];
  189.         $insert = [];
  190.         foreach (static::fields() as $field) {
  191.             if(substr( $this->{$field}, 0, 7 ) === 'file://') {
  192.                 $val = "0x".bin2hex(file_get_contents(str_replace('file://', '', $this->{$field})))."";
  193.             } else {
  194.                 $val = is_numeric($this->{$field}) ? $this->{$field} : (($this->{$field} === null) ? 'NULL' : '"' . static::escape($this->{$field}) . '"');
  195.             }
  196.             $insert[] = $val;
  197.             if ($field === 'id') {
  198.                 continue;
  199.             }
  200.             $update[] = ' `' . $field . '`=' . $val;
  201.         }
  202.         $query .= implode(', ', $insert);
  203.         $query .= ') ON DUPLICATE KEY UPDATE ';
  204.         $query .= implode(', ', $update);
  205.         $c = static::getConnection();
  206.         $c->query($query);
  207.         $this->id = $c->insert_id;
  208.         if ($this->id === 0) {
  209.             throw new DatabaseException("MySQL: Unable to execute query", $c->error);
  210.         }
  211.         return $this;
  212.     }
  213.  
  214.     public function update($id) {
  215.       $query = "UPDATE " . static::$table;
  216.       $update = [];
  217.       foreach (static::fields() as $field) {
  218.           $val = is_numeric($this->{$field}) ? $this->{$field} : (($this->{$field} === null) ? 'NULL' : '"' . static::escape($this->{$field}) . '"');
  219.           if ($field === 'id') {
  220.               continue;
  221.           }
  222.           $update[] = ' `' . $field . '`=' . $val;
  223.       }
  224.       $query .= ' SET ';
  225.       $query .= implode(', ', $update);
  226.       $query .= ' WHERE `id` = ' . $id;
  227.       $c = static::getConnection();
  228.       $c->query($query);
  229.       if ($this->id === 0) {
  230.           throw new DatabaseException("MySQL: Unable to execute query", $c->error);
  231.       }
  232.     }
  233.  
  234.     /**
  235.      * Protected helper function (internal use only)
  236.      *
  237.      * Returns the connection of the singleton class DatabaseConnection.
  238.      * This prevents creating multiple connections.
  239.      *
  240.      * @return mixed
  241.      * @throws DatabaseException
  242.      */
  243.     private static function getInstance() {
  244.         if (!static::$connection) {
  245.             $credentials = include(BASE_DIR . '/config/database.php');
  246.             static::$connection = new \mysqli($credentials['hostname'], $credentials['username'], $credentials['password'], $credentials['database']);
  247.             if (static::$connection->connect_errno) {
  248.                 throw new DatabaseException("MySQL connection failed! (" . static::$connection->connect_errno . ") ", static::$connection->connect_error);
  249.             }
  250.         }
  251.         static::$connection->set_charset("utf8");
  252.         return static::$connection;
  253.     }
  254.  
  255.     public static function escape($str) {
  256.         return mysqli_real_escape_string(static::getConnection(), $str);
  257.     }
  258. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top