From 47a05c2b2e7463925a122d768d1497ee6565c833 Mon Sep 17 00:00:00 2001 From: 127 Date: Thu, 19 Dec 2019 16:25:54 +0200 Subject: [PATCH] bin/shpala rewriten --- bin/shpala | 7 + bootstrap.php | 2 +- lib/shpala/base_cache.php | 60 +- lib/shpala/base_controller.php | 98 +-- lib/shpala/base_helpers.php | 4 +- lib/shpala/base_job.php | 23 +- lib/shpala/base_record.php | 909 +++++++++++++------------ lib/shpala/cache/storage_files.php | 230 +++---- lib/shpala/cache/storage_interface.php | 28 +- lib/shpala/database.php | 98 +-- lib/shpala/i18n.php | 66 +- lib/shpala/queue.php | 64 +- lib/shpala/resource.php | 128 ++-- lib/shpala/router.php | 475 +++++++------ lib/shpala/shpala.php | 2 +- lib/shpala/view.php | 198 +++--- lib/tasks/db/structure/task_dump.php | 2 +- lib/tasks/db/task_migrate.php | 2 +- lib/tasks/db/task_seed.php | 2 +- lib/tasks/db/task_version.php | 1 - 20 files changed, 1203 insertions(+), 1196 deletions(-) diff --git a/bin/shpala b/bin/shpala index 78391f4..ba491f8 100755 --- a/bin/shpala +++ b/bin/shpala @@ -33,6 +33,13 @@ $db = new Database(false, false); $db->set_connect($cnf->config['database']); $connect = $db->get_connect(); $dbname = $cnf->config['database']['database']; + +//Minimal setup to use BaseRecord +BaseRecord::$_db_di = $connect; +if(isset($cnf->config['database']['tables_prefix'])) { + BaseRecord::$_prefix_di = $cnf->config['database']['tables_prefix']; +} + require_once $task; exit(0); ?> \ No newline at end of file diff --git a/bootstrap.php b/bootstrap.php index 5c52f5d..8b291ae 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -3,7 +3,7 @@ $GLOBALS['APP_DIR'] = realpath(__DIR__); if($GLOBALS['APP_ENV'] != 'production'){ - $_sig = '/\.(?:png|jpg|jpeg|gif|css|html|htm|ico|js|webmanifest|txt)$/'; + $_sig = '/\.(?:png|jpg|jpeg|gif|css|html|htm|ico|js|webmanifest|txt|json)$/'; if(php_sapi_name() == 'cli-server' && preg_match($_sig, $_SERVER['REQUEST_URI'])) { return false; } diff --git a/lib/shpala/base_cache.php b/lib/shpala/base_cache.php index 6beedf4..cbc40e9 100644 --- a/lib/shpala/base_cache.php +++ b/lib/shpala/base_cache.php @@ -1,35 +1,35 @@ 'files', - 'options'=>[ - 'live'=>3600, - 'path'=>'/tmp/cache/' - ] - ]; - private static $_convention = 'Storage'; - - public static function factory($config=null){ - static::$_defaults['options']['path'] = $GLOBALS['APP_DIR'].static::$_defaults['options']['path']; - $options = static::$_defaults['options']; - $adapter_name = static::$_defaults['adapter']; - if(is_string($config)) { - $adapter_name = $config; - } - if(is_array($config)){ - $adapter_name = isset($config['adapter']) ? $config['adapter'] : $adapter_name; - $options = isset($config['options']) ? array_merge($options, $config['options']) : $options; - } - if ($adapter_name=='') { - die('Missing adapter'); - } - if (static::$adapters === null) { - $_n = static::$_convention.ucfirst($adapter_name); - static::$adapters = new $_n($options); - } - return static::$adapters; - } + protected static $adapters = null; + private static $_defaults = [ + 'adapter'=>'files', + 'options'=>[ + 'live'=>3600, + 'path'=>'/tmp/cache/' + ] + ]; + private static $_convention = 'Storage'; + + public static function factory($config=null){ + static::$_defaults['options']['path'] = $GLOBALS['APP_DIR'].static::$_defaults['options']['path']; + $options = static::$_defaults['options']; + $adapter_name = static::$_defaults['adapter']; + if(is_string($config)) { + $adapter_name = $config; + } + if(is_array($config)){ + $adapter_name = isset($config['adapter']) ? $config['adapter'] : $adapter_name; + $options = isset($config['options']) ? array_merge($options, $config['options']) : $options; + } + if ($adapter_name=='') { + die('Missing adapter'); + } + if (static::$adapters === null) { + $_n = static::$_convention.ucfirst($adapter_name); + static::$adapters = new $_n($options); + } + return static::$adapters; + } } ?> \ No newline at end of file diff --git a/lib/shpala/base_controller.php b/lib/shpala/base_controller.php index 9590ae4..fc35466 100644 --- a/lib/shpala/base_controller.php +++ b/lib/shpala/base_controller.php @@ -1,56 +1,56 @@ resource = $resource; + public $db; + public $view; + public $params; + public $resource; + public $i18n; + private $_render_layout = true; + private $_render_action = true; + + public function __construct(Resource &$resource) { + $this->resource = $resource; - //aliases - $this->db = $resource->connect; - $this->params = $resource->router->params; - $this->view = $resource->view; - - if($resource->i18n){ - $this->i18n = $resource->i18n->strings; - } - if($resource->helpers){ - $this->helpers = $resource->helpers; - } + //aliases + $this->db = $resource->connect; + $this->params = $resource->router->params; + $this->view = $resource->view; + + if($resource->i18n){ + $this->i18n = $resource->i18n->strings; + } + if($resource->helpers){ + $this->helpers = $resource->helpers; + } - $this->call_init(); - return $this; - } - - protected function call_init(){ - if(method_exists($this, 'init')){ - $this->init(); - } + $this->call_init(); + return $this; + } + + protected function call_init(){ + if(method_exists($this, 'init')){ + $this->init(); } - - protected function set_db(&$db){ - $this->db = $db; - } - - public function set_render_layout($flag=true){ - $this->_render_layout = $flag; - } - - public function get_render_layout(){ - return $this->_render_layout; - } - - public function set_render_action($flag=true){ - $this->_render_action = $flag; - } - - public function get_render_action(){ - return $this->_render_action; - } + } + + protected function set_db(&$db){ + $this->db = $db; + } + + public function set_render_layout($flag=true){ + $this->_render_layout = $flag; + } + + public function get_render_layout(){ + return $this->_render_layout; + } + + public function set_render_action($flag=true){ + $this->_render_action = $flag; + } + + public function get_render_action(){ + return $this->_render_action; + } } ?> \ No newline at end of file diff --git a/lib/shpala/base_helpers.php b/lib/shpala/base_helpers.php index 59fa493..4cb4267 100644 --- a/lib/shpala/base_helpers.php +++ b/lib/shpala/base_helpers.php @@ -1,5 +1,3 @@ \ No newline at end of file diff --git a/lib/shpala/base_job.php b/lib/shpala/base_job.php index 02e9a88..ed4beea 100644 --- a/lib/shpala/base_job.php +++ b/lib/shpala/base_job.php @@ -1,16 +1,17 @@ _db = self::$_db_di; - if(method_exists($this, 'init')){ - $this->init(); - } - return $this; - } + public static $_db_di=null; + protected $_db; + + public function __construct() { + if(self::$_db_di!=null){ + $this->_db = self::$_db_di; + } + if(method_exists($this, 'init')){ + $this->init(); + } + return $this; + } } ?> \ No newline at end of file diff --git a/lib/shpala/base_record.php b/lib/shpala/base_record.php index 8e23c22..9d64a2a 100644 --- a/lib/shpala/base_record.php +++ b/lib/shpala/base_record.php @@ -3,463 +3,466 @@ // TODO refactor run() fetchAll // TODO or/in/and methods class BaseRecord { - /* DI public variables */ - public static $_db_di; - public static $_prefix_di; - - /* MODEL basics*/ - protected $_db; - protected $_prefix = ''; - protected $_postfix = 'Model'; - protected $_table; - protected $_columns = []; - protected $_pkey = 'id'; - - /* SQL request builder*/ - private $_proirity = [ - ['select','update','delete'], //,'insert' - ['from'], - ['join'], - ['where'], - ['group','having'], - ['order', 'limit', 'offset'] - ]; - private $_sql_params = []; - private $_sql_string = ''; - private $_sql_binds = []; - - public function __construct() { - $this->_db = self::$_db_di; - $this->_prefix = self::$_prefix_di; - if(!$this->_table){ - $this->_table = $this->_prefix.$this->_decamelize(substr(get_class($this), 0, -(strlen($this->_postfix)))).'s'; - } - foreach ($this->_db->query('DESCRIBE '.$this->_table) as $row) { - $p = $row['Field']; - array_push($this->_columns, $p); - $this->$p = null; - } - $this->call_init(); - return $this; - } - - protected function call_init(){ - if(method_exists($this, 'init')){ - $this->init(); - } + /* DI public variables */ + public static $_db_di; + public static $_prefix_di; + + /* MODEL basics*/ + protected $_db; + protected $_prefix = ''; + protected $_postfix = 'Model'; + protected $_table; + protected $_columns = []; + protected $_pkey = 'id'; + + /* SQL request builder*/ + private $_proirity = [ + ['select','update','delete'], //,'insert' + ['from'], + ['join'], + ['where'], + ['group','having'], + ['order', 'limit', 'offset'] + ]; + private $_sql_params = []; + private $_sql_string = ''; + private $_sql_binds = []; + + public function __construct() { + $this->_db = self::$_db_di; + $this->_prefix = self::$_prefix_di; + if(!$this->_table){ + $this->_table = $this->_prefix.$this->_decamelize(substr(get_class($this), 0, -(strlen($this->_postfix)))).'s'; + } + foreach ($this->_db->query('DESCRIBE '.$this->_table) as $row) { + $p = $row['Field']; + array_push($this->_columns, $p); + $this->$p = null; + } + $this->call_init(); + return $this; + } + + protected function call_init(){ + if(method_exists($this, 'init')){ + $this->init(); } - - public function set_db(&$db){ - $this->_db = $db; - } - - public function get_db(){ - return $this->_db; - } - - public function get_table(){ - return $this->_table; - } - - public function set_pkey(string $key){ - $this->_pkey = $key; - } - - public function get_pkey(){ - return $this->_pkey; - } - - public function set_table(string $table, bool $autoprefix=true){ - $this->_table = ($autoprefix==true) ? $this->_prefix.$table : $table; - } - - public function get_sql_string(){ - return isset($this->_sql_string_debug) ? $this->_sql_string_debug : false; - } - - public function get_sql_binds(){ - return isset($this->_sql_binds_debug) ? $this->_sql_binds_debug : false; - } + } + + public function set_db(&$db){ + $this->_db = $db; + } + + public function get_db(){ + return $this->_db; + } + + public function get_table(){ + return $this->_table; + } + + public function set_pkey(string $key){ + $this->_pkey = $key; + } + + public function get_pkey(){ + return $this->_pkey; + } + + public function set_table(string $table, bool $autoprefix=true){ + $this->_table = ($autoprefix==true) ? $this->_prefix.$table : $table; + } + + public function get_sql_string(){ + return isset($this->_sql_string_debug) ? $this->_sql_string_debug : false; + } + + public function get_sql_binds(){ + return isset($this->_sql_binds_debug) ? $this->_sql_binds_debug : false; + } - // return int rowCount|0 - // TODO ->where & ->order - public function delete($ids=null){ - $this->_sql_params['delete'] = 'DELETE '; - if(is_numeric($ids)){ - $this->where([$this->_pkey=>$ids]); - } - if(is_array($ids)){ - $this->in($this->_pkey, array_map('intval', $ids)); - } - return $this; - } - - //return int lastInsertId - public function create(array $params, bool $ignore=false){ - $s = 'INSERT '; - $s .= ($ignore==false ? '' : 'IGNORE '); - $s .= 'INTO '.$this->_table.' ('; - $s .= implode(', ', array_keys($params)).') VALUES ('; - $s .= implode(', ', array_map(function($k){ - return ':'.$k; - }, array_keys($params))).')'; - $this->_set_debug_and_clean($s, $params); - $stmnt = $this->_db->prepare($s); - $this->_bind_values($stmnt, $params); - $stmnt->execute(); - return (int) $this->_db->lastInsertId(); - } - - // can be used with where and order - public function update(array $params, bool $ignore=false){ - $this->_sql_params['update'] = 'UPDATE '; - $this->_sql_params['update'] .= ($ignore==false ? '' : 'IGNORE '); - $this->_sql_params['update'] .= $this->_table.' SET '; - if($this->_is_assoc($params)){ - $this->_sql_params['update'] .= implode(', ', array_map(function($c, $v){ - $k = $this->_get_alias(); - $this->_sql_binds[$k] = $v; - return $c.'='.$k; - }, array_keys($params), $params) ); - } else { - $tpl = array_shift($params); - foreach($params as $p){ - $k = $this->_get_alias(); - $tpl = preg_replace('/\?/', $k, $tpl, 1); - $this->_sql_binds[$k] = $p; - } - $this->_sql_params['update'] .= $tpl; - } - return $this; - } - - public function find($params){ - if(is_numeric($params)){ - $this->select()->where([$this->_pkey=>$params]); - } - if(is_array($params) && count($params)>0){ - $this->select(); - $s = []; - foreach($params as $v){ - $k = $this->_get_alias(); - $this->_sql_binds[$k] = $v; - $s[]=$k; - } - $this->_sql_params['where'] = 'WHERE '.$this->_pkey.' IN ('.implode(', ', $s).')'; - } - return $this; - } - - public function first(){ - $this->select()->order([$this->_pkey])->limit(1); - return $this; - } - - public function take(int $limit){ - $this->select()->limit($limit); - return $this; - } - - public function select($params=null){ - if($params===null){ - $this->_sql_params['select'] = 'SELECT *'; - } - if(is_string($params)) { - $this->_sql_params['select'] = 'SELECT ' . $params; - } - if(is_array($params) && count($params)>0) { - $this->_sql_params['select'] = 'SELECT ' . implode(', ', $params); - } - return $this; - } - - public function count(string $params, string $as=''){ - if($as!=''){ - $as = ' as '.$as; - } - $this->select('COUNT('.$params.')'.$as); - return $this; - } - - public function distinct(){ - if(isset($this->_sql_params['select'])){ - if(stristr($this->_sql_params['select'], 'COUNT')){ - $this->_sql_params['select'] = preg_replace('/^SELECT COUNT\((\w+)\)/', "SELECT COUNT(DISTINCT $1) ", $this->_sql_params['select']); - } else { - $this->_sql_params['select'] = str_replace('SELECT ', 'SELECT DISTINCT ', $this->_sql_params['select']); - } - } else { - - } - return $this; - } - - public function from(array $tables=null){ - $this->_sql_params['from'] = 'FROM '.($tables!==null ? implode(', ', $tables) : $this->_table); - return $this; - } - - public function joins($params, $type='INNER'){ - if (is_string($params)) { - if(stristr($params, 'JOIN') === false){ - $this->_sql_params['join'] = $type.' JOIN '; - } - $this->_sql_params['join'] .= $params; - } - if(is_array($params) && count($params)>0){ - foreach($params as $table){ - $join_table = $this->_prefix.$table; - $this->_sql_params['join'] .= $type.' JOIN '.$join_table.' ON '.$this->_table.'.'.$this->_pkey.'='.$join_table.'.'.$this->_pkey; - } - } - return $this; - } - - public function in(string $column, array $params){ - if(count($params)>0){ - $_s=[]; - foreach($params as $p){ - $k = $this->_get_alias(); - $this->_sql_binds[$k] = $p; - $_s[] = $k; - } - $this->where($column.' IN ('.implode(', ', $_s).')'); - } - return $this; - } + // return int rowCount|0 + // TODO ->where & ->order + public function delete($ids=null){ + $this->_sql_params['delete'] = 'DELETE '; + if(is_numeric($ids)){ + $this->where([$this->_pkey=>$ids]); + } + if(is_array($ids)){ + $this->in($this->_pkey, array_map('intval', $ids)); + } + return $this; + } + + //return int lastInsertId + public function create(array $params, bool $ignore=false){ + $s = 'INSERT '; + $s .= ($ignore==false ? '' : 'IGNORE '); + $s .= 'INTO '.$this->_table.' ('; + $s .= implode(', ', array_keys($params)).') VALUES ('; + $s .= implode(', ', array_map(function($k){ + return ':'.$k; + }, array_keys($params))).')'; + $this->_set_debug_and_clean($s, $params); + $stmnt = $this->_db->prepare($s); + $this->_bind_values($stmnt, $params); + $stmnt->execute(); + return (int) $this->_db->lastInsertId(); + } + + // can be used with where and order + public function update(array $params, bool $ignore=false){ + $this->_sql_params['update'] = 'UPDATE '; + $this->_sql_params['update'] .= ($ignore==false ? '' : 'IGNORE '); + $this->_sql_params['update'] .= $this->_table.' SET '; + if($this->_is_assoc($params)){ + $this->_sql_params['update'] .= implode(', ', array_map(function($c, $v){ + $k = $this->_get_alias(); + $this->_sql_binds[$k] = $v; + return $c.'='.$k; + }, array_keys($params), $params) ); + } else { + $tpl = array_shift($params); + foreach($params as $p){ + $k = $this->_get_alias(); + $tpl = preg_replace('/\?/', $k, $tpl, 1); + $this->_sql_binds[$k] = $p; + } + $this->_sql_params['update'] .= $tpl; + } + return $this; + } + + public function find($params){ + if(is_numeric($params)){ + $this->select()->where([$this->_pkey=>$params]); + } + if(is_array($params) && count($params)>0){ + $this->select(); + $s = []; + foreach($params as $v){ + $k = $this->_get_alias(); + $this->_sql_binds[$k] = $v; + $s[]=$k; + } + $this->_sql_params['where'] = 'WHERE '.$this->_pkey.' IN ('.implode(', ', $s).')'; + } + return $this; + } + + public function first(){ + $this->select()->order([$this->_pkey])->limit(1); + return $this; + } + + public function take(int $limit){ + $this->select()->limit($limit); + return $this; + } + + public function select($params=null){ + if($params===null){ + $this->_sql_params['select'] = 'SELECT *'; + } + if(is_string($params)) { + $this->_sql_params['select'] = 'SELECT ' . $params; + } + if(is_array($params) && count($params)>0) { + $this->_sql_params['select'] = 'SELECT ' . implode(', ', $params); + } + return $this; + } + + public function count(string $params, string $as=''){ + if($as!=''){ + $as = ' as '.$as; + } + $this->select('COUNT('.$params.')'.$as); + return $this; + } + + public function distinct(){ + if(isset($this->_sql_params['select'])){ + if(stristr($this->_sql_params['select'], 'COUNT')){ + $this->_sql_params['select'] = preg_replace('/^SELECT COUNT\((\w+)\)/', "SELECT COUNT(DISTINCT $1) ", $this->_sql_params['select']); + } else { + $this->_sql_params['select'] = str_replace('SELECT ', 'SELECT DISTINCT ', $this->_sql_params['select']); + } + } else { + + } + return $this; + } + + public function from(array $tables=null){ + $this->_sql_params['from'] = 'FROM '.($tables!==null ? implode(', ', $tables) : $this->_table); + return $this; + } + + public function joins($params, $type='INNER'){ + if(!isset($this->_sql_params['join'])){ + $this->_sql_params['join'] = ''; + } + if (is_string($params)) { + if(stristr($params, 'JOIN') === false){ + $this->_sql_params['join'] = $type.' JOIN '; + } + $this->_sql_params['join'] .= $params; + } + if(is_array($params) && count($params)>0){ + foreach($params as $table){ + $join_table = $this->_prefix.$table; + $this->_sql_params['join'] .= $type.' JOIN '.$join_table.' ON '.$this->_table.'.'.$this->_pkey.'='.$join_table.'.'.$this->_pkey; + } + } + return $this; + } + + public function in(string $column, array $params){ + if(count($params)>0){ + $_s=[]; + foreach($params as $p){ + $k = $this->_get_alias(); + $this->_sql_binds[$k] = $p; + $_s[] = $k; + } + $this->where($column.' IN ('.implode(', ', $_s).')'); + } + return $this; + } - public function not($params){ - //User.where.not("name = 'Jon'") - // # SELECT * FROM users WHERE NOT (name = 'Jon') - if(is_string($params)){ - $this->where('NOT ('.$params.')'); - } - if(is_array($params)){ - $_cnt = count($params); - if($_cnt==1){ - $column = (array_keys($params))[0]; - } - // User.where.not(name: %w(Ko1 Nobu)) - // # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu') - if($_cnt==1 && is_array($params[$column])){ - $_s=[]; - foreach($params[$column] as $p){ - $k = $this->_get_alias(); - $_s[]=$k; - $this->_sql_binds[$k] = $p; - } - $this->where($column.' NOT IN ('.implode(', ', $_s).')'); - } - - // User.where.not(name: nil) - // # SELECT * FROM users WHERE name IS NOT NULL - if($_cnt==1 && $params[$column]==null){ - $this->where($column.' IS NOT NULL'); - } - - // User.where.not(name: "Jon") - // # SELECT * FROM users WHERE name != 'Jon' - if($_cnt==1 && !is_array($params[$column]) && $params[$column]!=null){ - $k = $this->_get_alias(); - $this->_sql_binds[$k] = $params[$column]; - $this->where($column.'!='.$k); - } - - // User.where.not(name: "Jon", role: "admin") - // # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin' - if($_cnt>1){ - $_s = []; - foreach($params as $k=>$v){ - $n = $this->_get_alias(); - $this->_sql_binds[$n] = $v; - $_s[] = $k.'!='.$n; - } - $this->where(implode(' AND ', $_s)); - } - } - return $this; - } - - public function or(){ - return $this; - } - - public function where($params=null){ - if(!isset($this->_sql_params['where'])){ - $this->_sql_params['where'] = 'WHERE '; - } else { - $this->_sql_params['where'] .= ' AND '; - } - if(!isset($params)) { - return $this; - } - if (is_string($params)){ - $this->_sql_params['where'] .= $params; - } - if(is_array($params) && count($params)>0){ - if($this->_is_assoc($params)){ - $this->_sql_params['where'] .= implode(' AND ', array_map(function($c, $v){ - $k = $this->_get_alias(); - $this->_sql_binds[$k] = $v; - return $c.'='.$k; - }, array_keys($params), $params) ); - } else { - $tpl = array_shift($params); - foreach($params as $p){ - $k = $this->_get_alias(); - $tpl = preg_replace('/\?/', $k, $tpl, 1); - $this->_sql_binds[$k] = $p; - } - $this->_sql_params['where'] .= $tpl; - } - } - return $this; - } - - //PDO fails to pass symols on order - public function order($params){ - $this->_sql_params['order'] = 'ORDER BY '; - if(is_string($params)){ - $this->_sql_params['order'] .= $params; - } - if(is_array($params) && count($params)>0) { - $this->_sql_params['order'] .= implode(', ', array_map(function($k, $v){ - $key = is_numeric($k) ? $v : $k; - $val = is_numeric($k) ? 'ASC' : $v; - return $key.' '.$val; - }, array_keys($params), $params) ); - } - return $this; - } - - public function group($params){ - $this->_sql_params['group'] = 'GROUP BY '; - if(is_string($params)){ - $this->_sql_params['group'] .= $params; - } - if(is_array($params) && count($params)>0){ - $this->_sql_params['group'] .= implode(', ', $params); - } - return $this; - } - - public function having($params){ - // if(!isset($this->_sql_params['group']) check if order section isset - $this->_sql_params['having'] = 'HAVING '; - if(is_string($params)){ - $this->_sql_params['having'] .= $params; - } - if(is_array($params) && count($params)>0){ - $tpl = array_shift($params); - foreach($params as $p){ - $k = $this->_get_alias(); - $tpl = preg_replace('/\?/', $k, $tpl, 1); - $this->_sql_binds[$k] = $p; - } - $this->_sql_params['having'] .= $tpl; - } - return $this; - } - - public function limit(int $limit){ - $k = $this->_get_alias(); - $this->_sql_params['limit'] = 'LIMIT '.$k; - $this->_sql_binds[$k] = $limit; - return $this; - } - - public function offset(int $offset){ - $k = $this->_get_alias(); - $this->_sql_params['offset'] = 'OFFSET '.$k; - $this->_sql_binds[$k] = $offset; - return $this; - } - - public function run(){ - if(count(array_intersect($this->_proirity[0], array_keys($this->_sql_params)))==0){ - $this->select(); - } - if(!isset($this->_sql_params['from']) && !isset($this->_sql_params['update'])){ - $this->from(); - } - foreach($this->_proirity as $part){ - foreach($part as $v){ - if(isset($this->_sql_params[$v])){ - $this->_sql_string .= $this->_sql_params[$v].' '; - } - } - } - try { - $stmnt = $this->_db->prepare($this->_sql_string); - $this->_bind_values($stmnt, $this->_sql_binds); - $stmnt->execute(); - if(isset($this->_sql_params['update']) || isset($this->_sql_params['delete'])){ - $r = $stmnt->rowCount(); - } else { - $r = $stmnt->fetchAll(PDO::FETCH_ASSOC); - } - $this->_cleanup(); - return $r; - } catch(PDOException $e) { - print_r($e->getMessage()); - $this->_cleanup(); - } + public function not($params){ + //User.where.not("name = 'Jon'") + // # SELECT * FROM users WHERE NOT (name = 'Jon') + if(is_string($params)){ + $this->where('NOT ('.$params.')'); + } + if(is_array($params)){ + $_cnt = count($params); + if($_cnt==1){ + $column = (array_keys($params))[0]; + } + // User.where.not(name: %w(Ko1 Nobu)) + // # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu') + if($_cnt==1 && is_array($params[$column])){ + $_s=[]; + foreach($params[$column] as $p){ + $k = $this->_get_alias(); + $_s[]=$k; + $this->_sql_binds[$k] = $p; + } + $this->where($column.' NOT IN ('.implode(', ', $_s).')'); + } + + // User.where.not(name: nil) + // # SELECT * FROM users WHERE name IS NOT NULL + if($_cnt==1 && $params[$column]==null){ + $this->where($column.' IS NOT NULL'); + } + + // User.where.not(name: "Jon") + // # SELECT * FROM users WHERE name != 'Jon' + if($_cnt==1 && !is_array($params[$column]) && $params[$column]!=null){ + $k = $this->_get_alias(); + $this->_sql_binds[$k] = $params[$column]; + $this->where($column.'!='.$k); + } + + // User.where.not(name: "Jon", role: "admin") + // # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin' + if($_cnt>1){ + $_s = []; + foreach($params as $k=>$v){ + $n = $this->_get_alias(); + $this->_sql_binds[$n] = $v; + $_s[] = $k.'!='.$n; + } + $this->where(implode(' AND ', $_s)); + } + } + return $this; + } + + public function or(){ + return $this; + } + + public function where($params=null){ + if(!isset($this->_sql_params['where'])){ + $this->_sql_params['where'] = 'WHERE '; + } else { + $this->_sql_params['where'] .= ' AND '; + } + if(!isset($params)) { + return $this; + } + if (is_string($params)){ + $this->_sql_params['where'] .= $params; + } + if(is_array($params) && count($params)>0){ + if($this->_is_assoc($params)){ + $this->_sql_params['where'] .= implode(' AND ', array_map(function($c, $v){ + $k = $this->_get_alias(); + $this->_sql_binds[$k] = $v; + return $c.'='.$k; + }, array_keys($params), $params) ); + } else { + $tpl = array_shift($params); + foreach($params as $p){ + $k = $this->_get_alias(); + $tpl = preg_replace('/\?/', $k, $tpl, 1); + $this->_sql_binds[$k] = $p; + } + $this->_sql_params['where'] .= $tpl; + } + } + return $this; + } + + //PDO fails to pass symols on order + public function order($params){ + $this->_sql_params['order'] = 'ORDER BY '; + if(is_string($params)){ + $this->_sql_params['order'] .= $params; + } + if(is_array($params) && count($params)>0) { + $this->_sql_params['order'] .= implode(', ', array_map(function($k, $v){ + $key = is_numeric($k) ? $v : $k; + $val = is_numeric($k) ? 'ASC' : $v; + return $key.' '.$val; + }, array_keys($params), $params) ); + } + return $this; + } + + public function group($params){ + $this->_sql_params['group'] = 'GROUP BY '; + if(is_string($params)){ + $this->_sql_params['group'] .= $params; + } + if(is_array($params) && count($params)>0){ + $this->_sql_params['group'] .= implode(', ', $params); + } + return $this; + } + + public function having($params){ + // if(!isset($this->_sql_params['group']) check if order section isset + $this->_sql_params['having'] = 'HAVING '; + if(is_string($params)){ + $this->_sql_params['having'] .= $params; + } + if(is_array($params) && count($params)>0){ + $tpl = array_shift($params); + foreach($params as $p){ + $k = $this->_get_alias(); + $tpl = preg_replace('/\?/', $k, $tpl, 1); + $this->_sql_binds[$k] = $p; + } + $this->_sql_params['having'] .= $tpl; + } + return $this; + } + + public function limit(int $limit){ + $k = $this->_get_alias(); + $this->_sql_params['limit'] = 'LIMIT '.$k; + $this->_sql_binds[$k] = $limit; + return $this; + } + + public function offset(int $offset){ + $k = $this->_get_alias(); + $this->_sql_params['offset'] = 'OFFSET '.$k; + $this->_sql_binds[$k] = $offset; + return $this; + } + + public function run(){ + if(count(array_intersect($this->_proirity[0], array_keys($this->_sql_params)))==0){ + $this->select(); + } + if(!isset($this->_sql_params['from']) && !isset($this->_sql_params['update'])){ + $this->from(); + } + foreach($this->_proirity as $part){ + foreach($part as $v){ + if(isset($this->_sql_params[$v])){ + $this->_sql_string .= $this->_sql_params[$v].' '; + } + } + } + try { + $stmnt = $this->_db->prepare($this->_sql_string); + $this->_bind_values($stmnt, $this->_sql_binds); + $stmnt->execute(); + if(isset($this->_sql_params['update']) || isset($this->_sql_params['delete'])){ + $r = $stmnt->rowCount(); + } else { + $r = $stmnt->fetchAll(PDO::FETCH_ASSOC); + } + $this->_cleanup(); + return $r; + } catch(PDOException $e) { + print_r($e->getMessage()); + $this->_cleanup(); + } - } - - private function _bind_values(PDOStatement &$stmnt, array $values){ - if(count($values)==0){ - return $stmnt; - } - foreach($values as $k=>$v){ - switch( true ) { - case is_numeric($v): - $type = PDO::PARAM_INT; - break; - case is_bool($v): - $type = PDO::PARAM_BOOL; - break; - case is_null($v): - $type = PDO::PARAM_NULL; - break; - default: - $type = PDO::PARAM_STR; - } - $stmnt->bindValue($k, $v, $type); - } - return $stmnt; - } - - private function _get_alias(){ - return ':'.count($this->_sql_binds); - } - - private function _is_assoc(array $arr){ - if(array()===$arr){ - return false; - } - return array_keys($arr) !== range(0, count($arr) - 1); - } - - private function _cleanup(){ - $this->_sql_params_debug = $this->_sql_params; - $this->_sql_string_debug = $this->_sql_string; - $this->_sql_binds_debug = $this->_sql_binds; - $this->_sql_params = []; - $this->_sql_string = ''; - $this->_sql_binds = []; - } - - private function _set_debug_and_clean(string $string, $params){ - $this->_sql_string = $string; - $this->_sql_binds = is_array($params) ? $params : [$params]; - $this->_cleanup(); - } - - private function _decamelize(string $input){ - return strtolower(preg_replace('/(?$v){ + switch(true){ + case is_numeric($v): + $type = PDO::PARAM_INT; + break; + case is_bool($v): + $type = PDO::PARAM_BOOL; + break; + case is_null($v): + $type = PDO::PARAM_NULL; + break; + default: + $type = PDO::PARAM_STR; + } + $stmnt->bindValue($k, $v, $type); + } + return $stmnt; + } + + private function _get_alias(){ + return ':'.count($this->_sql_binds); + } + + private function _is_assoc(array $arr){ + if(array()===$arr){ + return false; + } + return array_keys($arr) !== range(0, count($arr) - 1); + } + + private function _cleanup(){ + $this->_sql_params_debug = $this->_sql_params; + $this->_sql_string_debug = $this->_sql_string; + $this->_sql_binds_debug = $this->_sql_binds; + $this->_sql_params = []; + $this->_sql_string = ''; + $this->_sql_binds = []; + } + + private function _set_debug_and_clean(string $string, $params){ + $this->_sql_string = $string; + $this->_sql_binds = is_array($params) ? $params : [$params]; + $this->_cleanup(); + } + + private function _decamelize(string $input){ + return strtolower(preg_replace('/(? \ No newline at end of file diff --git a/lib/shpala/cache/storage_files.php b/lib/shpala/cache/storage_files.php index b698e68..e88454d 100644 --- a/lib/shpala/cache/storage_files.php +++ b/lib/shpala/cache/storage_files.php @@ -1,123 +1,123 @@ options = $options; - if (!is_readable($this->options['path'])) { - die("Cache dir is not readable"); - } - if (!is_writable($this->options['path'])) { - die("Cache dir is not writable"); - } - } - - public function set_options(array $options){ - $this->options = array_merge($this->options, $options); - } - - public function get_options(){ - return $this->options; - } - - public function get_item(string $key){ - return $this->_read($key); - } - - // public function get_items(array $keys){ - // - // } - - public function has_item(string $key){ - $file = $this->options['path'].$key; - $status = file_exists($file); - if($status==true){ - if($this->_invalidate($file)==true){ - return false; - } - } - return $status; - } - - // public function has_items(array $keys){ - // - // } - - public function set_item(string $key, string $value){ - // if($this->has_item($key)==true){ - return $this->_write($key, $value); - // } - // return false; + + private $options=[]; + + public function __construct(array $options) { + $this->options = $options; + if (!is_readable($this->options['path'])) { + die("Cache dir is not readable"); + } + if (!is_writable($this->options['path'])) { + die("Cache dir is not writable"); + } + } + + public function set_options(array $options){ + $this->options = array_merge($this->options, $options); + } + + public function get_options(){ + return $this->options; + } + + public function get_item(string $key){ + return $this->_read($key); + } + + // public function get_items(array $keys){ + // + // } + + public function has_item(string $key){ + $file = $this->options['path'].$key; + $status = file_exists($file); + if($status==true){ + if($this->_invalidate($file)==true){ + return false; + } + } + return $status; + } + + // public function has_items(array $keys){ + // + // } + + public function set_item(string $key, string $value){ + // if($this->has_item($key)==true){ + return $this->_write($key, $value); + // } + // return false; + } + + // public function set_items(array $keyValuePairs){ + // + // } + + // public function add_item(string $key, string $value){ + // if($this->has_item($key)==false){ + // return $this->_write($key, $value); + // } + // return false; + // } + + // public function add_items(array $keyValuePairs){ + // + // } + + public function remove_item(string $key){ + $this->_delete($key); + } + + // public function remove_items(array $keys){ + // + // } + + public function flush(){ + + } + + private function _read(string $key){ + $file = $this->options['path'].$key; + if(file_exists($file)){ + if($this->_invalidate($file)==true){ + return false; + } + } + if (!is_readable($file)) { + die("File is not readable $file"); + } + return file_get_contents($file); + } + + private function _write(string $key, string $value){ + $file = $this->options['path'].$key; + if(file_exists($file)){ + if($this->_invalidate($file)==true){ + return false; + } } - - // public function set_items(array $keyValuePairs){ - // - // } - - // public function add_item(string $key, string $value){ - // if($this->has_item($key)==false){ - // return $this->_write($key, $value); - // } - // return false; - // } - - // public function add_items(array $keyValuePairs){ - // - // } - - public function remove_item(string $key){ - $this->_delete($key); + if (!$handle = fopen($file, 'w')) { + die("Cannot open/create file ($file)"); } - - // public function remove_items(array $keys){ - // - // } + if (fwrite($handle, $value) === false) { + die("Cannot write to file ($filename)"); + } + fclose($handle); + return true; + } + + private function _delete(string $key){ + return unlink($this->options['path'].$key); + } - public function flush(){ - + private function _invalidate(string $file){ + if( (time()-filectime($file)) > $this->options['live']){ + return unlink($file); } - - private function _read(string $key){ - $file = $this->options['path'].$key; - if(file_exists($file)){ - if($this->_invalidate($file)==true){ - return false; - } - } - if (!is_readable($file)) { - die("File is not readable $file"); - } - return file_get_contents($file); - } - - private function _write(string $key, string $value){ - $file = $this->options['path'].$key; - if(file_exists($file)){ - if($this->_invalidate($file)==true){ - return false; - } - } - if (!$handle = fopen($file, 'w')) { - die("Cannot open/create file ($file)"); - } - if (fwrite($handle, $value) === false) { - die("Cannot write to file ($filename)"); - } - fclose($handle); - return true; - } - - private function _delete(string $key){ - return unlink($this->options['path'].$key); - } - - private function _invalidate(string $file){ - if( (time()-filectime($file)) > $this->options['live']){ - return unlink($file); - } - return false; - } - + return false; + } + } ?> \ No newline at end of file diff --git a/lib/shpala/cache/storage_interface.php b/lib/shpala/cache/storage_interface.php index 8d20e92..248547a 100644 --- a/lib/shpala/cache/storage_interface.php +++ b/lib/shpala/cache/storage_interface.php @@ -1,18 +1,18 @@ \ No newline at end of file diff --git a/lib/shpala/database.php b/lib/shpala/database.php index f7e4558..288c267 100644 --- a/lib/shpala/database.php +++ b/lib/shpala/database.php @@ -2,54 +2,56 @@ // TODO total refactor errors with //https://gist.github.com/jonahlyn/1186647 class Database { - private $_dbc; - private $_config; - private $_error = false; - // private $_error = 'Cannot connect to the database: '; - - public function __construct ($config=false, $set_default_db=true) { - if($config!=false) { - $this->set_connect($config); - if($set_default_db==true) - $this->set_db(); - } - } - - public function set_connect(array &$config, $interface='pdo'){ - $this->_config = $config; - if ($interface=='mysqli') { - $this->_dbc = mysqli_connect($config['host'].':'.$conf['port'], $config['username'], $config['password']) or die(mysqli_error()); - } else { - try { - $_srv = "{$config['driver']}:host={$config['host']}:{$config['port']}"; - $this->_dbc = isset($config['options']) - ? new PDO ($_srv, $config['username'], $config['password'], $config['options']) - : new PDO ($_srv, $config['username'], $config['password']); - return $this->_dbc; - } catch (PDOException $e) { - die($e->getMessage()); - } - } - } - - public function set_db($dbname=false){ - if($dbname==false) - $dbname = $this->_config['database']; - $this->_dbc->exec("use {$dbname}"); - return $this; - } - - public function get_db(){ - return $this->_dbc->query('select database()')->fetchColumn(); - } - - public function get_config(){ - return $this->_config; - } - - public function get_connect (){ - return $this->_dbc; - } + private $_dbc; + private $_config; + private $_error = false; + // private $_error = 'Cannot connect to the database: '; + + public function __construct ($config=false, $set_default_db=true) { + if($config!=false) { + $this->set_connect($config); + if($set_default_db==true){ + $this->set_db(); + } + } + } + + public function set_connect(array &$config, $interface='pdo'){ + $this->_config = $config; + if ($interface=='mysqli') { + $this->_dbc = mysqli_connect($config['host'].':'.$conf['port'], $config['username'], $config['password']) or die(mysqli_error()); + } else { + try { + $_srv = "{$config['driver']}:host={$config['host']}:{$config['port']}"; + $this->_dbc = isset($config['options']) + ? new PDO ($_srv, $config['username'], $config['password'], $config['options']) + : new PDO ($_srv, $config['username'], $config['password']); + return $this->_dbc; + } catch (PDOException $e) { + die($e->getMessage()); + } + } + } + + public function set_db($dbname=false){ + if($dbname==false) { + $dbname = $this->_config['database']; + } + $this->_dbc->exec("use {$dbname}"); + return $this; + } + + public function get_db(){ + return $this->_dbc->query('select database()')->fetchColumn(); + } + + public function get_config(){ + return $this->_config; + } + + public function get_connect (){ + return $this->_dbc; + } } ?> \ No newline at end of file diff --git a/lib/shpala/i18n.php b/lib/shpala/i18n.php index daeffa8..6577891 100644 --- a/lib/shpala/i18n.php +++ b/lib/shpala/i18n.php @@ -1,36 +1,36 @@ locale = ($this->locale===null && $locale!==false) ? $locale : self::$default_locale; - $file = $GLOBALS['APP_DIR'].$this->_dir.$this->locale.'.php'; - if(file_exists($file)){ - $this->strings = $this->_flatten((require_once($file))[$this->locale]); - } - } - - public function _t(string $el){ - return isset($this->strings[$el]) ? $this->strings[$el] : false; - } - - protected function _flatten($array, $prefix = '') { - $result = array(); - foreach($array as $key=>$value) { - if(is_array($value)) { - $result = $result + $this->_flatten($value, $prefix . $key . '.'); - } - else { - $result[$prefix . $key] = $value; - } - } - return $result; - } - -} - + public static $default_locale= 'en'; + public $locale=null; + public $strings=[]; + protected $_dir = '/config/locale/'; + protected $_separator = '.'; + + public function __construct($locale=false) { + $this->locale = ($this->locale===null && $locale!==false) ? $locale : self::$default_locale; + $file = $GLOBALS['APP_DIR'].$this->_dir.$this->locale.'.php'; + if(file_exists($file)){ + $this->strings = $this->_flatten((require_once($file))[$this->locale]); + } + } + + public function _t(string $el){ + return isset($this->strings[$el]) ? $this->strings[$el] : false; + } + + protected function _flatten($array, $prefix = '') { + $result = array(); + foreach($array as $key=>$value) { + if(is_array($value)) { + $result = $result + $this->_flatten($value, $prefix . $key . '.'); + } + else { + $result[$prefix . $key] = $value; + } + } + return $result; + } + +} + ?> \ No newline at end of file diff --git a/lib/shpala/queue.php b/lib/shpala/queue.php index 16f8dd5..3810dad 100644 --- a/lib/shpala/queue.php +++ b/lib/shpala/queue.php @@ -3,37 +3,37 @@ // abstract class+interfaces to implement queue // class Queue { - private $_timer = '/tmp/jobs/.timer'; - private $_timer_error_message = 'touch timer failed'; - private $_jobs_dir = '/app/jobs/'; - private $_queue = []; - private $_intval = 3;//3600*1; //1 hour default - - public function __construct() { - $this->_timer = $GLOBALS['APP_DIR'].$this->_timer; - $this->_jobs_dir = $GLOBALS['APP_DIR'].$this->_jobs_dir; - $this->_queue = array_slice(scandir($this->_jobs_dir), 3); - if(file_exists($this->_timer)){ - if( (time()-filectime($this->_timer)) > $this->_intval){ - touch($this->_timer) or die($this->_timer_error_message); - foreach ($this->_queue as $filename) { - $f = pathinfo($filename); - if($f['extension'] == 'php'){ - $class = $this->camelize($f['filename']); - new $class(); - } - } - } - } else { - touch($this->_timer) or die($this->_timer_error_message); - } - return $this; - } - - - public function camelize($str, $delimiter='_'){ - return str_replace($delimiter, '', ucwords(strtolower($str), $delimiter)); - } - + private $_timer = '/tmp/jobs/.timer'; + private $_timer_error_message = 'touch timer failed'; + private $_jobs_dir = '/app/jobs/'; + private $_queue = []; + private $_intval = 3;//3600*1; //1 hour default + + public function __construct() { + $this->_timer = $GLOBALS['APP_DIR'].$this->_timer; + $this->_jobs_dir = $GLOBALS['APP_DIR'].$this->_jobs_dir; + $this->_queue = array_slice(scandir($this->_jobs_dir), 3); + if(file_exists($this->_timer)){ + if( (time()-filectime($this->_timer)) > $this->_intval){ + touch($this->_timer) or die($this->_timer_error_message); + foreach ($this->_queue as $filename) { + $f = pathinfo($filename); + if($f['extension'] == 'php'){ + $class = $this->camelize($f['filename']); + new $class(); + } + } + } + } else { + touch($this->_timer) or die($this->_timer_error_message); + } + return $this; + } + + + public function camelize($str, $delimiter='_'){ + return str_replace($delimiter, '', ucwords(strtolower($str), $delimiter)); + } + } ?> diff --git a/lib/shpala/resource.php b/lib/shpala/resource.php index 011086f..1f27666 100644 --- a/lib/shpala/resource.php +++ b/lib/shpala/resource.php @@ -1,73 +1,71 @@ name = $router->current_resource; - $this->router = $router; + $this->name = $router->current_resource; + $this->router = $router; $this->config = $config; - if(isset($translate)) { - $this->i18n = $translate; - } - if(isset($connect)){ - $this->connect = $connect; - } - if(isset($helpers)){ - $this->helpers = $helpers; - } - } - - public function build(){ - //=========JOBS============// - if($this->connect!=null){ - BaseJob::$_db_di = $this->connect; - } - new Queue(); - //=========APP============// - $this->controller = new $this->router->controller_class($this); - } - - public function validate_resource(){ - // if(!in_array($this->name, $this->router->resources)){ - // if(!isset($this->router->resources[$this->name])){ - // $this->errors['no_resource_identified'] = true; - // } - // } - if (!class_exists($this->router->controller_class)){ - $this->errors['controller_class_not_exists'] = true; - } - if (!method_exists($this->router->controller_class, $this->router->action_method)){ - $this->errors['action_method_not_exists'] = true; - } - return (count($this->errors)==0) ? true : false; - } + if(isset($translate)) { + $this->i18n = $translate; + } + if(isset($connect)){ + $this->connect = $connect; + } + if(isset($helpers)){ + $this->helpers = $helpers; + } + } + + public function build(){ + //=========JOBS============// + if($this->connect!=null){ + BaseJob::$_db_di = $this->connect; + } + new Queue(); + //=========APP============// + $this->controller = new $this->router->controller_class($this); + } + + public function validate_resource(){ + // if(!in_array($this->name, $this->router->resources)){ + // if(!isset($this->router->resources[$this->name])){ + // $this->errors['no_resource_identified'] = true; + // } + // } + if (!class_exists($this->router->controller_class)){ + $this->errors['controller_class_not_exists'] = true; + } + if (!method_exists($this->router->controller_class, $this->router->action_method)){ + $this->errors['action_method_not_exists'] = true; + } + return (count($this->errors)==0) ? true : false; + } - - public function run(){ - $action = $this->router->action_method; - $this->controller->$action(); - } - - public function init_view(){ - $this->view = new View($this); - } - - + + public function run(){ + $action = $this->router->action_method; + $this->controller->$action(); + } + + public function init_view(){ + $this->view = new View($this); + } } ?> \ No newline at end of file diff --git a/lib/shpala/router.php b/lib/shpala/router.php index 7034e5e..f04a8a7 100644 --- a/lib/shpala/router.php +++ b/lib/shpala/router.php @@ -1,247 +1,246 @@ 'HTTP/1.1 100 Continue', - 101 => 'HTTP/1.1 101 Switching Protocols', - 200 => 'HTTP/1.1 200 OK', - 201 => 'HTTP/1.1 201 Created', - 202 => 'HTTP/1.1 202 Accepted', - 203 => 'HTTP/1.1 203 Non-Authoritative Information', - 204 => 'HTTP/1.1 204 No Content', - 205 => 'HTTP/1.1 205 Reset Content', - 206 => 'HTTP/1.1 206 Partial Content', - 300 => 'HTTP/1.1 300 Multiple Choices', - 301 => 'HTTP/1.1 301 Moved Permanently', - 302 => 'HTTP/1.1 302 Found', - 303 => 'HTTP/1.1 303 See Other', - 304 => 'HTTP/1.1 304 Not Modified', - 305 => 'HTTP/1.1 305 Use Proxy', - 307 => 'HTTP/1.1 307 Temporary Redirect', - 400 => 'HTTP/1.1 400 Bad Request', - 401 => 'HTTP/1.1 401 Unauthorized', - 402 => 'HTTP/1.1 402 Payment Required', - 403 => 'HTTP/1.1 403 Forbidden', - 404 => 'HTTP/1.1 404 Not Found', - 405 => 'HTTP/1.1 405 Method Not Allowed', - 406 => 'HTTP/1.1 406 Not Acceptable', - 407 => 'HTTP/1.1 407 Proxy Authentication Required', - 408 => 'HTTP/1.1 408 Request Time-out', - 409 => 'HTTP/1.1 409 Conflict', - 410 => 'HTTP/1.1 410 Gone', - 411 => 'HTTP/1.1 411 Length Required', - 412 => 'HTTP/1.1 412 Precondition Failed', - 413 => 'HTTP/1.1 413 Request Entity Too Large', - 414 => 'HTTP/1.1 414 Request-URI Too Large', - 415 => 'HTTP/1.1 415 Unsupported Media Type', - 416 => 'HTTP/1.1 416 Requested Range Not Satisfiable', - 417 => 'HTTP/1.1 417 Expectation Failed', - 500 => 'HTTP/1.1 500 Internal Server Error', - 501 => 'HTTP/1.1 501 Not Implemented', - 502 => 'HTTP/1.1 502 Bad Gateway', - 503 => 'HTTP/1.1 503 Service Unavailable', - 504 => 'HTTP/1.1 504 Gateway Time-out', - 505 => 'HTTP/1.1 505 HTTP Version Not Supported', - ]; - - public function __construct(array &$config) { - if(!isset($config['root'])) { - die('Set app root controller and action!'); - } - if(!isset($config['resources'])) { - die('No resources in app!'); - } - - $this->resources = $config['resources']; - $_l_ = explode(static::get_separator(), $config['root']); - static::set_root_controller($_l_[0]); - static::set_root_action($_l_[1]); - - //set up defaults by url + public $controller_class; + public $action_method; + public $params = []; + public $resources; + public $current_resource; + private static $_root_controller; + private static $_root_action; + private static $_controller_postfix = 'Controller'; + private static $_action_postfix = 'Action'; + private static $_sep_ = '#'; + private static $_default_action = 'index'; + private static $_routing_table; + private static $_http = [ + 100 => 'HTTP/1.1 100 Continue', + 101 => 'HTTP/1.1 101 Switching Protocols', + 200 => 'HTTP/1.1 200 OK', + 201 => 'HTTP/1.1 201 Created', + 202 => 'HTTP/1.1 202 Accepted', + 203 => 'HTTP/1.1 203 Non-Authoritative Information', + 204 => 'HTTP/1.1 204 No Content', + 205 => 'HTTP/1.1 205 Reset Content', + 206 => 'HTTP/1.1 206 Partial Content', + 300 => 'HTTP/1.1 300 Multiple Choices', + 301 => 'HTTP/1.1 301 Moved Permanently', + 302 => 'HTTP/1.1 302 Found', + 303 => 'HTTP/1.1 303 See Other', + 304 => 'HTTP/1.1 304 Not Modified', + 305 => 'HTTP/1.1 305 Use Proxy', + 307 => 'HTTP/1.1 307 Temporary Redirect', + 400 => 'HTTP/1.1 400 Bad Request', + 401 => 'HTTP/1.1 401 Unauthorized', + 402 => 'HTTP/1.1 402 Payment Required', + 403 => 'HTTP/1.1 403 Forbidden', + 404 => 'HTTP/1.1 404 Not Found', + 405 => 'HTTP/1.1 405 Method Not Allowed', + 406 => 'HTTP/1.1 406 Not Acceptable', + 407 => 'HTTP/1.1 407 Proxy Authentication Required', + 408 => 'HTTP/1.1 408 Request Time-out', + 409 => 'HTTP/1.1 409 Conflict', + 410 => 'HTTP/1.1 410 Gone', + 411 => 'HTTP/1.1 411 Length Required', + 412 => 'HTTP/1.1 412 Precondition Failed', + 413 => 'HTTP/1.1 413 Request Entity Too Large', + 414 => 'HTTP/1.1 414 Request-URI Too Large', + 415 => 'HTTP/1.1 415 Unsupported Media Type', + 416 => 'HTTP/1.1 416 Requested Range Not Satisfiable', + 417 => 'HTTP/1.1 417 Expectation Failed', + 500 => 'HTTP/1.1 500 Internal Server Error', + 501 => 'HTTP/1.1 501 Not Implemented', + 502 => 'HTTP/1.1 502 Bad Gateway', + 503 => 'HTTP/1.1 503 Service Unavailable', + 504 => 'HTTP/1.1 504 Gateway Time-out', + 505 => 'HTTP/1.1 505 HTTP Version Not Supported']; + + public function __construct(array &$config) { + if(!isset($config['root'])) { + die('Set app root controller and action!'); + } + if(!isset($config['resources'])) { + die('No resources in app!'); + } + + $this->resources = $config['resources']; + $_l_ = explode(static::get_separator(), $config['root']); + static::set_root_controller($_l_[0]); + static::set_root_action($_l_[1]); + + //set up defaults by url $_params_pos = strpos($_SERVER['REQUEST_URI'], '?'); $request = !$_params_pos ? $_SERVER['REQUEST_URI'] : substr($_SERVER['REQUEST_URI'], 0, $_params_pos); - $url = explode('/', $request); - $this->params['controller'] = ($url[1]!=false) ? $url[1] : static::get_root_controller(); - $this->params['action'] = (isset($url[2]) && $url[2]!=false) ? $url[2] : static::get_default_action(); - if(in_array($this->params['controller'], $this->resources)){ - $this->current_resource = $this->params['controller']; - } + $url = explode('/', $request); + $this->params['controller'] = ($url[1]!=false) ? $url[1] : static::get_root_controller(); + $this->params['action'] = (isset($url[2]) && $url[2]!=false) ? $url[2] : static::get_default_action(); + if(in_array($this->params['controller'], $this->resources)){ + $this->current_resource = $this->params['controller']; + } - // map to routing config requested controller and action - static::set_routes_table($this->resources); - // $table = static::get_routes_table(); - foreach($this->resources as $name=>$resource){ - if(isset($resource['as'])){ - if(isset($resource['regexp'])){ - if(preg_match($resource['regexp'], $request)){ - $this->current_resource = $name; - $_m_ = preg_replace($resource['regexp'], $resource['as'], trim($request, '/')); - $_m_ = explode('/', $_m_); - $_m_ = explode(static::get_separator(), $_m_[0]); - $this->params['controller'] = $_m_[0]; - $this->params['action'] = $_m_[1]; - break; - } - } elseif(isset($resource['path'])) { - if($resource['path']==$this->params['controller']){ - $this->current_resource = $name; - $_l_ = explode(static::get_separator(), $resource['as']); - $this->params['controller'] = $_l_[0]; - $this->params['action'] = $_l_[1]; - break; - } - } - } - // TODO - // elseif(isset($resource['controller'])){ - // - // } - } - $this->controller_class = ucfirst($this->params['controller']).static::get_controller_postfix(); - $this->action_method = ucfirst($this->params['action']).static::get_action_postfix(); + // map to routing config requested controller and action + static::set_routes_table($this->resources); + // $table = static::get_routes_table(); + foreach($this->resources as $name=>$resource){ + if(isset($resource['as'])){ + if(isset($resource['regexp'])){ + if(preg_match($resource['regexp'], $request)){ + $this->current_resource = $name; + $_m_ = preg_replace($resource['regexp'], $resource['as'], trim($request, '/')); + $_m_ = explode('/', $_m_); + $_m_ = explode(static::get_separator(), $_m_[0]); + $this->params['controller'] = $_m_[0]; + $this->params['action'] = $_m_[1]; + break; + } + } elseif(isset($resource['path'])) { + if($resource['path']==$this->params['controller']){ + $this->current_resource = $name; + $_l_ = explode(static::get_separator(), $resource['as']); + $this->params['controller'] = $_l_[0]; + $this->params['action'] = $_l_[1]; + break; + } + } + } + // TODO + // elseif(isset($resource['controller'])){ + // + // } + } + $this->controller_class = ucfirst($this->params['controller']).static::get_controller_postfix(); + $this->action_method = ucfirst($this->params['action']).static::get_action_postfix(); - if(count($url)>3){ - $kvals = array_slice($url,3); - $this->params['vars'] = array(); - foreach (array_chunk($kvals, 2) as $pair) { - if(!isset($pair[1])){ - $pair[1]=null; - } - list($key, $value) = $pair; - $this->params['vars'][$key] = $value; - } - } - } - - public static function set_root_controller(string $name){ - static::$_root_controller = $name; - } - public static function get_root_controller(){ - return static::$_root_controller; - } - - public static function set_root_action(string $name){ - static::$_root_action = $name; - } - public static function get_root_action(){ - return static::$_root_action; - } - - public static function set_controller_postfix(string $name){ - static::$_controller_postfix = $name; - } - public static function get_controller_postfix(){ - return static::$_controller_postfix; - } - - public static function set_action_postfix(string $name){ - static::$_action_postfix = $name; - } - public static function get_action_postfix(){ - return static::$_action_postfix; - } - - public static function set_separator(string $name){ - static::$_sep_ = $name; - } - public static function get_separator(){ - return static::$_sep_; - } - - public static function set_default_action(string $name){ - static::$_default_action = $name; - } - public static function get_default_action(){ - return static::$_default_action; - } - - public static function set_routes_table($resources){ - $r = []; - foreach($resources as $k=>$v){ - $is_array = is_array($v); - $resname = $is_array ? $k : $v; - if(!isset($r[$resname])){ - $r[$resname] = []; - } - if(!$is_array){ - $r[$resname]['controller'] = $resname; - $r[$resname]['actions'] = static::get_controller_actions($resname); - } else { - if(isset($v['as'])){ - $_l_ = explode(static::get_separator(), $v['as']); - $r[$resname]['controller'] = $_l_[0]; - $r[$resname]['actions'] = $_l_[1]; - if(isset($v['regexp'])){ - $r[$resname]['regexp'] = $v['regexp']; - } elseif(isset($v['path'])){ - $r[$resname]['path'] = $v['path']; - } - } elseif(isset($v['controller'])){ - $r[$resname]['controller'] = $v['controller']; - $r[$resname]['actions'] = static::get_controller_actions($v['controller']); - } - } - } - static::$_routing_table = $r; - } - - public static function get_routes_table(){ - return static::$_routing_table; - } - - public static function get_controller_actions($controller){ - $class_name = ucfirst($controller).static::get_controller_postfix(); - $class_methods = get_class_methods($class_name); - $actions = preg_grep("/^(.*)".static::get_action_postfix()."$/", $class_methods); - $r = array_map(function($el){ - return strtolower(str_replace(static::get_action_postfix(), '', $el)); - }, $actions); - return $r; - } - - public static function get_routes_info(){ - $table = static::get_routes_table(); - if(!$table){ - return false; - } - $o = ''; - foreach ($table as $k=>$v){ - if(isset($v['regexp'])){ - preg_match('/\/(.*)\/(.*)/', $v['regexp'], $_m_); - $o .= "/{$_m_[1]} ===========> {$v['controller']}#{$v['actions']}\n"; - } elseif(isset($v['path'])) { - $o .= "/{$v['path']} ===========> {$v['controller']}#{$v['actions']}\n"; - } else { - foreach($v['actions'] as $action){ - $p = isset($v['path']) ? $v['path'] : "{$v['controller']}/{$action}"; - $o .= "/{$p} ===========> {$v['controller']}#{$action}\n"; - } - } - } - return $o; - } - - public static function header(int $num){ - header(static::$_http[$num]); - } - - public function redirect($location, $num=false){ - if($num!=false) { - static::header($num); - } - header("Location: {$location}"); + if(count($url)>3){ + $kvals = array_slice($url,3); + $this->params['vars'] = array(); + foreach (array_chunk($kvals, 2) as $pair) { + if(!isset($pair[1])){ + $pair[1]=null; + } + list($key, $value) = $pair; + $this->params['vars'][$key] = $value; + } + } + } + + public static function set_root_controller(string $name){ + static::$_root_controller = $name; + } + public static function get_root_controller(){ + return static::$_root_controller; + } + + public static function set_root_action(string $name){ + static::$_root_action = $name; + } + public static function get_root_action(){ + return static::$_root_action; + } + + public static function set_controller_postfix(string $name){ + static::$_controller_postfix = $name; + } + public static function get_controller_postfix(){ + return static::$_controller_postfix; + } + + public static function set_action_postfix(string $name){ + static::$_action_postfix = $name; + } + public static function get_action_postfix(){ + return static::$_action_postfix; + } + + public static function set_separator(string $name){ + static::$_sep_ = $name; + } + public static function get_separator(){ + return static::$_sep_; + } + + public static function set_default_action(string $name){ + static::$_default_action = $name; + } + public static function get_default_action(){ + return static::$_default_action; + } + + public static function set_routes_table($resources){ + $r = []; + foreach($resources as $k=>$v){ + $is_array = is_array($v); + $resname = $is_array ? $k : $v; + if(!isset($r[$resname])){ + $r[$resname] = []; + } + if(!$is_array){ + $r[$resname]['controller'] = $resname; + $r[$resname]['actions'] = static::get_controller_actions($resname); + } else { + if(isset($v['as'])){ + $_l_ = explode(static::get_separator(), $v['as']); + $r[$resname]['controller'] = $_l_[0]; + $r[$resname]['actions'] = $_l_[1]; + if(isset($v['regexp'])){ + $r[$resname]['regexp'] = $v['regexp']; + } elseif(isset($v['path'])){ + $r[$resname]['path'] = $v['path']; + } + } elseif(isset($v['controller'])){ + $r[$resname]['controller'] = $v['controller']; + $r[$resname]['actions'] = static::get_controller_actions($v['controller']); + } + } + } + static::$_routing_table = $r; + } + + public static function get_routes_table(){ + return static::$_routing_table; + } + + public static function get_controller_actions($controller){ + $class_name = ucfirst($controller).static::get_controller_postfix(); + $class_methods = get_class_methods($class_name); + $actions = preg_grep("/^(.*)".static::get_action_postfix()."$/", $class_methods); + $r = array_map(function($el){ + return strtolower(str_replace(static::get_action_postfix(), '', $el)); + }, $actions); + return $r; + } + + public static function get_routes_info(){ + $table = static::get_routes_table(); + if(!$table){ + return false; + } + $o = ''; + foreach ($table as $k=>$v){ + if(isset($v['regexp'])){ + preg_match('/\/(.*)\/(.*)/', $v['regexp'], $_m_); + $o .= "/{$_m_[1]} ===========> {$v['controller']}#{$v['actions']}\n"; + } elseif(isset($v['path'])) { + $o .= "/{$v['path']} ===========> {$v['controller']}#{$v['actions']}\n"; + } else { + foreach($v['actions'] as $action){ + $p = isset($v['path']) ? $v['path'] : "{$v['controller']}/{$action}"; + $o .= "/{$p} ===========> {$v['controller']}#{$action}\n"; + } + } + } + return $o; + } + + public static function header(int $num){ + header(static::$_http[$num]); + } + + public function redirect($location, $num=false){ + if($num!=false) { + static::header($num); + } + header("Location: {$location}"); exit(0); - } + } } ?> \ No newline at end of file diff --git a/lib/shpala/shpala.php b/lib/shpala/shpala.php index 25f89d2..9a6675b 100644 --- a/lib/shpala/shpala.php +++ b/lib/shpala/shpala.php @@ -1,6 +1,6 @@ resource = $resource; - $this->view = $resource->controller->view; - if(isset($resource->i18n)) { - $this->i18n = $resource->i18n; - } - $path = static::get_path(); - $ext = static::get_extension(); - static::$_tpl_layout = $GLOBALS['APP_DIR'].$path.static::get_layout_file().$ext; - static::$_tpl_action = $GLOBALS['APP_DIR'].$path - .$this->resource->router->params['controller'].'/' - .$this->resource->router->params['action'] - .$ext; - } - - public static function set_path(string $value){ - static::$_path = $value; - } - - public static function get_path(){ - return static::$_path; - } - - public static function set_extension(string $value){ - static::$_extension = $value; - } - - public static function get_extension(){ - return static::$_extension; - } - - public static function set_layout_file(string $value){ - static::$_layout_file = $value; - } - - public static function get_layout_file(){ - return static::$_layout_file; - } - - public static function set_public_path(string $value){ - static::$_public_path = $value; - } - - public static function get_public_path(){ - return static::$_public_path; - } + public $resource; + public $errors=[]; + + protected $view; + + private static $_tpl_layout; + private static $_tpl_action; + + private static $_path = '/app/views/'; + private static $_extension = '.html.php'; + private static $_layout_file = 'layouts/application'; //no extension + private static $_public_path='/public/'; + + public function __construct(Resource &$resource) { + $this->resource = $resource; + $this->view = $resource->controller->view; + if(isset($resource->i18n)) { + $this->i18n = $resource->i18n; + } + $path = static::get_path(); + $ext = static::get_extension(); + static::$_tpl_layout = $GLOBALS['APP_DIR'].$path.static::get_layout_file().$ext; + static::$_tpl_action = $GLOBALS['APP_DIR'].$path + .$this->resource->router->params['controller'].'/' + .$this->resource->router->params['action'] + .$ext; + } + + public static function set_path(string $value){ + static::$_path = $value; + } + + public static function get_path(){ + return static::$_path; + } + + public static function set_extension(string $value){ + static::$_extension = $value; + } + + public static function get_extension(){ + return static::$_extension; + } + + public static function set_layout_file(string $value){ + static::$_layout_file = $value; + } + + public static function get_layout_file(){ + return static::$_layout_file; + } + + public static function set_public_path(string $value){ + static::$_public_path = $value; + } + + public static function get_public_path(){ + return static::$_public_path; + } - public function validate_layout(){ - if(!file_exists(static::$_tpl_layout)){ - $this->errors['layout_template_not_exists'] = true; - } - return (count($this->errors)>0) ? false : true; - } - - public function validate_action(){ - if(!file_exists(static::$_tpl_action)){ - $this->errors['action_template_not_exists'] = true; - } - return (count($this->errors)>0) ? false : true; - } - - public function render_layout(){ - //shortcut - $_v=$this->view; - $_t=$this->i18n; - require_once static::$_tpl_layout; - } - - public function render_action() { - //shortcut - $_v=$this->view; - $_t=$this->i18n; - require_once static::$_tpl_action; - } - - public function render_partial($file, $vars) { - require_once $file; - } - - public static function render_static($file, $header=false){ - if($header!=false) { - Router::header($header); - } - require_once $GLOBALS['APP_DIR'].static::get_public_path().$file; - exit(0); - } + public function validate_layout(){ + if(!file_exists(static::$_tpl_layout)){ + $this->errors['layout_template_not_exists'] = true; + } + return (count($this->errors)>0) ? false : true; + } + + public function validate_action(){ + if(!file_exists(static::$_tpl_action)){ + $this->errors['action_template_not_exists'] = true; + } + return (count($this->errors)>0) ? false : true; + } + + public function render_layout(){ + //shortcut + $_v=$this->view; + $_t=$this->i18n; + require_once static::$_tpl_layout; + } + + public function render_action() { + //shortcut + $_v=$this->view; + $_t=$this->i18n; + require_once static::$_tpl_action; + } + + public function render_partial($file, $vars) { + require_once $file; + } + + public static function render_static($file, $header=false){ + if($header!=false) { + Router::header($header); + } + require_once $GLOBALS['APP_DIR'].static::get_public_path().$file; + exit(0); + } } - + ?> \ No newline at end of file diff --git a/lib/tasks/db/structure/task_dump.php b/lib/tasks/db/structure/task_dump.php index 2f42e7c..90f5dac 100644 --- a/lib/tasks/db/structure/task_dump.php +++ b/lib/tasks/db/structure/task_dump.php @@ -1,3 +1,3 @@ \ No newline at end of file diff --git a/lib/tasks/db/task_migrate.php b/lib/tasks/db/task_migrate.php index 61eec31..70bfe8f 100644 --- a/lib/tasks/db/task_migrate.php +++ b/lib/tasks/db/task_migrate.php @@ -1,3 +1,3 @@ diff --git a/lib/tasks/db/task_seed.php b/lib/tasks/db/task_seed.php index 264d153..a9483e6 100644 --- a/lib/tasks/db/task_seed.php +++ b/lib/tasks/db/task_seed.php @@ -1,4 +1,4 @@ \ No newline at end of file diff --git a/lib/tasks/db/task_version.php b/lib/tasks/db/task_version.php index 9b32d55..8c4c246 100644 --- a/lib/tasks/db/task_version.php +++ b/lib/tasks/db/task_version.php @@ -1,4 +1,3 @@ get_connect(); echo 'DB version: '.$connect->query('select version()')->fetchColumn()."\n"; ?>