Advertisement
nickapopolus

Untitled

Oct 30th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.85 KB | None | 0 0
  1. <?php
  2.  
  3. class DatabaseObject {
  4.  
  5.   static protected $db;
  6.   static protected $table_name;
  7.   static protected $db_columns = [];
  8.   public $errors = [];
  9.  
  10.  
  11.   public static function set_db($db){
  12.     self::$db = $db;
  13.   }
  14.  
  15.   static public function find_by_sql($sql){
  16.    $result =  self::$db->query($sql);
  17.    if(!$result) {
  18.      exit("Database Query Failed");
  19.    }
  20.       //convert results into objects
  21.     $object_array=[];
  22.       while($record = $result->fetch_assoc()){
  23.      $object_array[] = static::instantiate($record);
  24.     }
  25.       $result->free();
  26.       return $object_array;
  27.     }
  28.  
  29.   static public function find_all(){
  30.     $sql = "SELECT * FROM " . static::$table_name;
  31.     return static::find_by_sql($sql);
  32.   }
  33.  
  34.   static public function find_by_id($id){
  35.       $sql = "SELECT * FROM " . static::$table_name;
  36.       $sql .= " WHERE id='" . self::$db->escape_string($id) . "'";
  37.       $object_array = static::find_by_sql($sql);
  38.       if(!$object_array){
  39.         return false;
  40.       }
  41.       return array_shift($object_array);
  42.     }
  43.  
  44.   static protected function instantiate($record){
  45.     $object = new static;
  46.     //could assign things by hand but its faster and easier to do it dunamically
  47.     //plus it's reusable.
  48.     foreach($record as $property => $value){
  49.       if(property_exists($object, $property)){
  50.         $object->$property = $value;
  51.       }
  52.     }
  53.     return $object;
  54.   }
  55.  
  56.   protected function validate() {
  57.     $this->errors = [];
  58.       $this->errors[] = "bar";
  59.     return $this->errors;
  60.   }
  61.  
  62.   protected function create(){
  63.       $this->validate();
  64.       if(!empty($errors))
  65.       {return false;}
  66.  
  67.       $attributes = $this->sanitize_attributes();
  68.  
  69.       $sql = "INSERT INTO " . static::$table_name . " (";
  70.       $sql .= join(',', array_keys($attributes));
  71.       $sql .= ") VALUES ('";
  72.       $sql .= join("', '", array_values($attributes));
  73.       $sql .= "')";
  74.       $result = self::$db->query($sql);
  75.       if ($result){
  76.         $this->id = static::$db->insert_id;
  77.       }
  78.       return $result;
  79.     }
  80.  
  81.        //attributes are the properties which have the db columns excluding id
  82.  
  83.   protected function update(){
  84.     $this->validate();
  85.     if(!empty($errors)){return false;}
  86.  
  87.     $attributes = $this->sanitize_attributes();
  88.     $attribute_pairs = [];
  89.     foreach($attributes as $key => $value) {
  90.       $attribute_pairs[] = "{$key}='{$value}'";
  91.     }
  92.     $sql = "UPDATE " . self::$db->escape_string(static::$table_name) . " SET ";
  93.     $sql .= join(', ', $attribute_pairs);
  94.     $sql .= " WHERE id='" . self::$db->escape_string($this->id) . "' ";
  95.     $sql .= "LIMIT 1";
  96.     $result = self::$db->query($sql);
  97.     return $result;
  98.   }
  99.  
  100.   public function save(){
  101.     if(isset($this->id)){
  102.       return $this->update();
  103.     } else {
  104.       return $this->create();
  105.     }
  106.   }
  107.  
  108.   public function merge_attributes($args){
  109.     foreach($args as $key => $value) {
  110.       if(property_exists($this, $key) && !is_null($value)){
  111.         $this->$key = $value;
  112.       }
  113.     }
  114.   }
  115.  
  116.   public function attributes() {
  117.       $attributes = [];
  118.  
  119.       foreach(static::$db_columns as $column) {
  120.         if($column == 'id'){ continue; }
  121.         $attributes[$column] = $this->$column;
  122.  
  123.       }
  124.       return $attributes;
  125.   }
  126.  
  127.    protected function sanitize_attributes() {
  128.       $attributes = $this->attributes();
  129.       $sanitized =[];
  130.       foreach($attributes as $key => $value){
  131.         $sanitized[$key] = self::$db->escape_string($value);
  132.       }
  133.       return $sanitized;
  134.     }
  135.  
  136.   public function delete(){
  137.       $sql = "DELETE FROM " . self::$db->escape_string(static::$table_name) . " ";
  138.       $sql .= "WHERE id='";
  139.       $sql .= self::$db->escape_string($this->id);
  140.       $sql .= "' LIMIT 1";
  141.  
  142.       $result = self::$db->query($sql);
  143.       return $result;
  144.       //after deleting the instance is still around
  145.       //which is useful so you can say $this->poop was deleted
  146.       //but we cant call CRUD functions
  147.   }
  148.  
  149. }
  150.  
  151. class Admin extends DatabaseObject {
  152.   static protected $table_name = 'admins';
  153.   static protected $db_columns = ['id', 'first_name', 'last_name', 'email', 'username', 'hashed_password'];
  154.  
  155.   public $id;
  156.   public $first_name;
  157.   public $last_name;
  158.   public $email;
  159.   public $username;
  160.   public $password;
  161.   public $confirm_password;
  162.   protected $hashed_password;
  163.   protected $password_required = true;
  164.  
  165.  
  166.  public function __construct($args = []){
  167.    $this->first_name = $args['first_name'] ?? '';
  168.    $this->last_name = $args['last_name'] ?? '';
  169.    $this->email = $args['email'] ?? '';
  170.    $this->username = $args['username'] ?? '';
  171.    $this->password = $args['password'] ?? '';
  172.    $this->confirm_password = $args['confirm_password'] ?? '';
  173.  }
  174.  
  175.   public function label() {
  176.     return $this->username . " Name: " . $this->first_name . " " . $this->last_name;
  177.   }
  178.  
  179.  
  180.   private function hash_password(){
  181.       $this->hashed_password = password_hash($this->password, PASSWORD_BCRYPT);
  182.   }
  183.  
  184.   protected function validate() {
  185.     $this->errors = parent::validate();
  186.     $this->errors[] = "foo";
  187.     if(is_blank($this->first_name)) {
  188.       $this->errors[] = "First name cannot be blank.";
  189.     } elseif (!has_length($this->first_name, array('min' => 2, 'max' => 255))) {
  190.       $this->errors[] = "First name must be between 2 and 255 characters.";
  191.     }
  192.  
  193.     if(is_blank($this->last_name)) {
  194.       $this->errors[] = "Last name cannot be blank.";
  195.     } elseif (!has_length($this->last_name, array('min' => 2, 'max' => 255))) {
  196.       $this->errors[] = "Last name must be between 2 and 255 characters.";
  197.     }
  198.  
  199.     if(is_blank($this->email)) {
  200.       $this->errors[] = "Email cannot be blank.";
  201.     } elseif (!has_length($this->email, array('max' => 255))) {
  202.       $this->errors[] = "Last name must be less than 255 characters.";
  203.     } elseif (!has_valid_email_format($this->email)) {
  204.       $this->errors[] = "Email must be a valid format.";
  205.     }
  206.  
  207.     if(is_blank($this->username)) {
  208.       $this->errors[] = "Username cannot be blank.";
  209.     } elseif (!has_length($this->username, array('min' => 8, 'max' => 255))) {
  210.       $this->errors[] = "Username must be between 8 and 255 characters.";
  211.     }
  212.  
  213.     if(is_blank($this->password)) {
  214.       $this->errors[] = "Password cannot be blank.";
  215.     } elseif (!has_length($this->password, array('min' => 12))) {
  216.       $this->errors[] = "Password must contain 12 or more characters";
  217.     } elseif (!preg_match('/[A-Z]/', $this->password)) {
  218.       $this->errors[] = "Password must contain at least 1 uppercase letter";
  219.     } elseif (!preg_match('/[a-z]/', $this->password)) {
  220.       $this->errors[] = "Password must contain at least 1 lowercase letter";
  221.     } elseif (!preg_match('/[0-9]/', $this->password)) {
  222.       $this->errors[] = "Password must contain at least 1 number";
  223.     } elseif (!preg_match('/[^A-Za-z0-9\s]/', $this->password)) {
  224.       $this->errors[] = "Password must contain at least 1 symbol";
  225.     }
  226.  
  227.     if(is_blank($this->confirm_password)) {
  228.       $this->errors[] = "Confirm password cannot be blank.";
  229.     } elseif ($this->password !== $this->confirm_password) {
  230.       $this->errors[] = "Password and confirm password must match.";
  231.     }
  232.  
  233.     return $this->errors;
  234.   }
  235.  
  236.   protected function create() {
  237.  
  238.     $this->hash_password();
  239.  
  240.     $result = parent::create();
  241.     return $result;
  242.  
  243.   }
  244.  
  245.   protected function update(){
  246.     if($this->password != ''){
  247.       $this->hash_password();
  248.     } else {
  249.       $this->password_required = false;
  250.     }
  251.     $result = parent::update();
  252.     return $result;
  253.   }
  254. }
  255.  
  256. //Bicycle is my post class. This is kind of embarrassing but I'm refreshing myself on OOP to get back into coding and I'm building a //fake bike store site.
  257. class Bicycle extends DatabaseObject {
  258.  
  259.  
  260. protected static $table_name = "bicycles";
  261. static protected $db_columns = ['id', 'brand', 'model', 'year', 'category', 'color', 'gender', 'price', 'condition_id', 'description', 'weight_kg'];
  262.  
  263.  
  264. public const CATEGORIES = ['road', 'mountain', 'hybrid', 'cruiser', 'city', 'BMX'];
  265. public const GENDER = ['mens', 'womens', 'unisex'];
  266. public $id;
  267. public $brand;
  268. public $model;
  269. public $year = 1987;
  270. public $category = self::CATEGORIES[0];
  271. public $color;
  272. public $gender;
  273. public $price = 0.0;
  274. public $condition_id;
  275. public $description;
  276.  
  277. protected $weight_kg = 0.0;
  278. public const CONDITION = [
  279.   1 => 'Beat up',
  280.   2 => 'Decent',
  281.   3 => 'Good',
  282.   4 => 'Great',
  283.   5 => 'Like New'
  284. ];
  285.  
  286. public function __construct($args=[]){
  287.   $this->brand     = $args['brand']     ?? null;
  288.   $this->model     = $args['model']     ?? null;
  289.   $this->year      = $args['year']      ?? $this->year;
  290.   $this->category  = $args['category']  ?? $this->category;
  291.   $this->color     = $args['color']     ?? null;
  292.   $this->gender    = $args['gender']    ?? null;
  293.   $this->price     = $args['price']     ?? $this->price;
  294.   $this->condition_id = $args['condition_id'] ?? null;
  295.   $this->weight_kg = $args['weight_kg'] ?? 0.0;
  296.   //foreach($args as $k => $v) {
  297.   //if(property_exists($this, $k)){
  298.   //$this->$k = $v;
  299.   //}
  300.   //}
  301. }
  302.  
  303. public function get_weight_kg(){
  304.   return $this->weight_kg . " kg";
  305. }
  306.  
  307. public function get_weight_kg_no_kg(){
  308.   return $this->weight_kg;
  309. }
  310.  
  311. public function set_weight_kg($value){
  312.   $this->weight_kg = floatval($value);
  313. }
  314.  
  315. public function get_weight_lbs(){
  316.   return $this->weight_kg * 2.2046226218 . " lbs";
  317. }
  318.  
  319. public function set_weight_lbs($value){
  320.   $this->weight_kg = $value / 2.2046226218;
  321. }
  322.  
  323. public function condition(){
  324.   if($this->condition_id > 0 ){
  325.     return Self::CONDITION[$this->condition_id];
  326.   } else {
  327.     return "unknown";
  328.   }
  329. }
  330. public function name() {
  331.   return $this->year . ' ' . $this->brand . ' ' . $this->model;
  332. }
  333.  
  334. protected function validate(){
  335.   $this->errors = parent::validate();
  336.   if(is_blank($this->brand)){
  337.     $this->errors[] = "Brand cannot be blank.";
  338.   }
  339.   return $this->errors;
  340. }
  341.  
  342. }
  343.  
  344.  
  345.  ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement