update descartes

This commit is contained in:
osaajani 2019-10-29 18:33:30 +01:00
parent 508aeb0957
commit e15fb3cf8c
15 changed files with 112 additions and 60 deletions

View File

@ -1,4 +1,5 @@
<?php
namespace descartes;
/**
* Cette classe sert de mère à tous les controlleurs destiné à la création d'API. Elle hérite de toutes les infos d'un controller standard, mais elle embarque en plus des mécanismes propres aux api REST, etc.
*/

View File

@ -1,5 +1,6 @@
<?php
/**
namespace descartes;
/**
* Class to route console query
*/
class Console
@ -108,7 +109,7 @@
$params[$name] = $value;
}
$reflection = new ReflectionMethod($controller, $method);
$reflection = new \ReflectionMethod($controller, $method);
$method_arguments = [];
foreach ($reflection->getParameters() as $parameter)
@ -168,12 +169,12 @@
$retour .= 'Help of Controller ' . $controller . "\n" .
"Methods : \n";
$reflection = new ReflectionClass($controller);
$reflection = new \ReflectionClass($controller);
$reflection_methods = $reflection->getMethods();
}
else
{
$reflection_methods = [new ReflectionMethod($controller, $method)];
$reflection_methods = [new \ReflectionMethod($controller, $method)];
$retour .= 'Help of Controller ' . $controller . ' and method ' . $method . "\n";
}
@ -228,7 +229,14 @@
return true;
}
$controller = new $controller(...$args);
$reflection = new \ReflectionClass($controller);
$reflection_method = $reflection->getMethod($method);
if (!$reflection_method->isStatic())
{
$controller = new $controller(...$args);
}
return call_user_func_array([$controller, $method], $params);
}

View File

@ -1,4 +1,5 @@
<?php
namespace descartes;
/**
* This class is the parent of all controllers
*/

View File

@ -1,5 +1,7 @@
<?php
/**
namespace descartes;
/**
* Cette classe sert de mère à tous les controlleurs internes
*/
class InternalController extends Controller

View File

@ -1,4 +1,6 @@
<?php
namespace descartes;
/**
* Cette classe sert de mère à tous les modèles, elle permet de gérer l'ensemble des fonction necessaires aux requetes en base de données
* @param $pdo : Une instance de PDO
@ -31,7 +33,7 @@
* @param string $password : Le mot de passe à employer
* @return mixed : Un objet PDO ou false en cas d'erreur
*/
public static function connect ($host, $dbname, $user, $password, ?string $charset = 'UTF8', ?array $options = null)
public static function _connect ($host, $dbname, $user, $password, ?string $charset = 'UTF8', ?array $options = null)
{
$options = $options ?? [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
@ -58,7 +60,7 @@
* @param boolean $debug : If we must return debug info instead of data, by default false
* @return mixed : Result of query, depend of $return_type | null | array | object | int
*/
public function run_query (string $query, array $datas = array(), int $return_type = self::FETCHALL, int $fetch_mode = PDO::FETCH_ASSOC, bool $debug = false)
protected function _run_query (string $query, array $datas = array(), int $return_type = self::FETCHALL, int $fetch_mode = PDO::FETCH_ASSOC, bool $debug = false)
{
$query = $this->pdo->prepare($query);
$query->setFetchMode($return_type);
@ -98,7 +100,7 @@
* Return last inserted id
* return int : Last inserted id
*/
public function last_id() : int
protected function _last_id() : int
{
return $this->pdo->lastInsertId();
}
@ -113,7 +115,7 @@
* @param string $values : Values to generate in array from
* @return array : Array ['QUERY' => string 'IN(...)', 'PARAMS' => [parameters to pass to execute]]
*/
public function generate_in_from_array ($values)
protected function _generate_in_from_array ($values)
{
$return = array(
'QUERY' => '',
@ -141,7 +143,7 @@
* @param $value : value of field
* @return array : array with QUERY and PARAMS
*/
public function evaluate_condition (string $fieldname, $value) : array
protected function _evaluate_condition (string $fieldname, $value) : array
{
$first_char = mb_substr($fieldname, 0, 1);
$second_char = mb_substr($fieldname, 1, 1);
@ -206,13 +208,13 @@
* @param string $offset : Le nombre de résultats à ignorer (par défaut pas de résultats ignorés)
* @return mixed : False en cas d'erreur, sinon les lignes retournées
*/
public function select (string $table, array $conditions = [], ?string $order_by = null, bool $desc = false, ?int $limit = null, ?int $offset = null)
protected function _select (string $table, array $conditions = [], ?string $order_by = null, bool $desc = false, ?int $limit = null, ?int $offset = null)
{
$wheres = array();
$params = array();
foreach ($conditions as $label => $value)
{
$condition = $this->evaluate_condition($label, $value);
$condition = $this->_evaluate_condition($label, $value);
$wheres[] = $condition['QUERY'];
$params = array_merge($params, $condition['PARAM']);
}
@ -267,9 +269,9 @@
* Get one line from table, posssibly with some conditions
* see get
*/
public function select_one (string $table, array $conditions = [], ?string $order_by = null, bool $desc = false, ?int $limit = null, ?int $offset = null)
protected function _select_one (string $table, array $conditions = [], ?string $order_by = null, bool $desc = false, ?int $limit = null, ?int $offset = null)
{
$result = $this->select($table, $conditions, $order_by, $desc, $limit, $offset);
$result = $this->_select($table, $conditions, $order_by, $desc, $limit, $offset);
if (empty($result[0]))
{
@ -283,13 +285,13 @@
* Count line from table, posssibly with some conditions
* @param array $conditions : conditions of query Les conditions pour la mise à jour sous la forme "label" => "valeur". Un operateur '<, >, <=, >=, !' peux précder le label pour modifier l'opérateur par défaut (=)
*/
public function count (string $table, array $conditions = []) : int
protected function _count (string $table, array $conditions = []) : int
{
$wheres = array();
$params = array();
foreach ($conditions as $label => $value)
{
$condition = $this->evaluate_condition($label, $value);
$condition = $this->_evaluate_condition($label, $value);
$wheres[] = $condition['QUERY'];
$params = array_merge($params, $condition['PARAM']);
}
@ -318,7 +320,7 @@
* @param array $conditions : conditions to use, format 'fieldname' => 'value', fieldname can be preceed by operator '<, >, <=, >=, ! or = (by default)' to adapt comparaison operator
* @return mixed : Number of line modified
*/
public function update (string $table, array $datas, array $conditions = array()) : int
protected function _update (string $table, array $datas, array $conditions = array()) : int
{
$params = array();
$sets = array();
@ -334,14 +336,14 @@
$wheres = array();
foreach ($conditions as $label => $value)
{
$condition = $this->evaluate_condition($label, $value);
$condition = $this->_evaluate_condition($label, $value);
$wheres[] = $condition['QUERY'];
$params = array_merge($params, $condition['PARAM']);
}
$query = "UPDATE `" . $table . "` SET " . implode(', ', $sets) . " WHERE 1 AND " . implode(' AND ', $wheres);
return $this->run_query($query, $params, self::ROWCOUNT);
return $this->_run_query($query, $params, self::ROWCOUNT);
}
/**
@ -350,20 +352,20 @@
* @param array $conditions : conditions to use, format 'fieldname' => 'value', fieldname can be preceed by operator '<, >, <=, >=, ! or = (by default)' to adapt comparaison operator
* @return mixed : Number of line deleted
*/
public function delete (string $table, array $conditions = []) : int
protected function _delete (string $table, array $conditions = []) : int
{
//On gère les conditions
$wheres = array();
$params = array();
foreach ($conditions as $label => $value)
{
$condition = $this->evaluate_condition($label, $value);
$condition = $this->_evaluate_condition($label, $value);
$wheres[] = $condition['QUERY'];
$params = array_merge($params, $condition['PARAM']);
}
$query = "DELETE FROM `" . $table . "` WHERE 1 AND " . implode(' AND ', $wheres);
return $this->run_query($query, $params, self::ROWCOUNT);
return $this->_run_query($query, $params, self::ROWCOUNT);
}
/**
@ -372,7 +374,7 @@
* @param array $datas : new datas
* @return mixed : null on error, number of line inserted else
*/
public function insert (string $table, array $datas) : ?int
protected function _insert (string $table, array $datas) : ?int
{
$params = array();
$field_names = array();
@ -386,7 +388,7 @@
$query = "INSERT INTO `" . $table . "` (`" . implode('`, `', $field_names) . "`) VALUES(:" . implode(', :', $field_names) . ")";
//On retourne le nombre de lignes insérées
return $this->run_query($query, $params, self::ROWCOUNT);
return $this->_run_query($query, $params, self::ROWCOUNT);
}
}

View File

@ -1,5 +1,7 @@
<?php
/**
namespace descartes;
/**
* Cette classe gère l'appel des ressources
*/
class Router
@ -18,12 +20,12 @@
if (!array_key_exists($controller, ROUTES))
{
throw new DescartesExceptionRouterUrlGenerationError('Try to generate url for controller ' . $controller . ' that did not exist.');
throw new \descartes\exceptions\DescartesExceptionRouterUrlGenerationError('Try to generate url for controller ' . $controller . ' that did not exist.');
}
if (!array_key_exists($method, ROUTES[$controller]))
{
throw new DescartesExceptionRouterUrlGenerationError('Try to generate url for method ' . $controller . '::' . $method . ' that did not exist.');
throw new \descartes\exceptions\DescartesExceptionRouterUrlGenerationError('Try to generate url for method ' . $controller . '::' . $method . ' that did not exist.');
}
$get_params = http_build_query($get_params);
@ -57,7 +59,7 @@
return $url . $route . ($get_params ? '?' . $get_params : '');
}
throw new DescartesExceptionRouterUrlGenerationError('Cannot find any route for ' . $controller . '::' . $method . ' with parameters ' . print_r($params, true));
throw new \descartes\exceptions\DescartesExceptionRouterUrlGenerationError('Cannot find any route for ' . $controller . '::' . $method . ' with parameters ' . print_r($params, true));
}
@ -175,7 +177,7 @@
*/
protected static function compute_method (string $controller, string $method)
{
if (is_subclass_of($controller, 'ApiController'))
if (is_subclass_of($controller, 'descartes\ApiController'))
{
//On va choisir le type à employer
$http_method = $_SERVER['REQUEST_METHOD'];
@ -224,7 +226,7 @@
*/
protected static function compute_params (string $controller, string $method, array $params) : array
{
$reflection = new ReflectionMethod($controller, $method);
$reflection = new \ReflectionMethod($controller, $method);
$method_arguments = [];
foreach ($reflection->getParameters() as $parameter)
@ -286,7 +288,7 @@
*/
public static function error_404 () : void
{
throw new DescartesException404();
throw new \descartes\exceptions\DescartesException404();
}
@ -312,19 +314,19 @@
$controller = static::compute_controller($computed_url['controller']);
if (!$controller)
{
throw new DescartesExceptionRouterInvocationError('Try to call controller ' . $computed_url['controller'] . ' that did not exists.');
throw new \descartes\exceptions\DescartesExceptionRouterInvocationError('Try to call controller ' . $computed_url['controller'] . ' that did not exists.');
}
$method = static::compute_method($controller, $computed_url['method']);
if (!$method)
{
throw new DescartesExceptionRouterInvocationError('Try to call the method ' . $computed_url['method'] . ' that did not exists from controller ' . $controller . '.');
throw new \descartes\exceptions\DescartesExceptionRouterInvocationError('Try to call the method ' . $computed_url['method'] . ' that did not exists from controller ' . $controller . '.');
}
$compute_params_result = static::compute_params($controller, $method, $params);
if (!$compute_params_result['success'])
{
throw new DescartesExceptionRouterInvocationError($compute_params_result['message']);
throw new \descartes\exceptions\DescartesExceptionRouterInvocationError($compute_params_result['message']);
}
$method_arguments = $compute_params_result['method_arguments'];

View File

@ -14,18 +14,11 @@
{
$class = str_replace('\\', '/', $class); #Gestion des namespaces
if (file_exists(PWD . '/descartes/' . $class . '.php'))
{
require_once(PWD . '/descartes/' . $class . '.php');
}
elseif (file_exists(PWD . '/descartes/exceptions/' . $class . '.php'))
{
require_once(PWD . '/descartes/exceptions/' . $class . '.php');
}
elseif (file_exists(PWD . '/' . $class . '.php'))
if (file_exists(PWD . '/' . $class . '.php'))
{
require_once(PWD . '/' . $class . '.php');
}
}
}
spl_autoload_register('autoloader');

View File

@ -1,4 +1,6 @@
<?php
namespace descartes;
/*
* Define Descartes env
*/
@ -6,6 +8,18 @@
$http_protocol = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://';
$http_server_name = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost';
$http_server_port = isset($_SERVER['SERVER_PORT']) ? ($_SERVER['SERVER_PORT'] == 80) ? '' : ':' . $_SERVER['SERVER_PORT'] : '';
$https = $_SERVER['HTTPS'] ?? false;
if ( !isset($_SERVER['SERVER_PORT']) || ($_SERVER['SERVER_PORT'] == 80 && !$https) || ($_SERVER['SERVER_PORT'] === 443 && $https) )
{
$http_server_port = '';
}
else
{
$http_server_port = ':' . $_SERVER['SERVER_PORT'];
}
$pwd = substr(__DIR__, 0, strrpos(__DIR__, '/'));
$http_pwd = $http_protocol . $http_server_name . $http_server_port . $http_dir_path;

1
descartes/exceptions/DescartesException404.php Executable file → Normal file
View File

@ -1,4 +1,5 @@
<?php
namespace descartes\exceptions;
class DescartesException404 extends Exception {};

View File

@ -1,4 +1,5 @@
<?php
namespace descartes\exceptions;
class DescartesExceptionConsoleInvocationError extends Exception {};

View File

@ -1,4 +1,5 @@
<?php
namespace descartes\exceptions;
class DescartesExceptionRouterInvocationError extends Exception {};

View File

@ -1,4 +1,5 @@
<?php
namespace descartes\exceptions;
class DescartesExceptionRouterUrlGenerationError extends Exception {};

View File

@ -1,4 +1,5 @@
<?php
namespace descartes\exceptions;
class DescartesExceptionTemplateNotReadable extends Exception {};

38
descartes/load-environment.php Executable file → Normal file
View File

@ -1,11 +1,21 @@
<?php
namespace descartes;
function define_array ($array)
{
foreach ($array as $key => $value)
{
define(mb_strtoupper($key), $value);
}
}
function load_env ()
{
### DESCARTES ENV ###
$environment = [];
$env = [];
//Load descartes global env
require_once(__DIR__ . '/env.php');
$environment = array_merge($environment, $env);
@ -15,21 +25,23 @@
require_once(__DIR__ . '/../env.descartes.php');
$environment = array_merge($environment, $env);
}
//Load user defined global env
//Define all Descartes constants
define_array($environment);
### GLOBAL ENV ###
$environment = [];
$env = [];
if (file_exists(__DIR__ . '/../env.php'))
{
require_once(__DIR__ . '/../env.php');
$environment = array_merge($environment, $env);
}
//Define all constants
foreach ($environment as $name => $value)
{
define(mb_strtoupper($name), $value);
}
define_array($environment);
//Load user defined env specific env
### SPECIFIC ENV ###
$environment = [];
$env = [];
@ -39,11 +51,7 @@
$environment = array_merge($environment, $env);
}
//Define env specific constants
foreach ($environment as $name => $value)
{
define(mb_strtoupper($name), $value);
}
define_array($environment);
}
load_env();

16
descartes/load.php Executable file
View File

@ -0,0 +1,16 @@
<?php
###############
# ENVIRONMENT #
###############
require_once(__DIR__ . '/load-environment.php');
############
# AUTOLOAD #
############
require_once(PWD . '/descartes/autoload.php');
require_once(PWD . '/vendor/autoload.php');
###########
# ROUTING #
###########
require_once(PWD . '/routes.php'); //Include routes