duckbrain/src/Libs/ModelMySQL.php

416 lines
9.9 KiB
PHP
Raw Normal View History

2020-03-08 04:37:19 +01:00
<?php
namespace Libs;
use Libs\Database;
class ModelMySQL {
public $id;
protected $primaryKey = 'id';
protected $ignoreSave = ['id'];
protected $forceSave = [];
static protected $table;
static protected $tableSufix = 's';
static protected $db;
static protected $querySelect = [
'select' => '*',
'where' => '',
2020-03-12 05:57:15 +01:00
'leftJoin' => '',
'rightJoin' => '',
'on' => '',
2020-03-08 04:37:19 +01:00
'AndOr' => '',
'orderBy'=>'',
'groupBy'=>'',
'limit' => '',
];
private static function db(){
if (is_null(self::$db))
self::$db = Database::getConnection();
return self::$db;
}
private static function query($query){
$db = self::db();
$result = $db->query($query);
if ($db->errno){
echo 'Fallo al consultar la base de datos.<br>
Errno: ' . addslashes ($db->errno).'<br>
Error: ' . addslashes ($db->error).'<br>'.$query;
exit();
}
return $result;
}
private static function resetQuery(){
self::$querySelect = [
'select' => '*',
'where' => '',
2020-03-12 05:57:15 +01:00
'leftJoin' => '',
'rightJoin' => '',
'on' => '',
2020-03-08 04:37:19 +01:00
'AndOr' => '',
'orderBy'=>'',
'groupBy'=>'',
'limit' => '',
];
}
private static function buildQuery(){
$sql = 'SELECT '.self::$querySelect['select'].' FROM '.self::table();
2020-03-12 05:57:15 +01:00
if (self::$querySelect['leftJoin'] != ''){
$sql .= ' LEFT JOIN ' . self::$querySelect['leftJoin'];
$sql .= ' ON '. self::$querySelect['on'];
} elseif(self::$querySelect['rightJoin'] != ''){
$sql .= ' RIGHT JOIN ' . self::$querySelect['leftJoin'];
$sql .= ' ON '. self::$querySelect['on'];
}
2020-03-08 04:37:19 +01:00
if (self::$querySelect['where'] != ''){
$sql .= ' WHERE '.self::$querySelect['where'];
if (self::$querySelect['AndOr'] != ''){
$sql .= self::$querySelect['AndOr'];
}
}
if (self::$querySelect['groupBy'] != ''){
$sql .= ' GROUP BY '.self::$querySelect['groupBy'];
}
if (self::$querySelect['orderBy'] != ''){
$sql .= ' ORDER BY '.self::$querySelect['orderBy'];
}
if (self::$querySelect['limit'] != ''){
$sql .= ' LIMIT '.self::$querySelect['limit'];
}
self::resetQuery();
return $sql;
}
public function getInstance($elem = []){
$class = get_called_class();
$instace = new $class;
foreach ($elem as $key => $value){
$instace->$key = $value;
}
return $instace;
}
private function getVars(){ // Source: https://stackoverflow.com/questions/10009015/show-all-public-attributes-name-and-value-of-an-object
$get_vars_proxy = create_function('$obj', 'return get_object_vars($obj);');
$result = $get_vars_proxy($this);
foreach ($this->ignoreSave as $del){
unset($result[$del]);
}
foreach ($this->forceSave as $value){
$result[$value] = $this->$value;
}
return $result;
}
public static function className(){
return strtolower(substr(strrchr(get_called_class(), '\\'), 1));
}
private static function table(){
if (isset(self::$table))
return self::$table;
return self::className().self::$tableSufix;
}
private function update(){
$atts = $this->getVars();
foreach ($atts as $key => $value){
$value = self::db()->real_escape_string($value);
$set[]="$key='$value'";
}
$table = self::table();
$pk = $this->primaryKey;
$pkv = $this->$pk;
$sql = "UPDATE $table SET ".join(', ', $set)." WHERE $pk='$pkv'";
self::query($sql);
}
private function add(){
$db = self::db();
$atts = $this->getVars();
foreach ($atts as $key => $value){
$into[] = "`$key`";
$values[] = "'".$db->real_escape_string($value)."'";
}
$table = self::table();
$sql = "INSERT INTO $table (".join(', ', $into).") VALUES (".join(', ', $values).")";
self::query($sql);
$pk = $this->primaryKey;
$this->$pk = $db->insert_id;
}
public function save(){
$pk = $this->primaryKey;
if (isset($this->$pk))
$this->update();
else
$this->add();
}
public function delete(){
$atts = $this->getVars();
foreach ($atts as $key => $value){
$value = self::db()->real_escape_string($value);
$set[]="$key='$value'";
}
$table = self::table();
$pk = $this->primaryKey;
$pkv = $this->$pk;
$sql = "DELETE FROM $table WHERE $pk='$pkv'";
self::query($sql);
}
public static function select($value){
$db = self::db();
$select = [];
foreach($value as $elem){
$select[] = $db->real_escape_string($elem);
}
self::$querySelect['select'] = join(', ', $select);
return new static();
}
/*
* Sintaxis permitidas:
* - Class::where(columna, operador, valor)
* - Class::where(columna, valor) // Operador por defecto "="
*/
public static function where($column, $operator, $value=null){
if (is_null($value)){
$value = $operator;
$operator = '=';
}
$value = self::db()->real_escape_string($value);
self::$querySelect['where'] = "$column$operator'$value'";
return new static();
}
public static function where_in($column,$arr, $in = true){
foreach($arr as $index => $value){
$arr[$index] = self::db()->real_escape_string($value);
}
if ($in)
self::$querySelect['where'] = "$column IN (".join(', ',$arr).")";
else
self::$querySelect['where'] = "$column NOT IN (".join(', ',$arr).")";
return new static();
}
2020-03-12 05:57:15 +01:00
public static function leftJoin($table, $columnA, $operator, $columnB = null){
if (is_null($columnB)){
$columnB = $operator;
$operator = '=';
}
$columnA = self::db()->real_escape_string($columnA);
$columnB = self::db()->real_escape_string($columnB);
self::$querySelect['leftJoin'] = $table;
self::$querySelect['on'] = "$columnA$operator$columnB";
return new static();
}
public static function rightJoin($table, $columnA, $operator, $columnB = null){
if (is_null($columnB)){
$columnB = $operator;
$operator = '=';
}
$columnA = self::db()->real_escape_string($columnA);
$columnB = self::db()->real_escape_string($columnB);
self::$querySelect['rightJoin'] = $table;
self::$querySelect['on'] = "$columnA$operator$columnB";
return new static();
}
2020-03-08 04:37:19 +01:00
public static function and($column, $operator, $value=null){
if (is_null($value)){
$value = $operator;
$operator = '=';
}
$value = self::db()->real_escape_string($value);
self::$querySelect['AndOr'] = " AND $column$operator'$value'";
return new static();
}
public static function or($column, $operator, $value=null){
if (is_null($value)){
$value = $operator;
$operator = '=';
}
$value = self::db()->real_escape_string($value);
self::$querySelect['AndOr'] = " OR $column$operator'$value'";
return new static();
}
public static function groupBy($arr){
self::$querySelect['groupBy'] = join(', ', $arr);
return new static();
}
public static function limit($initial, $final = 0){
$initial = (int)$initial;
$final = (int)$final;
if ($final==0)
self::$querySelect['limit'] = $initial;
else
self::$querySelect['limit'] = $initial.', '.$final;
return new static();
}
public static function orderBy($value, $order = 'ASC'){
if ($value == "RAND"){
self::$querySelect['orderBy'] = 'RAND()';
return new static();
}
$value = self::db()->real_escape_string($value);
if (!(strtoupper($order) == 'ASC' || strtoupper($order) == 'DESC'))
$order = 'ASC';
self::$querySelect['orderBy'] = $value.' '.$order;
return new static();
}
public static function count(){
self::$querySelect['select'] = 'count(*) as quantity';
$sql = self::buildQuery();
$result = self::query($sql)->fetch_assoc();
return $result['quantity'];
}
public static function getById($id){
return self::where('id', $id)->getFirst();
}
public static function search($search, $in = null){
$className = get_called_class();
$objAtts = array_keys((new $className())->getVars());
if ($in == null){
$in = $objAtts;
}
$db = self::db();
$search = $db->real_escape_string($search);
$where = [];
foreach($in as $row){
if(in_array($row, $objAtts))
$where[] = "$row LIKE '%$search%'";
}
if (self::$querySelect['where']=='')
self::$querySelect['where'] = join($where, ' OR ');
else
self::$querySelect['where'] = self::$querySelect['where'] .' AND ('.join($where, ' OR ').')';
return new static();
}
public static function get(){ // Devuelve array vacío si no encuentra nada
$sql = self::buildQuery();
$result = self::query($sql);
$instaces = [];
while ($row = $result->fetch_assoc()){
$instaces[] = self::getInstance($row);
}
return $instaces;
}
public static function getFirst(){ // Devuelve null si no encuentra nada
self::limit(1);
$instaces = self::get();
return empty($instaces) ? null : $instaces[0];
}
public static function all(){
$sql = 'SELECT * FROM '.self::table();
$result = self::query($sql);
$instaces = [];
while ($row = $result->fetch_assoc()){
$instaces[] = self::getInstance($row);
}
return $instaces;
}
}
?>