From bc00900a14beecf9ee11d00b622a189efda04563 Mon Sep 17 00:00:00 2001 From: bim-g Date: Wed, 3 Jan 2024 00:43:17 +0200 Subject: [PATCH] [ENH] refactor and clean code --- README.md | 49 +++-- assets/index.php | 5 - config/autoload.php | 13 +- config/constant.php | 2 +- config/database.php | 2 +- config/function.php | 43 +++-- config/globals.php | 2 +- config/index.php | 5 - config/init.php | 18 +- controller/exampleController.php | 23 ++- index.php | 2 +- lang/en/index.php | 5 - lang/en/language.php | 26 +-- lang/fr/index.php | 5 - lang/fr/language.php | 40 ++-- middleware/Validation/exampleValidation.php | 8 +- src/Core/Application.php | 9 +- src/Core/Bundles.php | 6 +- src/Core/Controller.php | 3 +- src/Core/DotEnv.php | 4 +- src/Core/Email.php | 157 ++++++++-------- src/Core/Event/EventEmitter.php | 62 ++++--- src/Core/Event/Listener.php | 39 ++-- src/Core/Http/Response.php | 2 +- src/Core/Media.php | 119 ++++++------ src/Core/MetaData.php | 173 +++++++++--------- src/Core/MiddleWare.php | 3 +- src/Core/Orm/DB.php | 4 +- src/Core/Orm/DBSelect.php | 32 ++-- src/Core/Orm/DBUpdate.php | 2 +- .../Provider/Contract/EntityInterface.php | 9 +- src/Core/Orm/EntityModel/Provider/Entity.php | 6 +- src/Core/Orm/Provider/Contract/DbContract.php | 8 +- src/Core/Orm/Provider/DbProvider.php | 31 ++-- src/Core/Orm/Traits/QueryExecuter.php | 4 +- .../Orm/WhereQueryBuilder/WhereBuilder.php | 24 +-- .../Orm/WhereQueryBuilder/WhereConditions.php | 36 ++-- src/Core/Resolver/OptionsResolver.php | 22 +-- src/Core/Routing/Route.php | 69 +++---- src/Core/Routing/Traits/routeBuilder.php | 10 +- .../Providers/ValidatorProvider.php | 28 +-- .../Validation/Validator/ArrayValidator.php | 38 ++-- .../Validation/Validator/BooleanValidator.php | 32 ++-- .../Validation/Validator/DateValidator.php | 48 ++--- .../Validation/Validator/NumberValidator.php | 34 ++-- .../Validation/Validator/StringValidator.php | 55 +++--- src/Test/ConfigTest.php | 5 +- views/404.php | 13 +- 48 files changed, 702 insertions(+), 633 deletions(-) delete mode 100644 assets/index.php delete mode 100644 config/index.php delete mode 100644 lang/en/index.php delete mode 100644 lang/fr/index.php diff --git a/README.md b/README.md index a1a1d48..2ee10c6 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,31 @@ # Wepesi + * Wepesi library -`wepesi` is the quick ans simple framework the help you devellop simple web application with php and design OOP concept, -it has been design by following most off principle for big framework but make it simple for develloper. + `wepesi` is the quick ans simple framework the help you devellop simple web application with php and design OOP + concept, + it has been design by following most off principle for big framework but make it simple for develloper. ## Installation + The installation of the application does not require somuch thing; + - In you are familliar with `composer` to install : -You can find project directly on packagest on : https://packagist.org/packages/wepesi/wepesi + You can find project directly on packagest on : https://packagist.org/packages/wepesi/wepesi + ```shell composer create-project wepesi/wepesi ``` + and it will create a project for You. -- In case you are not familliar with `composer` you can donwload it directly the source code on github on :https://github.com/kivudesign/Wepesi, no nee of extra module to start workin on the project. +- In case you are not familliar with `composer` you can donwload it directly the source code on github + on :https://github.com/kivudesign/Wepesi, no nee of extra module to start workin on the project. # Intoduction -Wepesi is a simple Web framework that help you devellop simple web application, and benefit advantage of large php framework like + +Wepesi is a simple Web framework that help you devellop simple web application, and benefit advantage of large php +framework like + - routing - controller - simple ORM *without migration @@ -25,24 +35,33 @@ Wepesi is a simple Web framework that help you devellop simple web application, - Validation - View -All module are built-id, its has been design to give to make the framework flexible, you can restructure everything as you want and be able to add more module. +All module are built-id, its has been design to give to make the framework flexible, you can restructure everything as +you want and be able to add more module. # Integration -no need to know about composer, the simple way is to download the all the project and place on the server side devellopenent. + +no need to know about composer, the simple way is to download the all the project and place on the server side +devellopenent. decompress the file, and folder the instruction. -- if you are using `wamp`, place the decopress folder on the `www` folder of `wamp` folder with is on the root of the dick c: on windows + +- if you are using `wamp`, place the decopress folder on the `www` folder of `wamp` folder with is on the root of the + dick c: on windows - if you are using `xamp`, you place the folder on the `htdocs` -you can rename the folder as you want according to you need + you can rename the folder as you want according to you need # Structure + the library is subdivised in multiple part with folder, we have: -- `class` : where all model and where we can find the core logic to run the libray. - there is a folder call `app`, in with you are not allowed to modified any class if you dont know what you are doing. - in some case, it will have an impact on the way your application is working. -- `controller`: where you can creat all the controller. the system has been designed like that to make a difference between controller and model. + +- `class` : where all model and where we can find the core logic to run the libray. + there is a folder call `app`, in with you are not allowed to modified any class if you dont know what you are doing. + in some case, it will have an impact on the way your application is working. +- `controller`: where you can creat all the controller. the system has been designed like that to make a difference + between controller and model. - `config`: where you can config the database configuration, and the autoloading. -- `layout`: the layout help manage all `css style` or `javascript script`, or not. the idea, is to have a better logical. in case you use the layout, - there is a way yu can accee those file by using wepesi class `Bundle`. +- `layout`: the layout help manage all `css style` or `javascript script`, or not. the idea, is to have a better + logical. in case you use the layout, + there is a way yu can accee those file by using wepesi class `Bundle`. - `route`: is where you can define all your route - `views`: here is where you will create all the pages that will display by the user. - `index.php`: this is the main file. to start the app, diff --git a/assets/index.php b/assets/index.php deleted file mode 100644 index 345f463..0000000 --- a/assets/index.php +++ /dev/null @@ -1,5 +0,0 @@ -load(); +(new DotEnv(dirname(__DIR__) . '/.env'))->load(); $GLOBALS['config'] ['mysql'] = [ diff --git a/config/function.php b/config/function.php index 0ceae2d..29bf15e 100644 --- a/config/function.php +++ b/config/function.php @@ -20,10 +20,12 @@ function getSubDirectories(string $dir): array * @param $class * @return false|mixed|string */ -function extractNamespace($class){ - $class_arr = explode("\\",$class); +function extractNamespace($class) +{ + $class_arr = explode("\\", $class); return end($class_arr); } + /** * @param $fileName * @return mixed|string @@ -38,26 +40,27 @@ function checkFileExtension($fileName) * @param array $exclude_folder * @return void */ -function autoIndexFolder(array $exclude_folder = []){ +function autoIndexFolder(array $exclude_folder = []) +{ $app_root = appDirSeparator(dirname(__DIR__)); // check if cache directory exists before processing - $cash_file_dir = appDirSeparator($app_root.'/cache'); + $cash_file_dir = appDirSeparator($app_root . '/cache'); if (!file_exists($cash_file_dir)) { mkdir($cash_file_dir, 0777, true); } // define exclude folder to not be affected by the situation. $exclude = ['vendor', 'test']; - if(count($exclude_folder)) $exclude = array_merge($exclude,$exclude_folder); - $implode = implode('|',$exclude); + if (count($exclude_folder)) $exclude = array_merge($exclude, $exclude_folder); + $implode = implode('|', $exclude); $folder_struct = getSubDirectories($app_root); - $filter = array_filter($folder_struct,function($folder_name) use ($implode) { + $filter = array_filter($folder_struct, function ($folder_name) use ($implode) { $pattern = "/$implode/i"; - if(!preg_match($pattern, strtolower(trim($folder_name)))) { + if (!preg_match($pattern, strtolower(trim($folder_name)))) { return $folder_name; } }); - if(!checkCacheContent($cash_file_dir, $filter)){ + if (!checkCacheContent($cash_file_dir, $filter)) { foreach ($filter as $subFolder) { if (!is_file($subFolder . '/index.php')) { copy(__DIR__ . '/index.php', $subFolder . '/index.php'); @@ -74,18 +77,18 @@ function autoIndexFolder(array $exclude_folder = []){ function checkCacheContent(string $cash_file_dir, array $filter): bool { $status = true; - $cash_file_path = appDirSeparator($cash_file_dir.'/index_folder.txt'); + $cash_file_path = appDirSeparator($cash_file_dir . '/index_folder.txt'); sort($filter); - $file_content = json_encode($filter,true); + $file_content = json_encode($filter, true); $cache_file = fOpen($cash_file_path, 'a+'); - if(!is_file($cash_file_path) || filesize($cash_file_path) < 1 ){ - fwrite($cache_file,$file_content); - }else{ - $content = fread($cache_file,filesize($cash_file_path)); - if($content != $file_content) { + if (!is_file($cash_file_path) || filesize($cash_file_path) < 1) { + fwrite($cache_file, $file_content); + } else { + $content = fread($cache_file, filesize($cash_file_path)); + if ($content != $file_content) { $cache_file = fOpen($cash_file_path, 'w'); fwrite($cache_file, $file_content); - }else{ + } else { $status = false; } } @@ -97,7 +100,8 @@ function checkCacheContent(string $cash_file_dir, array $filter): bool * @param string $path * @return string */ -function appDirSeparator(string $path):string{ +function appDirSeparator(string $path): string +{ $new_path = $path; if ((substr(PHP_OS, 0, 3)) === 'WIN') $new_path = str_replace("\\", '/', $path); return $new_path; @@ -107,7 +111,8 @@ function appDirSeparator(string $path):string{ * @param $ex * @return void */ -function dumper($ex){ +function dumper($ex) +{ print('
');
     print_r($ex);
     print('
'); diff --git a/config/globals.php b/config/globals.php index 35581bb..39fd723 100644 --- a/config/globals.php +++ b/config/globals.php @@ -15,5 +15,5 @@ 'vendor' => true, 'autoload' => ['src', 'controller', 'middleware', 'models', 'helpers'], 'helper' => WEB_ROOT, - 'preferences' => WEB_ROOT. 'helper' + 'preferences' => WEB_ROOT . 'helper' ]; \ No newline at end of file diff --git a/config/index.php b/config/index.php deleted file mode 100644 index 345f463..0000000 --- a/config/index.php +++ /dev/null @@ -1,5 +0,0 @@ -load(); +(new DotEnv($ROOT_DIR . '/.env'))->load(); $appConfiguration = new AppConfiguration(); diff --git a/lang/en/index.php b/lang/en/index.php deleted file mode 100644 index 345f463..0000000 --- a/lang/en/index.php +++ /dev/null @@ -1,5 +0,0 @@ -"Welcom" +$language = [ + "Welcom" => "Welcom" ]; -$validation=[ - "required"=>"required", - "min"=>"must be a minimum of", - "max"=>"must be a maximum of", - "matches"=>"must match", - "number"=>"must be a number", - "email"=>"invalid email address", - "url"=>"invalid url", - "file"=>"should be a file", - "unique"=>"already exist.", - "unknown"=>"unknown" +$validation = [ + "required" => "required", + "min" => "must be a minimum of", + "max" => "must be a maximum of", + "matches" => "must match", + "number" => "must be a number", + "email" => "invalid email address", + "url" => "invalid url", + "file" => "should be a file", + "unique" => "already exist.", + "unknown" => "unknown" ]; diff --git a/lang/fr/index.php b/lang/fr/index.php deleted file mode 100644 index 345f463..0000000 --- a/lang/fr/index.php +++ /dev/null @@ -1,5 +0,0 @@ -"Bienvenu", - "Welcome to Wepesi"=>"Bienvenu chez Wepesi", - "you can find the simple example here"=>"Vous pouvez trouvez un exemple ici", - "A Simple Php MVC platform to develop quickly a php application"=>"Une plateforme Simple Php MVC pour développer rapidement une application web", - "Home"=>"Acceuill", - "contact"=>"contact", - "Translate"=>"Traduire", - "Change the language"=>"Changez de langue" +$language = [ + "Welcome" => "Bienvenu", + "Welcome to Wepesi" => "Bienvenu chez Wepesi", + "you can find the simple example here" => "Vous pouvez trouvez un exemple ici", + "A Simple Php MVC platform to develop quickly a php application" => "Une plateforme Simple Php MVC pour développer rapidement une application web", + "Home" => "Acceuill", + "contact" => "contact", + "Translate" => "Traduire", + "Change the language" => "Changez de langue" ]; -$validation=[ - "required"=> "est obligatoire", - "min"=> "doit être au minimum", - "max"=> "doit être au maximum", - "matches"=> "doit correspondre", - "number"=> "doit être un nombre", - "email"=> "Adresse e-mail invalide", - "url"=>"invalid url", - "file"=> "devrait être un fichier", - "unique"=> "existe déjà.", - "unknown"=> "Inconus." +$validation = [ + "required" => "est obligatoire", + "min" => "doit être au minimum", + "max" => "doit être au maximum", + "matches" => "doit correspondre", + "number" => "doit être un nombre", + "email" => "Adresse e-mail invalide", + "url" => "invalid url", + "file" => "devrait être un fichier", + "unique" => "existe déjà.", + "unknown" => "Inconus." ]; \ No newline at end of file diff --git a/middleware/Validation/exampleValidation.php b/middleware/Validation/exampleValidation.php index 6f76627..63bc0fa 100644 --- a/middleware/Validation/exampleValidation.php +++ b/middleware/Validation/exampleValidation.php @@ -1,11 +1,13 @@ $this->schema->string("token") ->min(1) @@ -17,8 +19,8 @@ function changeLang(){ ->required() ]; - $this->validate->check($_POST,$rules); - if(!$this->validate->passed()){ + $this->validate->check($_POST, $rules); + if (!$this->validate->passed()) { dumper($this->validate->errors()); exit(); } diff --git a/src/Core/Application.php b/src/Core/Application.php index 4d3184b..a60af14 100644 --- a/src/Core/Application.php +++ b/src/Core/Application.php @@ -82,19 +82,20 @@ private function domainSetup(): object * use method to get domain ip * @return string */ - public static function getDomainIp() : string + public static function getDomainIp(): string { $ip = $_SERVER['REMOTE_ADDR']; - if (! empty($_SERVER['HTTP_CLIENT_IP'])) { + if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; - } elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { + } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif ($ip == '::1') { $ip = gethostbyname(getHostName()); } return $ip; } + /** * simple builtin dumper for dump data * @param $ex @@ -115,7 +116,7 @@ public static function dumper($ex) */ public static function setLayout(string $layout) { - self::$LAYOUT = self::$ROOT_DIR.'/views/'.$layout; + self::$LAYOUT = self::$ROOT_DIR . '/views/' . $layout; } /** diff --git a/src/Core/Bundles.php b/src/Core/Bundles.php index d92a9ae..ef920e9 100644 --- a/src/Core/Bundles.php +++ b/src/Core/Bundles.php @@ -2,8 +2,6 @@ namespace Wepesi\Core; -use Wepesi\Core\MetaData; - /** * */ @@ -49,7 +47,7 @@ public static function getHeaderJS() * manage to add javascript script on the page * @param string $file */ - static function insertJS(string $file,bool $is_module = false, bool $not_void=false) + static function insertJS(string $file, bool $is_module = false, bool $not_void = false) { if (is_file(ROOT . 'assets/js/' . $file . '.js')) { $src = WEB_ROOT . "assets/js/$file.js"; @@ -57,7 +55,7 @@ static function insertJS(string $file,bool $is_module = false, bool $not_void=fa $link = << EOF; - if($not_void){ + if ($not_void) { return $link; } echo $link . PHP_EOL; diff --git a/src/Core/Controller.php b/src/Core/Controller.php index 1c68bf7..6f7536e 100644 --- a/src/Core/Controller.php +++ b/src/Core/Controller.php @@ -5,6 +5,7 @@ namespace Wepesi\Core; -abstract class Controller{ +abstract class Controller +{ protected View $view; } diff --git a/src/Core/DotEnv.php b/src/Core/DotEnv.php index 154a150..de32e6c 100644 --- a/src/Core/DotEnv.php +++ b/src/Core/DotEnv.php @@ -19,7 +19,7 @@ class DotEnv */ public function __construct(string $path) { - if(!file_exists($path)) { + if (!file_exists($path)) { throw new \InvalidArgumentException(sprintf('%s does not exist', $path)); } $this->path = $path; @@ -28,7 +28,7 @@ public function __construct(string $path) /** * @return void */ - public function load() :void + public function load(): void { if (!is_readable($this->path)) { throw new \RuntimeException(sprintf('%s file is not readable', $this->path)); diff --git a/src/Core/Email.php b/src/Core/Email.php index 376c69a..5084763 100644 --- a/src/Core/Email.php +++ b/src/Core/Email.php @@ -2,7 +2,8 @@ namespace Wepesi\Core; -class Email { +class Email +{ private $url; private string $from; private string $contact; @@ -13,47 +14,49 @@ class Email { function __construct() { - $this->subject="Welcome to Wepesi"; - $this->from="no-reply@".APP_DOMAIN; - $this->contact="contact@".APP_DOMAIN; - $this->url=DEFAULT_DOMAIN; - $this->default_lang=LANG; + $this->subject = "Welcome to Wepesi"; + $this->from = "no-reply@" . APP_DOMAIN; + $this->contact = "contact@" . APP_DOMAIN; + $this->url = DEFAULT_DOMAIN; + $this->default_lang = LANG; } /** - * @return array|void + * @param array $data + * @return array|bool */ - private function checkConfig(array $config_data){ - try{ - $validat=new Validate($config_data); - $schema=[ - "from"=>$validat->string("from")->required()->email()->check(), - "to"=>$validat->string("to")->required()->email()->check(), - ]; - $validat->check($config_data,$schema); - if(!$validat->passed()){ - throw new \Exception($validat->errors()); - } - }catch (\Exception $ex){ - return ["exception"=>$ex->getMessage()]; - } - } - - private function sendMail(array $data,string $body){ - try{ - $this->from=$data["from"]; - $this->to=$data["to"]; - $this->subject=$data["subject"]; - $check_email=$this->checkConfig(["from"=>$this->from,"to"=>$this->to]); - if(isset($check_email['exception'])) return $check_email; - $header=[ - "MIME_Version:1.0", - "Content-type:text/html;charset=iso-8859", - "From:$this->from" - ]; - return mail($this->to,$this->subject,$body,implode("\r\n",$header)); - }catch (\Exception $ex){ - return ["exception"=>$ex->getMessage()]; + function welcom(array $data) + { + $subject = isset($data["subject"]) ?? $this->subject; + $body = << + + +
Bienvenues chez Wepesi
+ Your simple and light weight framework to devellop simple wep application +
+ + +

Wepesi

+
.
+ + + + +
Unsubscribe
+ + +

Wepesi

+
votre assistant, de prise de rendez-vous.
+ + + + EOF; + try { + $body = $this->template($body); + return $this->sendMail($data, $body); + } catch (\Exception $ex) { + return ["exception" => $ex->getMessage()]; } } @@ -62,9 +65,10 @@ private function sendMail(array $data,string $body){ * @return string * Wepesi model format email template */ - private function template(string $message_body):string{ - try{ - $thisYear= date("Y",time()); + private function template(string $message_body): string + { + try { + $thisYear = date("Y", time()); return <<< html_body @@ -128,46 +132,47 @@ private function template(string $message_body):string{ html_body; - }catch (\Exception $ex){ - return ["exception"=>$ex->getMessage()]; + } catch (\Exception $ex) { + return ["exception" => $ex->getMessage()]; + } + } + + private function sendMail(array $data, string $body) + { + try { + $this->from = $data["from"]; + $this->to = $data["to"]; + $this->subject = $data["subject"]; + $check_email = $this->checkConfig(["from" => $this->from, "to" => $this->to]); + if (isset($check_email['exception'])) return $check_email; + $header = [ + "MIME_Version:1.0", + "Content-type:text/html;charset=iso-8859", + "From:$this->from" + ]; + return mail($this->to, $this->subject, $body, implode("\r\n", $header)); + } catch (\Exception $ex) { + return ["exception" => $ex->getMessage()]; } } /** - * @param array $data - * @return array|bool + * @return array|void */ - function welcom(array $data){ - $subject=isset($data["subject"])??$this->subject; - $body=<< - - -
Bienvenues chez Wepesi
- Your simple and light weight framework to devellop simple wep application -
- - -

Wepesi

-
.
- - - - -
Unsubscribe
- - -

Wepesi

-
votre assistant, de prise de rendez-vous.
- - - - EOF; - try{ - $body=$this->template($body); - return $this->sendMail($data,$body); - }catch (\Exception $ex){ - return ["exception"=>$ex->getMessage()]; + private function checkConfig(array $config_data) + { + try { + $validat = new Validate($config_data); + $schema = [ + "from" => $validat->string("from")->required()->email()->check(), + "to" => $validat->string("to")->required()->email()->check(), + ]; + $validat->check($config_data, $schema); + if (!$validat->passed()) { + throw new \Exception($validat->errors()); + } + } catch (\Exception $ex) { + return ["exception" => $ex->getMessage()]; } } } \ No newline at end of file diff --git a/src/Core/Event/EventEmitter.php b/src/Core/Event/EventEmitter.php index ec5dd8a..3af09bb 100644 --- a/src/Core/Event/EventEmitter.php +++ b/src/Core/Event/EventEmitter.php @@ -1,52 +1,60 @@ hasListeners($event)) { foreach ($this->listeners[$event] as $listener) { $listener->handle($args); - if($listener->stopPropagation){ + if ($listener->stopPropagation) { break; } } } } - - function on(string $event,callable $callback,int $priority=0):Listener{ - if(!$this->hasListeners($event)){ - $this->listeners[$event]=[]; - } - $listener= new Listener($callback, $priority); - $this->listeners[$event][]= $listener; - $this->sortListener($event); - return $listener; + + private function hasListeners(string $event): bool + { + return array_key_exists($event, $this->listeners); } - function once(string $event,callable $callback,int $priority=0):Listener{ - - return $this->on($event,$callback,$priority)->once(); + + function once(string $event, callable $callback, int $priority = 0): Listener + { + + return $this->on($event, $callback, $priority)->once(); } - private function hasListeners(string $event):bool{ - return array_key_exists($event, $this->listeners); + function on(string $event, callable $callback, int $priority = 0): Listener + { + if (!$this->hasListeners($event)) { + $this->listeners[$event] = []; + } + $listener = new Listener($callback, $priority); + $this->listeners[$event][] = $listener; + $this->sortListener($event); + return $listener; } - private function sortListener($event){ - uasort($this->listeners[$event],function($a,$b){ - return $a->getPriority()<$b->getPriority(); + private function sortListener($event) + { + uasort($this->listeners[$event], function ($a, $b) { + return $a->getPriority() < $b->getPriority(); }); } } \ No newline at end of file diff --git a/src/Core/Event/Listener.php b/src/Core/Event/Listener.php index 22f1aaf..7eef1b9 100644 --- a/src/Core/Event/Listener.php +++ b/src/Core/Event/Listener.php @@ -2,36 +2,43 @@ namespace Wepesi\Core\Event; -class Listener{ +class Listener +{ + public $stopPropagation = false; private $callback, - $priority, - $once, - $calls=0; - public $stopPropagation=false; + $priority, + $once, + $calls = 0; - function __construct(callable $callback,int $priority) + function __construct(callable $callback, int $priority) { - $this->callback=$callback; - $this->priority=$priority; + $this->callback = $callback; + $this->priority = $priority; } - function handle(array $args){ - if($this->once && $this->calls>0){ + + function handle(array $args) + { + if ($this->once && $this->calls > 0) { return null; } $this->calls++; - return call_user_func_array($this->callback,$args); + return call_user_func_array($this->callback, $args); } - function once():Listener{ - $this->once=true; + function once(): Listener + { + $this->once = true; return $this; } - function getPriority(){ + + function getPriority() + { return $this->priority; } - function stopPropagation():Listener{ - $this->stopPropagation=true; + function stopPropagation(): Listener + { + $this->stopPropagation = true; return $this; } } \ No newline at end of file diff --git a/src/Core/Http/Response.php b/src/Core/Http/Response.php index 578dc52..bcfd9ca 100644 --- a/src/Core/Http/Response.php +++ b/src/Core/Http/Response.php @@ -1,6 +1,6 @@ _target_dir= $target_dir; + $this->_target_dir = $target_dir; } - function uploadImg($file){ - try{ + + function uploadImg($file) + { + try { if (!isset($file["name"])) { throw new \Exception("try to access to key `name` witch dos not exist"); } @@ -25,12 +28,31 @@ function uploadImg($file){ if ($res = $this->upload($file, ("photos/" . $filetype), $filetype)) { return $res; } - }catch (\Exception $ex){ - return ["exception"=>$ex->getMessage()]; + } catch (\Exception $ex) { + return ["exception" => $ex->getMessage()]; + } + } + + private function exception(int $src_error = 0): array + { + $message = "extenstion not supported"; + switch ($src_error) { + case 1: + $message = "error thumbnail"; + break; + case 5: + $message = "try to access to key `name` witch dos not exist"; + break; + case 20: + $message = "unable to upload the file"; + break; } + return ["exception" => $message]; } - private function upload($file,$formatFile, $filetype){ - $Link = $this->_target_dir . '/' .date('Y') . '/' . date('m') . '/'; + + private function upload($file, $formatFile, $filetype) + { + $Link = $this->_target_dir . '/' . date('Y') . '/' . date('m') . '/'; $target_dir = $Link; if (!file_exists($target_dir)) { @@ -39,66 +61,48 @@ private function upload($file,$formatFile, $filetype){ $filename = $file['name']; $imageRenamed = $this->renameFile($filename); - $fileToUpload = (string) $imageRenamed[0]; - if(!move_uploaded_file($file['tmp_name'], $target_dir . $fileToUpload)){ + $fileToUpload = (string)$imageRenamed[0]; + if (!move_uploaded_file($file['tmp_name'], $target_dir . $fileToUpload)) { return $this->exception(10); } - $format=explode("/", $formatFile); - if($format[0]=="photos"){ - $value = $this->thumbnail($fileToUpload, $target_dir, $Link,$format[1]); + $format = explode("/", $formatFile); + if ($format[0] == "photos") { + $value = $this->thumbnail($fileToUpload, $target_dir, $Link, $format[1]); if (!$value) { return $this->exception(1); } } return [ - "name"=>$filename, - "extension"=>$filetype, - "link"=> $Link . $fileToUpload + "name" => $filename, + "extension" => $filetype, + "link" => $Link . $fileToUpload ]; } private function renameFile($img) { - $lastid=TIME(); + $lastid = TIME(); $boom = explode(".", $img); $ext = end($boom); $img = date('y') . Md5($lastid) . date('m') . '.' . $ext; $store = date('y') . Md5($lastid) . date('m'); return array($img, $store); } - function uploadSingleFile($file,string $extension_file=null){ - try{ - if(!isset($file["name"])){ - throw new \Exception("try to access to key `name` witch dos not exist"); - } - $target_file = $this->_target_dir . basename($file["name"]); - $filetype = pathinfo($target_file, PATHINFO_EXTENSION); - if ($extension_file) { - if ($filetype != $extension_file) { - return $this->exception(); - } - return $this->upload($file, ("$extension_file/" . $filetype), $filetype); - } else { - return $this->upload($file, ("media/" . $filetype), $filetype); - } - }catch (\Exception $ex){ - return ["exception"=>$ex->getMessage()]; - } - } - private function thumbnail($imageToConvert, $source, $dest,$format) + + private function thumbnail($imageToConvert, $source, $dest, $format) { $imageCreated = $source . $imageToConvert; - $thumb=null; + $thumb = null; if ($imageCreated) { list($width, $height) = getimagesize($imageCreated); //$type will return the type of the image - $source = $format!="png"? imagecreatefromjpeg($imageCreated): imagecreatefrompng($imageCreated); + $source = $format != "png" ? imagecreatefromjpeg($imageCreated) : imagecreatefrompng($imageCreated); - if (Media::maxWidth >= $width && Media::maxHeigth >= $height) { + if (Media::maxWidth >= $width && Media::maxHeigth >= $height) { $ratio = 1; } elseif ($width > $height) { $ratio = Media::maxWidth / $width; } else { - $ratio = Media::maxHeigth / $height; + $ratio = Media::maxHeigth / $height; } $thumb_width = round($width * $ratio); //get the smaller value from cal # floor() @@ -117,16 +121,25 @@ private function thumbnail($imageToConvert, $source, $dest,$format) imagedestroy($thumb); imagedestroy($source); } - private function exception(int $src_error=0):array{ - $message="extenstion not supported"; - switch ($src_error){ - case 1: $message="error thumbnail"; - break; - case 5: $message="try to access to key `name` witch dos not exist"; - break; - case 20: $message="unable to upload the file"; - break; + + function uploadSingleFile($file, string $extension_file = null) + { + try { + if (!isset($file["name"])) { + throw new \Exception("try to access to key `name` witch dos not exist"); + } + $target_file = $this->_target_dir . basename($file["name"]); + $filetype = pathinfo($target_file, PATHINFO_EXTENSION); + if ($extension_file) { + if ($filetype != $extension_file) { + return $this->exception(); + } + return $this->upload($file, ("$extension_file/" . $filetype), $filetype); + } else { + return $this->upload($file, ("media/" . $filetype), $filetype); + } + } catch (\Exception $ex) { + return ["exception" => $ex->getMessage()]; } - return ["exception"=>$message]; } } \ No newline at end of file diff --git a/src/Core/MetaData.php b/src/Core/MetaData.php index d180e2f..7b0d8cd 100644 --- a/src/Core/MetaData.php +++ b/src/Core/MetaData.php @@ -136,11 +136,11 @@ function follow(): MetaData */ function keyword($keyword): MetaData { - if (is_array($keyword)){ - $this->_keyword = array_filter($keyword,function($item){ - return is_string($item) && strlen(trim($item))>0; + if (is_array($keyword)) { + $this->_keyword = array_filter($keyword, function ($item) { + return is_string($item) && strlen(trim($item)) > 0; }); - }else{ + } else { $this->_keyword = [trim($keyword)]; } return $this; @@ -199,6 +199,35 @@ function canonical(string $canonical): MetaData return $this; } + /** + * Get the complete meta data to be displayed + * @return string + */ + public function build(): string + { + if ($this->_title && $this->_description) { + $open_graph_meta = $this->openGraphMeta(); + $twitter_meta = $this->twitterMeta(); + $tags_exist = $this->getTags(); + $canonical_exist = $this->getCanonical(); + $keyword_exist = $this->getKeyWord(); + $author_exist = $this->getAuthor(); + return << + + + $keyword_exist + $author_exist + $tags_exist + $canonical_exist + + $open_graph_meta + + $twitter_meta + META; + } + } + /** * Open graph meta tags promote integration between * Facebook, LinkedIn, Google, and your website. @@ -212,7 +241,7 @@ protected function openGraphMeta(): string $cover_exist = $this->getCover(); $lang_exist = $this->getLang(); $title = $this->getTitle(); - $description = $this->getDescription(); + $description = $this->getDescription(); $title = $this->getTitle(); $app_domain = $_SERVER['SERVER_NAME'] ?? 'localhost'; return <<getLink(true); - $cover_exist = $this->getCover(true); - $lang_exist = $this->getLang(true); - $canonical_exist = $this->getCanonical(true); - $type_exist = $this->getType(true); - $description = $this->getDescription(true); - $title = $this->getTitle(true); - return << - $title - $description - $link_exist - $cover_exist - $lang_exist - $canonical_exist - $type_exist - HTML; - } - - /** - * @return string|null - */ - protected function getTitle(bool $twitter = false): string + protected function getLink(bool $twitter = false): string { $destination = $twitter ? 'twitter' : 'og'; - return "_title\" />"; - } - - /** - * @return string|null - */ - protected function getCanonical(bool $twitter = false): string - { - $canonical = $twitter ? "_canonical\">" : "_canonical\">"; - return $this->_canonical ? $canonical : ''; + return $this->_link ? "_link\" />" : ''; } /** * @return string|null */ - protected function getLang(bool $twitter = false): string + protected function getType(bool $twitter = fals): string { - $destination = $twitter ? 'twitter' : 'og'; - return $this->_lang ? "_lang\" />" : ''; + $type = $twitter ? "_type\" />" : ""; + return $this->_type ? $type : ''; } /** @@ -300,37 +293,68 @@ protected function getCover(bool $twitter = false): string } /** - * @return string + * @return string|null */ - protected function getLink(bool $twitter = false): string + protected function getLang(bool $twitter = false): string { $destination = $twitter ? 'twitter' : 'og'; - return $this->_link ? "_link\" />" : ''; + return $this->_lang ? "_lang\" />" : ''; } /** * @return string|null */ - protected function getAuthor(): ?string + protected function getTitle(bool $twitter = false): string { - return $this->_author ? "_author\">" : ''; + $destination = $twitter ? 'twitter' : 'og'; + return "_title\" />"; } /** * @return string|null */ - protected function getType(bool $twitter = fals): string + protected function getDescription(bool $twitter = false): ?string { - $type = $twitter ? "_type\" />" : ""; - return $this->_type ? $type : ''; - }/** + $destination = $twitter ? 'twitter' : 'og'; + return $this->_description ? "_description\" />" : ''; + } + + /** + * Twitter cards work in a similar way to Open Graph. + * It will use these tags to enhance the display of your page when shared on their platform. + * + * @return string + */ + protected function twitterMeta(): string + { + $link_exist = $this->getLink(true); + $cover_exist = $this->getCover(true); + $lang_exist = $this->getLang(true); + $canonical_exist = $this->getCanonical(true); + $type_exist = $this->getType(true); + $description = $this->getDescription(true); + $title = $this->getTitle(true); + return << + $title + $description + $link_exist + $cover_exist + $lang_exist + $canonical_exist + $type_exist + HTML; + } + + /** * @return string|null */ - protected function getKeyWord(): string + protected function getCanonical(bool $twitter = false): string { - $keyword = implode(',', $this->_keyword); - return count($this->_keyword) > 0 ? "" : ''; + $canonical = $twitter ? "_canonical\">" : "_canonical\">"; + return $this->_canonical ? $canonical : ''; } + /** * @return string|null */ @@ -343,39 +367,18 @@ protected function getTags(): string /** * @return string|null */ - protected function getDescription(bool $twitter = false): ?string + protected function getKeyWord(): string { - $destination = $twitter ? 'twitter' : 'og'; - return $this->_description ? "_description\" />" : ''; + $keyword = implode(',', $this->_keyword); + return count($this->_keyword) > 0 ? "" : ''; } /** - * Get the complete meta data to be displayed - * @return string + * @return string|null */ - public function build(): string + protected function getAuthor(): ?string { - if ($this->_title && $this->_description) { - $open_graph_meta = $this->openGraphMeta(); - $twitter_meta = $this->twitterMeta(); - $tags_exist = $this->getTags(); - $canonical_exist = $this->getCanonical(); - $keyword_exist = $this->getKeyWord(); - $author_exist = $this->getAuthor(); - return << - - - $keyword_exist - $author_exist - $tags_exist - $canonical_exist - - $open_graph_meta - - $twitter_meta - META; - } + return $this->_author ? "_author\">" : ''; } public function generate(): array diff --git a/src/Core/MiddleWare.php b/src/Core/MiddleWare.php index 77f5024..5e7e3d7 100644 --- a/src/Core/MiddleWare.php +++ b/src/Core/MiddleWare.php @@ -13,7 +13,8 @@ abstract class MiddleWare protected Validate $validate; protected Schema $schema; - public function __construct(){ + public function __construct() + { $this->schema = new Schema(); $this->validate = new Validate(); } diff --git a/src/Core/Orm/DB.php b/src/Core/Orm/DB.php index 5d3c332..bb18086 100644 --- a/src/Core/Orm/DB.php +++ b/src/Core/Orm/DB.php @@ -2,11 +2,9 @@ namespace Wepesi\Core\Orm; -use phpDocumentor\Reflection\Types\This; +use This; use Wepesi\Core\Config; use Wepesi\Core\Orm\Traits\QueryExecuter; -use Wepesi\Core\Resolver\Option; -use Wepesi\Core\Resolver\OptionsResolver; /** * diff --git a/src/Core/Orm/DBSelect.php b/src/Core/Orm/DBSelect.php index 4ad549d..007e790 100644 --- a/src/Core/Orm/DBSelect.php +++ b/src/Core/Orm/DBSelect.php @@ -208,7 +208,7 @@ public function offset(int $offset): DBSelect public function result(): array { $this->build(); - return (! isset($this->result['exception']) && count($this->include_object)>0 && count($this->result)>0) ? $this->formatData($this->result) : $this->result; + return (!isset($this->result['exception']) && count($this->include_object) > 0 && count($this->result) > 0) ? $this->formatData($this->result) : $this->result; } /** @@ -275,7 +275,7 @@ protected function formatData(array $result): array } else if (!in_array($relation->parent, $parent_entity)) { $other_entity[] = $relation->parent; } - switch ($relation->type){ + switch ($relation->type) { case 'HasMany' : if (!in_array($relation->child, $children_entity)) { $children_entity[] = $relation->child; @@ -285,8 +285,9 @@ protected function formatData(array $result): array break; case 'BelongTo': break; - case 'HasOne': $other_entity[] = $relation->child; - break; + case 'HasOne': + $other_entity[] = $relation->child; + break; } } return $this->buildStructure($result, $parent_entity[0], $children_entity, $other_entity); @@ -410,9 +411,9 @@ private function getExtractedChild(array $data_parent_table, string $child_table } $unique = Escape::removeDuplicateAssocArray($child_tables); - return array_map(function($item){ + return array_map(function ($item) { return (object)$item; - },$unique); + }, $unique); } /** @@ -436,15 +437,6 @@ private function getExtractedUndefined(array $first_row, string $parent_table_na return (object)$data_table; } - /** - * @param array $includes - * @return DBSelect - */ - private function include(array $includes): DBSelect - { - $this->include_object = $includes; - return $this; - } /** * @param $name * @param $arguments @@ -456,4 +448,14 @@ public function __call($name, $arguments) return call_user_func_array([$this, $name], $arguments); } } + + /** + * @param array $includes + * @return DBSelect + */ + private function include(array $includes): DBSelect + { + $this->include_object = $includes; + return $this; + } } diff --git a/src/Core/Orm/DBUpdate.php b/src/Core/Orm/DBUpdate.php index 7a1d663..cdb97bf 100644 --- a/src/Core/Orm/DBUpdate.php +++ b/src/Core/Orm/DBUpdate.php @@ -102,7 +102,7 @@ private function update() $where_params = $this->where['params'] ?? []; $fields = $this->_fields['keys']; $field_params = $this->_fields['params'] ?? []; - $params = array_merge(array_values($field_params),array_values($where_params)); + $params = array_merge(array_values($field_params), array_values($where_params)); //generate the sql query to be executed $sql = "UPDATE $this->table SET $fields $where"; $this->query($sql, $params); diff --git a/src/Core/Orm/EntityModel/Provider/Contract/EntityInterface.php b/src/Core/Orm/EntityModel/Provider/Contract/EntityInterface.php index dc94ad8..e9688c1 100644 --- a/src/Core/Orm/EntityModel/Provider/Contract/EntityInterface.php +++ b/src/Core/Orm/EntityModel/Provider/Contract/EntityInterface.php @@ -1,7 +1,10 @@ getClassDefinition($entityName,true); + $entity_table_object = $this->getClassDefinition($entityName, true); if (is_array($entity_table_object) && isset($entity_table_object['exception'])) { throw new \Exception($entity_table_object['exception']); } @@ -205,6 +205,7 @@ public function findOne(): array return ['exception' => $ex->getMessage()]; } } + /** * @return array */ @@ -227,6 +228,7 @@ public function count(): array return ['exception' => $ex->getMessage()]; } } + /** * @param array $fields * @return $this diff --git a/src/Core/Orm/Provider/Contract/DbContract.php b/src/Core/Orm/Provider/Contract/DbContract.php index a14c058..3726786 100644 --- a/src/Core/Orm/Provider/Contract/DbContract.php +++ b/src/Core/Orm/Provider/Contract/DbContract.php @@ -4,7 +4,9 @@ interface DbContract { - function error() : string; - function result() : array; - function count() : int; + function error(): string; + + function result(): array; + + function count(): int; } \ No newline at end of file diff --git a/src/Core/Orm/Provider/DbProvider.php b/src/Core/Orm/Provider/DbProvider.php index 7108779..976f0e1 100644 --- a/src/Core/Orm/Provider/DbProvider.php +++ b/src/Core/Orm/Provider/DbProvider.php @@ -8,7 +8,7 @@ /** * */ -abstract class DbProvider Implements DbContract +abstract class DbProvider implements DbContract { /** * @var string @@ -21,15 +21,15 @@ abstract class DbProvider Implements DbContract /** * @var \PDO */ - protected \PDO $pdo ; + protected \PDO $pdo; /** * @var array */ - protected array $result = [] ; + protected array $result = []; /** * @var int */ - protected int $lastID = 0 ; + protected int $lastID = 0; /** * @var int */ @@ -48,6 +48,17 @@ public function error(): string return $this->_error; } + /** + * @return int + * return counted rows of a select query + */ + public function count(): int + { + return $this->_count; + } + + abstract function result(): array; + /** * @param string $sql * @param array $params @@ -61,19 +72,9 @@ protected function query(string $sql, array $values) $this->lastID = $q['lastID'] ?? 0; $this->_count = $q['count'] ?? 0; - if($q['error'] !== ''){ + if ($q['error'] !== '') { $this->_error = $q['error']; $this->result = ['exception' => $q['error']]; } } - - /** - * @return int - * return counted rows of a select query - */ - public function count(): int - { - return $this->_count; - } - abstract function result(): array; } \ No newline at end of file diff --git a/src/Core/Orm/Traits/QueryExecuter.php b/src/Core/Orm/Traits/QueryExecuter.php index ea33b4d..3ddd634 100644 --- a/src/Core/Orm/Traits/QueryExecuter.php +++ b/src/Core/Orm/Traits/QueryExecuter.php @@ -19,7 +19,7 @@ trait QueryExecuter * @param array $params * @return array */ - protected function executeQuery(\PDO $pdo, string $sql, array $params = [],int $last_id = -1): array + protected function executeQuery(\PDO $pdo, string $sql, array $params = [], int $last_id = -1): array { try { $data_result = [ @@ -60,7 +60,7 @@ protected function executeQuery(\PDO $pdo, string $sql, array $params = [],int $ $data_result['lastID'] = $last_id; $data_result['count'] = $query->rowCount(); $sql = "SELECT * FROM $this->table WHERE id=?"; - return $this->executeQuery($pdo, $sql, [$last_id],$last_id); + return $this->executeQuery($pdo, $sql, [$last_id], $last_id); break; case 'update': $data_result['count'] = $query->rowCount(); diff --git a/src/Core/Orm/WhereQueryBuilder/WhereBuilder.php b/src/Core/Orm/WhereQueryBuilder/WhereBuilder.php index 6301cae..e5112d7 100644 --- a/src/Core/Orm/WhereQueryBuilder/WhereBuilder.php +++ b/src/Core/Orm/WhereQueryBuilder/WhereBuilder.php @@ -42,6 +42,18 @@ public function andOption(WhereConditions $where_condition): WhereBuilder return $this; } + /** + * @param $name + * @param $arguments + * @return mixed|void + */ + public function __call($name, $arguments) + { + if (method_exists($this, $name)) { + return call_user_func_array([$this, $name], $arguments); + } + } + /** * @param WhereBuilder $builder * @return array[] @@ -60,16 +72,4 @@ protected function generate(): array { return $this->operator; } - - /** - * @param $name - * @param $arguments - * @return mixed|void - */ - public function __call($name, $arguments) - { - if (method_exists($this, $name)) { - return call_user_func_array([$this, $name], $arguments); - } - } } diff --git a/src/Core/Orm/WhereQueryBuilder/WhereConditions.php b/src/Core/Orm/WhereQueryBuilder/WhereConditions.php index c4bef43..5f307ed 100644 --- a/src/Core/Orm/WhereQueryBuilder/WhereConditions.php +++ b/src/Core/Orm/WhereQueryBuilder/WhereConditions.php @@ -19,7 +19,7 @@ final class WhereConditions */ public function __construct(string $field) { - $this->field_condition = (Object)[ + $this->field_condition = (object)[ 'field_name' => $field, 'comparison' => null, 'field_value' => null, @@ -38,6 +38,15 @@ public function isGreaterThan($field_comparison): WhereConditions return $this; } + /** + * @param $field_value + * @return void + */ + private function conditionIsString($field_value) + { + $this->field_condition->field_value = is_numeric($field_value) ? $field_value : "" . $field_value . ""; + } + /** * @param $field_comparison * @return $this @@ -115,23 +124,6 @@ public function isLike($field_comparison): WhereConditions return $this; } - /** - * @return object - */ - private function getCondition(): object - { - return $this->field_condition; - } - - /** - * @param $field_value - * @return void - */ - private function conditionIsString($field_value) - { - $this->field_condition->field_value = is_numeric($field_value) ? $field_value : "" . $field_value . ""; - } - /** * @param $name * @param $arguments @@ -143,4 +135,12 @@ public function __call($name, $arguments) return call_user_func_array([$this, $name], $arguments); } } + + /** + * @return object + */ + private function getCondition(): object + { + return $this->field_condition; + } } diff --git a/src/Core/Resolver/OptionsResolver.php b/src/Core/Resolver/OptionsResolver.php index a4c5fce..798dd99 100644 --- a/src/Core/Resolver/OptionsResolver.php +++ b/src/Core/Resolver/OptionsResolver.php @@ -22,9 +22,18 @@ public function __construct(array $options) } } + /** + * @param Option $option + * @return void + */ + private function add(Option $option): void + { + $this->options->offsetSet($option->getName(), $option); + } + public function resolve(array $options): array { - try{ + try { $this->checkDiff($options); /** @@ -52,20 +61,11 @@ public function resolve(array $options): array ); } return $optionsResolved; - }catch (InvalidArgumentException $ex){ + } catch (InvalidArgumentException $ex) { return ['InvalidArgumentException' => $ex]; } } - /** - * @param Option $option - * @return void - */ - private function add(Option $option): void - { - $this->options->offsetSet($option->getName(), $option); - } - private function checkDiff(array $options): void { $defined = $this->options->getArrayCopy(); diff --git a/src/Core/Routing/Route.php b/src/Core/Routing/Route.php index bf8b458..2615870 100644 --- a/src/Core/Routing/Route.php +++ b/src/Core/Routing/Route.php @@ -10,7 +10,8 @@ /** * */ -class Route{ +class Route +{ /** * @var string */ @@ -33,7 +34,7 @@ class Route{ /** * @var array|mixed */ - private array $_get_params,$middleware_tab; + private array $_get_params, $middleware_tab; /** * @@ -44,7 +45,8 @@ class Route{ * @param $path * @param $callable */ - function __construct($path,$callable,array $middleware = []){ + function __construct($path, $callable, array $middleware = []) + { $this->pattern = trim($path, '/'); $this->callable = $callable; $this->_matches = []; @@ -57,18 +59,19 @@ function __construct($path,$callable,array $middleware = []){ * @param $url * @return bool */ - function match($url):bool{ + function match($url): bool + { $url = trim($url, '/'); - $path = preg_replace_callback('#:([\w]+)#',[$this,'paramMatch'],$this->pattern); + $path = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], $this->pattern); $regex = "#^$path$#i"; - if(!preg_match($regex,$url,$matches)){ + if (!preg_match($regex, $url, $matches)) { return false; } // remove the url path on the array key array_shift($matches); array_shift($_GET); $this->_matches = $matches; - foreach ($matches as $key => $val){ + foreach ($matches as $key => $val) { $_GET[$this->_get_params[$key]] = $val; } return true; @@ -77,48 +80,37 @@ function match($url):bool{ /** * */ - public function call(){ - try{ + public function call() + { + try { if (count($this->middleware_tab) > 0) { foreach ($this->middleware_tab as $middleware) { - $this->routeFunctionCall($middleware, true,$this->_matches); + $this->routeFunctionCall($middleware, true, $this->_matches); } $this->middleware_tab = []; } - $this->routeFunctionCall($this->callable,false,$this->_matches); - }catch (\Exception $ex){ + $this->routeFunctionCall($this->callable, false, $this->_matches); + } catch (\Exception $ex) { echo $ex->getMessage(); } } - /** - * @param $match - * @return string - */ - private function paramMatch($match):string{ - // - if(isset($this->_params[$match[1]])){ - return '(' .$this->_params[$match[1]]. ')'; - } - $this->_get_params[] = $match[1]; - return '([^/]+)'; - } - /** * @param $param * @param $regex * @return $this */ - public function with($param,$regex): Route + public function with($param, $regex): Route { - $this->_params[$param] = str_replace('(','(?:',$regex); + $this->_params[$param] = str_replace('(', '(?:', $regex); return $this; } /** * @return array */ - public function getMatch():array{ + public function getMatch(): array + { return $this->_matches; } @@ -134,10 +126,11 @@ public function getPattern(): string * @param $params * @return array|string|string[] */ - public function getUrl($params){ + public function getUrl($params) + { $path = $this->pattern; - foreach($params as $k => $v){ - $path = str_replace(":$k",$v,$path); + foreach ($params as $k => $v) { + $path = str_replace(":$k", $v, $path); } return $path; } @@ -151,4 +144,18 @@ public function middleware($middleware): Route $this->middleware_tab[] = $middleware; return $this; } + + /** + * @param $match + * @return string + */ + private function paramMatch($match): string + { + // + if (isset($this->_params[$match[1]])) { + return '(' . $this->_params[$match[1]] . ')'; + } + $this->_get_params[] = $match[1]; + return '([^/]+)'; + } } \ No newline at end of file diff --git a/src/Core/Routing/Traits/routeBuilder.php b/src/Core/Routing/Traits/routeBuilder.php index 2e9d159..cfd7315 100644 --- a/src/Core/Routing/Traits/routeBuilder.php +++ b/src/Core/Routing/Traits/routeBuilder.php @@ -9,9 +9,9 @@ trait routeBuilder { - protected function routeFunctionCall($callable, bool $is_middleware = false,array $matches = []): void + protected function routeFunctionCall($callable, bool $is_middleware = false, array $matches = []): void { - $controller = !$is_middleware? 'controller' : 'middleware'; + $controller = !$is_middleware ? 'controller' : 'middleware'; try { if (is_string($callable) || is_array($callable)) { $params = is_string($callable) ? explode('#', $callable) : $callable; @@ -22,17 +22,17 @@ protected function routeFunctionCall($callable, bool $is_middleware = false,arra $classCallable = $params[0]; $class_method = $params[1]; if (!class_exists($classCallable, true)) { - throw new \InvalidArgumentException("$classCallable class not defined, not a valid $controller",500); + throw new \InvalidArgumentException("$classCallable class not defined, not a valid $controller", 500); } $reflection = new \ReflectionClass($classCallable); $class_instance = $reflection->newInstance(); - if(!$reflection->isInstance($class_instance)){ + if (!$reflection->isInstance($class_instance)) { throw new \ReflectionException('Only instantiable class can be used. Not abstract,interface, or trait can be used.'); } if (!method_exists($class_instance, $class_method)) { - throw new \BadMethodCallException("method : $class_method does not belong the class : $classCallable.",500); + throw new \BadMethodCallException("method : $class_method does not belong the class : $classCallable.", 500); } call_user_func_array([$class_instance, $class_method], $matches); } else { diff --git a/src/Core/Validation/Providers/ValidatorProvider.php b/src/Core/Validation/Providers/ValidatorProvider.php index 70a71b7..f5aa877 100644 --- a/src/Core/Validation/Providers/ValidatorProvider.php +++ b/src/Core/Validation/Providers/ValidatorProvider.php @@ -34,6 +34,7 @@ abstract class ValidatorProvider implements Contracts * @var MessageErrorBuilder */ protected MessageErrorBuilder $messageItem; + /** * */ @@ -56,19 +57,6 @@ abstract public function min(int $rule); */ abstract public function max(int $rule); - /** - * Provide validation module name - * @return string - */ - abstract protected function classProvider(): string ; - - /** - * @return string - */ - private function getClassProvider(): string - { - return $this->classProvider() && strlen($this->classProvider()) > 0 ? $this->classProvider() : 'unknown'; - } /** * @return void */ @@ -94,6 +82,20 @@ public function required() } } + /** + * @return string + */ + private function getClassProvider(): string + { + return $this->classProvider() && strlen($this->classProvider()) > 0 ? $this->classProvider() : 'unknown'; + } + + /** + * Provide validation module name + * @return string + */ + abstract protected function classProvider(): string; + /** * * @param array $value diff --git a/src/Core/Validation/Validator/ArrayValidator.php b/src/Core/Validation/Validator/ArrayValidator.php index 8076f49..e12e381 100644 --- a/src/Core/Validation/Validator/ArrayValidator.php +++ b/src/Core/Validation/Validator/ArrayValidator.php @@ -27,25 +27,6 @@ public function __construct(string $item, array $data_source = []) $this->field_value = $data_source[$item]; } - /** - * check the minimum length of an array should be about - * @param int $rule - * @return void - */ - public function min(int $rule): void - { - // TODO: Implement min() method. - if ($this->checkNotPositiveParamMethod($rule)) return; - if (count($this->field_value) < $rule) { - $this->messageItem - ->type('array.min') - ->message("`$this->field_name` should have a minimum of `$rule` elements") - ->label($this->field_name) - ->limit($rule); - $this->addError($this->messageItem); - } - } - /** * @param int $rule * @return void @@ -104,6 +85,25 @@ public function string(): void } } + /** + * check the minimum length of an array should be about + * @param int $rule + * @return void + */ + public function min(int $rule): void + { + // TODO: Implement min() method. + if ($this->checkNotPositiveParamMethod($rule)) return; + if (count($this->field_value) < $rule) { + $this->messageItem + ->type('array.min') + ->message("`$this->field_name` should have a minimum of `$rule` elements") + ->label($this->field_name) + ->limit($rule); + $this->addError($this->messageItem); + } + } + /** * @return void */ diff --git a/src/Core/Validation/Validator/BooleanValidator.php b/src/Core/Validation/Validator/BooleanValidator.php index 443c63d..7fbaa6f 100644 --- a/src/Core/Validation/Validator/BooleanValidator.php +++ b/src/Core/Validation/Validator/BooleanValidator.php @@ -38,22 +38,6 @@ function __construct(string $item, array $source) } } - /** - * @param $rule - * @return void - */ - public function min($rule) - { - } - - /** - * @param $rule - * @return void - */ - public function max($rule) - { - } - /** * * @param string|null $itemKey @@ -76,6 +60,22 @@ private function isBoolean(string $itemKey = null): bool return true; } + /** + * @param $rule + * @return void + */ + public function min($rule) + { + } + + /** + * @param $rule + * @return void + */ + public function max($rule) + { + } + /** * @param string $value * @return void diff --git a/src/Core/Validation/Validator/DateValidator.php b/src/Core/Validation/Validator/DateValidator.php index 3658cc9..0014821 100644 --- a/src/Core/Validation/Validator/DateValidator.php +++ b/src/Core/Validation/Validator/DateValidator.php @@ -30,6 +30,30 @@ public function __construct(string $item, array $data_source) $this->checkExist(); } + /** + * @param string|null $itemKey + * @return void + */ + protected function checkExist(string $itemKey = null): void + { + $item_to_check = $itemKey ? $itemKey : $this->field_name; + $regex = '#[a-zA-Z0-9]#'; + $this->_errors = []; + if (!isset($this->data_source[$item_to_check])) { + $this->messageItem + ->type('any.unknown') + ->message("`$item_to_check` is unknown") + ->label($item_to_check); + $this->addError($this->messageItem); + } else if (!preg_match($regex, $this->data_source[$item_to_check]) || strlen(trim($this->data_source[$item_to_check])) == 0) { + $this->messageItem + ->type('date.unknown') + ->message("`$item_to_check` should be a date.") + ->label($item_to_check); + $this->addError($this->messageItem); + } + } + /** * @return void */ @@ -116,30 +140,6 @@ public function max($rule) } } - /** - * @param string|null $itemKey - * @return void - */ - protected function checkExist(string $itemKey = null): void - { - $item_to_check = $itemKey ? $itemKey : $this->field_name; - $regex = '#[a-zA-Z0-9]#'; - $this->_errors = []; - if (!isset($this->data_source[$item_to_check])) { - $this->messageItem - ->type('any.unknown') - ->message("`$item_to_check` is unknown") - ->label($item_to_check); - $this->addError($this->messageItem); - } else if (!preg_match($regex, $this->data_source[$item_to_check]) || strlen(trim($this->data_source[$item_to_check])) == 0) { - $this->messageItem - ->type('date.unknown') - ->message("`$item_to_check` should be a date.") - ->label($item_to_check); - $this->addError($this->messageItem); - } - } - /** * @return string */ diff --git a/src/Core/Validation/Validator/NumberValidator.php b/src/Core/Validation/Validator/NumberValidator.php index c591eb0..de8f500 100644 --- a/src/Core/Validation/Validator/NumberValidator.php +++ b/src/Core/Validation/Validator/NumberValidator.php @@ -35,6 +35,23 @@ public function __construct(string $item, array $data_source) $this->isNumber(); } + /** + * @return bool + */ + protected function isNumber(): bool + { + $regex_string = '#[a-zA-Z]#'; + if (preg_match($regex_string, trim($this->data_source[$this->field_name])) || ((int)$this->data_source[$this->field_name] !== $this->field_value)) { + $this->messageItem + ->type('number.unknown') + ->message("`$this->field_name` should be a number") + ->label($this->field_name); + $this->addError($this->messageItem); + return false; + } + return true; + } + /** * @param int $rule * @return void @@ -82,23 +99,6 @@ public function positive() } } - /** - * @return bool - */ - protected function isNumber(): bool - { - $regex_string = '#[a-zA-Z]#'; - if (preg_match($regex_string, trim($this->data_source[$this->field_name])) || ((int)$this->data_source[$this->field_name] !== $this->field_value)) { - $this->messageItem - ->type('number.unknown') - ->message("`$this->field_name` should be a number") - ->label($this->field_name); - $this->addError($this->messageItem); - return false; - } - return true; - } - /** * @return string */ diff --git a/src/Core/Validation/Validator/StringValidator.php b/src/Core/Validation/Validator/StringValidator.php index 236a88f..e36bee7 100644 --- a/src/Core/Validation/Validator/StringValidator.php +++ b/src/Core/Validation/Validator/StringValidator.php @@ -6,9 +6,6 @@ namespace Wepesi\Core\Validation\Validator; -use Wepesi\Core\Orm\DB; -use Wepesi\Core\Orm\WhereQueryBuilder\WhereBuilder; -use Wepesi\Core\Orm\WhereQueryBuilder\WhereConditions; use Wepesi\Core\Validation\Providers\ValidatorProvider; /** @@ -117,6 +114,30 @@ public function match(string $key_to_match) } } + /** + * + * @param string $item_key + * @return void + */ + protected function isStringAndValid(string $item_key): void + { + $field_to_check = !$item_key ? $this->field_name : $item_key; + $regex = '#[a-zA-Z0-9]#'; + if (!isset($this->data_source[$field_to_check])) { + $this->messageItem + ->type('string.unknown') + ->message("`$field_to_check` is not valid") + ->label($field_to_check); + $this->addError($this->messageItem); + } else if (!preg_match($regex, $this->data_source[$field_to_check]) || strlen(trim($this->field_value)) == 0) { + $this->messageItem + ->type('string.unknown') + ->message("`$field_to_check` should be a string") + ->label($field_to_check); + $this->addError($this->messageItem); + } + } + /** * @param string $ip_address * @return void @@ -152,10 +173,11 @@ public function addressIpv6(string $ip_address) * @return $this * @throws \Exception */ - public function unique(string $table_name){ + public function unique(string $table_name) + { $db = \Wepesi\Core\Orm\DB::getInstance(); $condition = (new \Wepesi\Core\Orm\WhereQueryBuilder\WhereConditions($this->field_name))->isEqualTo(\Wepesi\Core\Escape::encode($this->field_value)); - $where = (new \Wepesi\Core\Orm\WhereQueryBuilder\WhereBuilder())->andOption($condition); + $where = (new \Wepesi\Core\Orm\WhereQueryBuilder\WhereBuilder())->andOption($condition); $check_uniq = $db->get($table_name)->where($where)->result(); if ($db->error()) { $this->messageItem @@ -172,29 +194,6 @@ public function unique(string $table_name){ } return $this; } - /** - * - * @param string $item_key - * @return void - */ - protected function isStringAndValid(string $item_key): void - { - $field_to_check = !$item_key ? $this->field_name : $item_key; - $regex = '#[a-zA-Z0-9]#'; - if (!isset($this->data_source[$field_to_check])) { - $this->messageItem - ->type('string.unknown') - ->message("`$field_to_check` is not valid") - ->label($field_to_check); - $this->addError($this->messageItem); - } else if (!preg_match($regex, $this->data_source[$field_to_check]) || strlen(trim($this->field_value)) == 0) { - $this->messageItem - ->type('string.unknown') - ->message("`$field_to_check` should be a string") - ->label($field_to_check); - $this->addError($this->messageItem); - } - } protected function classProvider(): string { diff --git a/src/Test/ConfigTest.php b/src/Test/ConfigTest.php index 04fc1cc..e020bc6 100644 --- a/src/Test/ConfigTest.php +++ b/src/Test/ConfigTest.php @@ -5,12 +5,13 @@ namespace Wepesi\Test; -use Wepesi\Core\Config; use PHPUnit\Framework\TestCase; +use Wepesi\Core\Config; class ConfigTest extends TestCase { - public function testNotGet(){ + public function testNotGet() + { $this->assertEquals(false, Config::get()); } // the module shouldbe rewrite cause global variable break unit test diff --git a/views/404.php b/views/404.php index 59995c1..32e037e 100644 --- a/views/404.php +++ b/views/404.php @@ -6,16 +6,17 @@ content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> Pages not found -
-

404

-

Go home

-
+
+

404

+

Go home

+
\ No newline at end of file