SMMP/build/orm/core/Table.php

194 lines
5.3 KiB
PHP
Raw Permalink Normal View History

2016-07-21 20:05:30 +00:00
<?php
2016-10-18 14:03:03 +00:00
namespace orm\core;
2016-07-21 20:05:30 +00:00
use \database\core\DatabaseDriver;
2016-10-18 17:09:47 +00:00
use \error\core\Error;
2016-10-18 14:03:03 +00:00
use \orm\core\Rows;
2016-07-21 20:05:30 +00:00
// CLASSE MAITRE
class Table{
/* RENVOIE LES DONNEES D'UNE TABLE
*
* @table<String> Nom de la table à selectionner
* @driver<String> [optional] DatabaseDriver label
2016-07-21 20:05:30 +00:00
*
* @return this<ORM> Retourne une instance de l'ORM
*
*/
public static function get($table_name, $driver=null){
2016-07-21 20:05:30 +00:00
/* [0] Initialisation des attributs
=========================================================*/
$schema = [
'database' => DatabaseDriver::get($driver)->getConfig()['dbname'],
2016-07-21 20:05:30 +00:00
'table' => null,
'columns' => null
];
/* [1] On vérifie que la table existe
=========================================================*/
/* (1) Requête */
$checkTable = DatabaseDriver::getPDO($driver)->query("SHOW tables FROM ".$schema['database']);
$checkTableResult = DatabaseDriver::delNumeric( $checkTable->fetchAll() );
2016-07-21 20:05:30 +00:00
/* (2) On met en forme les données */
$tables = [];
foreach($checkTableResult as $table)
$tables[] = $table['Tables_in_'.$schema['database']];
2016-07-21 20:05:30 +00:00
/* (3) Si n'existe pas, on renvoie une erreur */
if( !in_array($table_name, $tables) )
return null;
/* (4) On enregistre les données */
$schema['table'] = $table_name;
/* [2] Si la table existe, on récupère les colonnes
2016-07-21 20:05:30 +00:00
=========================================================*/
/* (1) On récupère les colonnes */
$getColumns = DatabaseDriver::getPDO($driver)->query("SHOW columns FROM ".$schema['database'].'.'.$table_name);
$columnsResult = DatabaseDriver::delNumeric( $getColumns->fetchAll() );
2016-07-21 20:05:30 +00:00
/* (2) On met en forme les données */
$columns = [];
foreach($columnsResult as $col){
// On formatte le type //
$type = $col['Type'];
if( preg_match('/^(int|float|varchar|text)/i', $type, $m) )
$type = strtolower($m[1]);
2016-07-21 20:05:30 +00:00
// On ajoute la colonne //
$columns[$col['Field']] = [
'type' => $type,
'primary' => $col['Key'] == 'PRI'
];
}
/* (3) Si on trouve rien, on envoie une erreur */
if( !is_array($columns) || count($columns) == 0 )
return null;
/* (4) On enregistre les colonnes */
$schema['columns'] = $columns;
/* [3] On récupère les clés étrangères
=========================================================*/
/* (1) On récupère le texte du 'CREATE TABLE' */
$getCreateTable = DatabaseDriver::getPDO($driver)->query("show create table ".$table_name);
$create_table = $getCreateTable->fetch()['Create Table'];
/* (2) On découpte en lignes */
$create_table_lines = explode("\n", $create_table);
/* (3) Pour chaque ligne, si c'est une contrainte, on l'enregistre dans la colonne associée */
foreach($create_table_lines as $i=>$line)
if( preg_match('/CONSTRAINT `.+` FOREIGN KEY \(`(.+)`\) REFERENCES `(.+)` \(`(.+)`\)+/i', $line, $m) )
$schema['columns'][$m[1]]['references'] = [$m[2], $m[3]];
2016-07-21 20:05:30 +00:00
/* [3] On renvoie une instance de 'Rows'
=========================================================*/
return new Rows($schema, $driver);
2016-07-21 20:05:30 +00:00
}
};
2016-10-18 14:03:03 +00:00
/*** USE CASE :: ACCESS TABLE `user` ***/
// ORM::Table('user');
/**** USE CASE :: WHERE ****/
// WHERE `username` = 'someUsername'
// ORM::Table('user')->whereUsername('someUsername');
// EQUIVALENT TO
// ORM::Table('user')->whereUsername('someUsername', Rows::COND_EQUAL);
// WHERE `id_user` < 100
// ORM::Table('user')->whereIdUser(100, Rows::COND_INF);
// WHERE `id_user` <= 100
// ORM::Table('user')->whereIdUser(100, Rows::COND_INFEQ);
// WHERE `id_user` > 10
// ORM::Table('user')->whereIdUser(10, Rows::COND_SUP);
// WHERE `id_user` >= 10
// ORM::Table('user')->whereIdUser(10, Rows::COND_SUPEQ);
// WHERE `id_user` in (1, 2, 3, 8)
// ORM::Table('user')->whereIdUser([1, 2, 3, 8], Rows::COND_IN);
// WHERE `id_user` LIKE 'John %'
// ORM::Table('user')->whereIdUser('John %', Rows::COND_LIKE);
/*** USE CASE :: ORDER BY ****/
// ORDER BY `a` ASC, `b` DESC
// Table::get('someTable')
// ->orderby('a', Rows::ORDER_ASC)
// ->orderby('b', Rows::ORDER_DESC);
2016-07-21 20:05:30 +00:00
//
2016-10-18 14:03:03 +00:00
// Note: `Rows::ORDER_ASC` is set by default if the given FLAG is invalid
/**** USE CASE :: SELECT ****/
// SELECT id_user, username
// Table::get('user')
// ->select('id_user')
// ->select('username');
/**** USE CASE :: AGGREGATION FUNCTIONS ****/
// SELECT COUNT(`count`)
// Table::get('user')->select('count', Rows::SEL_COUNT)
// SELECT SUM(distinct `count`)
// Table::get('user')->select('count', Rows::SEL_SUM, Rows::SEL_DISTINCT);
// SELECT AVG(`count`)
// Table::get('user')->select('count', Rows::SEL_AVG);
// SELECT MAX(`id_user`)
// Table::get('user')->select('id_user', Rows::SEL_MAX);
// SELECT MIN(`id_user`)
// Table::get('user')->select('id_user', Rows::SEL_MIN);
// SELECT GROUP_CONCAT(`count`)
// Table::get('user')->select('count', Rows::SEL_CONCAT);
/**** USE CASE :: FETCH ****/
// SELECT ... FROM ... WHERE ... ORDERBY ... LIMIT ...
// Table::get('user')
// ->select('id_user')
// ->fetch();
// SELECT UNIQUE ... FROM ... WHERE ... ORDERBY ... LIMIT ...
// Table::get('user')
// ->select('id_user')
// ->unique->fetch();
/**** USE CASE :: TABLE JOIN ****/
// WHERE `user`.`id_user` = `user_merge`.`id_user`
// Table::get('user_merge')->join(
// Table::get('user')->whereIdUser(1, Rows::COND_SUP)
// );