From 2aabbd1e2046702a821ed5538e517da0b68320f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?N=27Guessan=20Kouadio=20Elis=C3=A9e?= Date: Wed, 30 Mar 2022 06:19:49 +0000 Subject: [PATCH] fix: removed ResponseInterface --- .../Auth/EmailVerificationController.php | 16 +- .../Auth/ForgotPasswordController.php | 18 +- app/Http/Controllers/Auth/LoginController.php | 10 +- .../Controllers/Auth/LogoutController.php | 6 +- .../Controllers/Auth/RegisterController.php | 10 +- app/Http/Middlewares/AccountPolicy.php | 4 +- app/Http/Middlewares/ApiAuth.php | 10 +- app/Http/Middlewares/AuthPolicy.php | 4 +- app/Http/Middlewares/HttpAuth.php | 12 +- app/Http/Middlewares/HttpCors.php | 2 +- app/Http/Validators/Auth/LoginValidator.php | 4 +- .../Validators/Auth/RegisterValidator.php | 9 +- core/Application.php | 4 +- core/Database/Repository.php | 4 +- .../InvalidResponseDataException .php | 21 +++ core/Http/Redirect.php | 79 --------- core/Http/Request.php | 8 + core/Http/Response.php | 159 ++++++++++++++++++ core/Http/Response/DownloadResponse.php | 41 ----- core/Http/Response/JsonResponse.php | 40 ----- core/Http/Response/Response.php | 58 ------- core/Http/Response/ResponseInterface.php | 14 -- core/Http/Validator/Validator.php | 25 ++- core/Http/Validator/ValidatorInterface.php | 2 +- core/Routing/Route.php | 22 +-- core/Routing/Router.php | 10 +- core/Support/Auth.php | 4 +- core/Support/DependencyInjection.php | 6 +- core/Support/Metrics.php | 27 +-- core/Testing/ApplicationTestCase.php | 12 +- resources/stubs/Controller.stub | 4 +- resources/stubs/Validator.stub | 5 + routes/auth.php | 4 +- 33 files changed, 307 insertions(+), 347 deletions(-) create mode 100644 core/Exceptions/InvalidResponseDataException .php delete mode 100644 core/Http/Redirect.php create mode 100644 core/Http/Response.php delete mode 100644 core/Http/Response/DownloadResponse.php delete mode 100644 core/Http/Response/JsonResponse.php delete mode 100644 core/Http/Response/Response.php delete mode 100644 core/Http/Response/ResponseInterface.php diff --git a/app/Http/Controllers/Auth/EmailVerificationController.php b/app/Http/Controllers/Auth/EmailVerificationController.php index 9a0f178b..4aa655f1 100644 --- a/app/Http/Controllers/Auth/EmailVerificationController.php +++ b/app/Http/Controllers/Auth/EmailVerificationController.php @@ -15,7 +15,7 @@ use Core\Support\Mail\Mail; use App\Database\Models\Token; use App\Mails\VerificationMail; -use Core\Http\Response\Response; +use Core\Http\Response; use App\Http\Actions\UserActions; /** @@ -35,27 +35,27 @@ public function notify(Request $request, Response $response) ]); Alert::default(__('email_verification_link_sent'))->success(); - $response->redirect()->to('login')->go(); + $response->redirectUrl('login')->send(302); } Alert::default(__('email_verification_link_not_sent'))->error(); - $response->redirect()->to('signup')->go(); + $response->redirectUrl('signup')->send(302); } public function verify(Request $request, Response $response) { if (!$request->hasQuery('email', 'token')) { - $response->send(data: __('bad_request'), code: 400); + $response->data(__('bad_request'))->send(400); } $token = Token::findBy('email', $request->email); if (!$token || $token->token !== $request->token) { - $response->send(data: __('invalid_password_reset_link'), code: 400); + $response->data(__('invalid_password_reset_link'))->send(400); } if (Carbon::parse($token->expire)->lt(Carbon::now())) { - $response->send(data: __('expired_password_reset_link'), code: 400); + $response->data(__('expired_password_reset_link'))->send(400); } $token->delete(); @@ -64,12 +64,12 @@ public function verify(Request $request, Response $response) if (!$user) { Alert::default(__('account_not_found'))->error(); - $response->redirect()->to('signup')->go(); + $response->redirectUrl('signup')->send(400); } Mail::send(new WelcomeMail($user->email, $user->name)); Alert::default(__('email_verified'))->success(); - $response->redirect()->to('login')->go(); + $response->redirectUrl('login')->send(400); } } diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index cfe7e6a9..fc307a74 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -14,7 +14,7 @@ use App\Mails\TokenMail; use Core\Support\Mail\Mail; use App\Database\Models\Token; -use Core\Http\Response\Response; +use Core\Http\Response; use App\Http\Actions\UserActions; use App\Http\Validators\Auth\LoginValidator; @@ -35,31 +35,31 @@ public function notify(Request $request, Response $response) ]); Alert::default(__('password_reset_link_sent'))->success(); - $response->redirect()->back()->go(); + $response->redirectBack()->send(302); } Alert::default(__('password_reset_link_not_sent'))->error(); - $response->redirect()->back()->go(); + $response->redirectBack()->send(302); } public function reset(Request $request, Response $response) { if (!$request->hasQuery('email', 'token')) { - $response->send(data: __('bad_request'), code: 400); + $response->data(__('bad_request'))->send(400); } $token = Token::findBy('email', $request->email); if (!$token || $token->token !== $request->token) { - $response->send(data: __('invalid_password_reset_link'), code: 400); + $response->data(__('invalid_password_reset_link'))->send(400); } if (Carbon::parse($token->expire)->lt(Carbon::now())) { - $response->send(data: __('expired_password_reset_link'), code: 400); + $response->data(__('expired_password_reset_link'))->send(400); } $token->delete(); - $response->redirect()->to("password/new?email={$request->email}")->go(); + $response->redirectUrl("/password/new?email={$request->email}")->send(302); } public function update(Request $request, Response $response, LoginValidator $loginValidator) @@ -69,10 +69,10 @@ public function update(Request $request, Response $response, LoginValidator $log if (!$user) { Alert::default(__('password_not_reset'))->error(); - $response->redirect()->back()->go(); + $response->redirectBack()->send(302); } Alert::default(__('password_reset'))->success(); - $response->redirect()->to('login')->go(); + $response->redirectUrl('/login')->send(302); } } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 6556c022..ae2e8c28 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -12,17 +12,17 @@ use Core\Support\Auth; use Core\Support\Alert; use Core\Support\Session; -use Core\Http\Response\Response; +use Core\Http\Response; use App\Http\Validators\Auth\LoginValidator; class LoginController { public function index(Request $request, Response $response) { - if (!Auth::check($request)) $response->view('auth.login'); + if (!Auth::check($request)) $response->view('auth.login')->send(); $uri = !Session::has('intended') ? config('app.home') : Session::pull('intended'); - $response->redirect()->to($uri)->go(); + $response->redirectUrl($uri)->send(302); } public function authenticate(Request $request, Response $response, LoginValidator $loginValidator) @@ -33,10 +33,10 @@ public function authenticate(Request $request, Response $response, LoginValidato $uri = !Session::has('intended') ? config('app.home') : Session::pull('intended'); Alert::toast(__('welcome', ['name' => Auth::get('name')]))->success(); - $response->redirect()->to($uri)->go(); + $response->redirectUrl($uri)->send(302); } Alert::default(__('login_failed'))->error(); - $response->redirect()->to('login')->withInputs($request->only('email', 'password'))->withErrors([__('login_failed')])->go(); + $response->redirectUrl('/login')->withInputs($request->only('email', 'password'))->withErrors([__('login_failed')])->send(302); } } diff --git a/app/Http/Controllers/Auth/LogoutController.php b/app/Http/Controllers/Auth/LogoutController.php index aa5005e0..91cb3df3 100644 --- a/app/Http/Controllers/Auth/LogoutController.php +++ b/app/Http/Controllers/Auth/LogoutController.php @@ -10,15 +10,15 @@ use Core\Support\Auth; use Core\Support\Alert; -use Core\Http\Response\Response; +use Core\Http\Response; class LogoutController { public function __invoke(Response $response) { Auth::forget(); - Alert::toast(__('logged_out'))->success(); - $response->redirect()->to(config('app.home'))->go(); + + $response->redirectUrl(config('app.home'))->send(302); } } diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index 952d13d5..dfbb0f93 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -14,7 +14,7 @@ use Core\Support\Session; use App\Mails\WelcomeMail; use Core\Support\Mail\Mail; -use Core\Http\Response\Response; +use Core\Http\Response; use App\Http\Actions\UserActions; use App\Http\Validators\Auth\RegisterValidator; @@ -22,10 +22,10 @@ class RegisterController { public function index(Request $request, Response $response) { - if (!Auth::check($request)) $response->view('auth.signup'); + if (!Auth::check($request)) $response->view('auth.signup')->send(); $uri = !Session::has('intended') ? config('app.home') : Session::pull('intended'); - $response->redirect()->to($uri)->go(); + $response->redirectUrl($uri)->send(302); } public function register(Request $request, Response $response, RegisterValidator $registerValidator) @@ -34,12 +34,12 @@ public function register(Request $request, Response $response, RegisterValidator $user = UserActions::create($validator->validated()); if (config('security.auth.email_verification')) { - $response->redirect()->to('email/notify')->go(); + $response->redirectUrl('/email/notify')->send(302); } Mail::send(new WelcomeMail($user->email, $user->name)); Alert::default(__('account_created'))->success(); - $response->redirect()->to('login')->go(); + $response->redirectUrl('/login')->send(302); } } diff --git a/app/Http/Middlewares/AccountPolicy.php b/app/Http/Middlewares/AccountPolicy.php index 0d0edffc..aa2b6740 100644 --- a/app/Http/Middlewares/AccountPolicy.php +++ b/app/Http/Middlewares/AccountPolicy.php @@ -9,7 +9,7 @@ namespace App\Http\Middlewares; use Core\Http\Request; -use Core\Http\Response\Response; +use Core\Http\Response; use Core\Support\Auth; use Core\Support\Alert; @@ -23,7 +23,7 @@ public function handle(Request $request, Response $response) if (config('security.auth.email_verification')) { if (is_null(Auth::get('email_verified'))) { Alert::default(__('email_not_verifed'))->error(); - $response->redirect()->to('login')->intended($request->fullUri())->go(); + $response->redirectUrl('/login')->intended($request->fullUri())->send(302); } } } diff --git a/app/Http/Middlewares/ApiAuth.php b/app/Http/Middlewares/ApiAuth.php index 5b3a8dbb..3883c543 100644 --- a/app/Http/Middlewares/ApiAuth.php +++ b/app/Http/Middlewares/ApiAuth.php @@ -10,7 +10,7 @@ use Core\Support\Auth; use Core\Http\Request; -use Core\Http\Response\JsonResponse; +use Core\Http\Response; use Core\Support\Encryption; /** @@ -18,20 +18,20 @@ */ class ApiAuth { - public function handle(Request $request, JsonResponse $response) + public function handle(Request $request, Response $response) { if (empty($request->getHttpAuth())) { - $response->send(data: __('auth_required'), code: 401); + $response->json([__('auth_required')])->send(401); } list($method, $token) = $request->getHttpAuth(); if (trim($method) !== 'Bearer') { - $response->send(data: __('invalid_auth_method'), code: 401); + $response->json([__('invalid_auth_method')])->send(401); } if (!Auth::checkToken(Encryption::decrypt($token), $user)) { - $response->send(data: __('invalid_credentials'), code: 401); + $response->json([__('invalid_credentials')])->send(401); } } } diff --git a/app/Http/Middlewares/AuthPolicy.php b/app/Http/Middlewares/AuthPolicy.php index 0743a2cf..9cdd3a56 100644 --- a/app/Http/Middlewares/AuthPolicy.php +++ b/app/Http/Middlewares/AuthPolicy.php @@ -10,7 +10,7 @@ use Core\Support\Auth; use Core\Http\Request; -use Core\Http\Response\Response; +use Core\Http\Response; use Core\Support\Alert; /** @@ -22,7 +22,7 @@ public function handle(Request $request, Response $response) { if (!Auth::check($request)) { Alert::default(__('not_logged'))->error(); - $response->redirect()->to('login')->intended($request->fullUri())->withErrors([__('not_logged')])->go(); + $response->redirectUrl('login')->intended($request->fullUri())->withErrors([__('not_logged')])->send(302); } } } diff --git a/app/Http/Middlewares/HttpAuth.php b/app/Http/Middlewares/HttpAuth.php index cd9a83a4..5ccad5ee 100644 --- a/app/Http/Middlewares/HttpAuth.php +++ b/app/Http/Middlewares/HttpAuth.php @@ -8,32 +8,32 @@ namespace App\Http\Middlewares; -use Core\Support\Auth; use Core\Http\Request; -use Core\Http\Response\JsonResponse; +use Core\Support\Auth; +use Core\Http\Response; /** * Authenticate user by http */ class HttpAuth { - public function handle(Request $request, JsonResponse $response) + public function handle(Request $request, Response $response) { if (empty($request->getHttpAuth())) { - $response->send(data: __('auth_required'), code: 401); + $response->json([__('auth_required')])->send(401); } list($method, $credentials) = $request->getHttpAuth(); if (trim($method) !== 'Basic') { - $response->send(data: __('invalid_auth_method'), code: 401); + $response->json([__('invalid_auth_method')])->send(401); } $credentials = base64_decode($credentials); list($email, $password) = explode(':', $credentials); if (!Auth::checkCredentials($email, $password, $user)) { - $response->send(data: __('invalid_credentials'), code: 401); + $response->json([__('invalid_credentials')])->send(401); } } } diff --git a/app/Http/Middlewares/HttpCors.php b/app/Http/Middlewares/HttpCors.php index ebf25a84..49253eff 100644 --- a/app/Http/Middlewares/HttpCors.php +++ b/app/Http/Middlewares/HttpCors.php @@ -8,7 +8,7 @@ namespace App\Http\Middlewares; -use Core\Http\Response\Response; +use Core\Http\Response; /** * Manage HTTP CORS diff --git a/app/Http/Validators/Auth/LoginValidator.php b/app/Http/Validators/Auth/LoginValidator.php index 7c2876f4..91401b06 100644 --- a/app/Http/Validators/Auth/LoginValidator.php +++ b/app/Http/Validators/Auth/LoginValidator.php @@ -18,8 +18,8 @@ class LoginValidator extends Validator public function rules(): array { return [ - 'email' => 'required|max_len,255', - 'password' => 'required|max_len,525' + 'email' => 'required|valid_email|max_len,255', + 'password' => 'required|max_len,255' ]; } diff --git a/app/Http/Validators/Auth/RegisterValidator.php b/app/Http/Validators/Auth/RegisterValidator.php index 23850bde..1cbd027c 100644 --- a/app/Http/Validators/Auth/RegisterValidator.php +++ b/app/Http/Validators/Auth/RegisterValidator.php @@ -15,11 +15,10 @@ class RegisterValidator extends Validator { public function __construct() { - return $this - ->addCustomRule('unique', function($field, array $input, array $params, $value) { - $data = (new Repository($params[0]))->select('*')->where($field, $value); - return !$data->exists(); - }, 'This {field} is already used by another user'); + $this->addCustomRule('unique', function($field, array $input, array $params, $value) { + $data = (new Repository($params[0]))->select('*')->where($field, $value); + return !$data->exists(); + }, 'This {field} is already registered'); } /** diff --git a/core/Application.php b/core/Application.php index d05aef61..4506e34a 100644 --- a/core/Application.php +++ b/core/Application.php @@ -12,7 +12,7 @@ use Core\Routing\Router; use Core\Support\Whoops; use Core\Support\Exception; -use Core\Http\Response\Response; +use Core\Http\Response; /** * Main application @@ -34,7 +34,7 @@ public function run() if (config('errors.log')) save_log('Exception: ' . $e); if (config('errors.display')) die($e); - $response->view(view: config('errors.views.500'), code: 500); + $response->view(config('errors.views.500'))->send(500); } } } diff --git a/core/Database/Repository.php b/core/Database/Repository.php index 31295b30..af2bcd4a 100644 --- a/core/Database/Repository.php +++ b/core/Database/Repository.php @@ -140,9 +140,7 @@ public function insert(array $items) public function insertGetId(array $items) { - if (!$this->insert($items)) { - return null; - } + if (!$this->insert($items)) return null; return QueryBuilder::lastInsertedId(); } diff --git a/core/Exceptions/InvalidResponseDataException .php b/core/Exceptions/InvalidResponseDataException .php new file mode 100644 index 00000000..544ea100 --- /dev/null +++ b/core/Exceptions/InvalidResponseDataException .php @@ -0,0 +1,21 @@ +uri = $uri; - return $this; - } - - public function route(string $route, $params = null): self - { - $this->uri = route_uri($route, $params); - return $this; - } - - public function back(): self - { - $history = Session::get('history'); - - if (!empty($history)) { - end($history); - $this->uri = prev($history); - } - - return $this; - } - - public function intended(string $uri): self - { - return $this->with('intended', $uri); - } - - public function go(int $code = 302) - { - exit($this->headers('Location', url($this->uri), $code)); - } - - public function with(string $key, $data): self - { - Session::create($key, $data); - return $this; - } - - public function withErrors(array $errors): self - { - Session::create('errors', $errors); - return $this; - } - - public function withInputs(array $inputs): self - { - Session::create('inputs', $inputs); - return $this; - } - - public function withCookie(string $name, string $value, int $expire = 3600, bool $secure = false, string $domain = ''): self - { - Cookies::create($name, $value, $expire, $secure, $domain); - return $this; - } -} diff --git a/core/Http/Request.php b/core/Http/Request.php index 50c8ab27..e8dda1f6 100644 --- a/core/Http/Request.php +++ b/core/Http/Request.php @@ -8,6 +8,7 @@ namespace Core\Http; +use Core\Http\Validator\Validator; use Core\Support\Uploader; /** @@ -266,4 +267,11 @@ public function all() return $all; } + + public function validate(array $rules, array $messages = [], array $inputs = []): Validator + { + $inputs = empty($inputs) ? $this->inputs() : $inputs; + + return (new Validator($rules, $messages))->validate($inputs); + } } diff --git a/core/Http/Response.php b/core/Http/Response.php new file mode 100644 index 00000000..20df7f10 --- /dev/null +++ b/core/Http/Response.php @@ -0,0 +1,159 @@ +headers = array_merge($this->headers, $headers); + return $this; + } + + public function data(string $data): self + { + if (empty($data)) throw new InvalidResponseDataException(); + + $this->addHeaders(['Content-Length' => strlen($data)]); + $this->data = $data; + + return $this; + } + + public function view(string $view, array $data = []): self + { + $this->data = View::getContent($view, $data); + return $this; + } + + public function redirectUrl(string $uri): self + { + $this->uri = $uri; + $this->addHeaders(['Location' => url($this->uri)]); + + return $this; + } + + public function redirectRoute(string $route, $params = null): self + { + return $this->redirectUrl(route_uri($route, $params)); + } + + public function redirectBack(): self + { + $history = Session::get('history'); + + if(empty($history)) return $this->redirectUrl('/'); + + end($history); + + return $this->redirectUrl(prev($history)); + } + + public function intended(string $uri): self + { + return $this->with('intended', $uri); + } + + public function with(string $key, $data): self + { + Session::create($key, $data); + return $this; + } + + public function withErrors(array $errors): self + { + Session::create('errors', $errors); + return $this; + } + + public function withInputs(array $inputs): self + { + Session::create('inputs', $inputs); + return $this; + } + + public function withCookie(string $name, string $value, int $expire = 3600, bool $secure = false, string $domain = ''): self + { + Cookies::create($name, $value, $expire, $secure, $domain); + return $this; + } + + public function download(string $filename): self + { + if (!file_exists($filename)) { + throw new FileNotFoundException($filename); + } + + $this->addHeaders([ + 'Content-Type' => mime_content_type($filename), + 'Content-Length' => filesize($filename), + 'Content-Disposition' => 'attachment; filename="' . basename($filename) . '"', + 'Cache-Control' => 'no-cache', + 'Pragma' => 'no-cache', + 'Expires' => '0' + ]); + + ob_clean(); + flush(); + + $this->data = readfile($filename); + + return $this; + } + + public function json(array $data): self + { + if (empty($data)) throw new InvalidJsonDataException(); + + $data = json_encode($data); + + $this->addHeaders([ + 'Content-Type' => 'application/json', + 'Content-Length' => strlen($data), + ]); + + $this->data = $data; + + return $this; + } + + public function send(int $code = 200) + { + if (config('app.env') === 'test') { + header('Session:' . json_encode($_SESSION)); + } + + http_response_code($code); + + foreach ($this->headers as $key => $value) { + header($key . ':' . $value); + } + + if (!empty($this->data)) exit($this->data); + + exit(); + } +} diff --git a/core/Http/Response/DownloadResponse.php b/core/Http/Response/DownloadResponse.php deleted file mode 100644 index 637707ba..00000000 --- a/core/Http/Response/DownloadResponse.php +++ /dev/null @@ -1,41 +0,0 @@ -headers(array_merge($headers, [ - 'Content-Type' => mime_content_type($filename), - 'Content-Length' => filesize($filename), - 'Content-Disposition' => 'attachment; filename="' . basename($filename) . '"', - 'Cache-Control' => 'no-cache', - 'Pragma' => 'no-cache', - 'Expires' => '0' - ]), null, $code); - - ob_clean(); - flush(); - - exit(readfile($filename)); - } -} diff --git a/core/Http/Response/JsonResponse.php b/core/Http/Response/JsonResponse.php deleted file mode 100644 index b80577d1..00000000 --- a/core/Http/Response/JsonResponse.php +++ /dev/null @@ -1,40 +0,0 @@ -headers(array_merge($headers, [ - 'Content-Type' => 'application/json', - 'Content-Length' => strlen($data), - ]), null, $code); - - exit($data); - } -} diff --git a/core/Http/Response/Response.php b/core/Http/Response/Response.php deleted file mode 100644 index ddb5873a..00000000 --- a/core/Http/Response/Response.php +++ /dev/null @@ -1,58 +0,0 @@ - $v) { - header($k . ':' . $v); - } - } - - /** - * @param string $data - */ - public function send($data, array $headers = [], int $code = 200) - { - if (empty($data)) return; - - $this->headers(array_merge($headers, ['Content-Length' => strlen($data)]), null, $code); - - exit($data); - } - - public function view(string $view, array $data = [], array $headers = [], int $code = 200) - { - $this->send(View::getContent($view, $data), $headers, $code); - } - - public function redirect() - { - return new Redirect(); - } -} diff --git a/core/Http/Response/ResponseInterface.php b/core/Http/Response/ResponseInterface.php deleted file mode 100644 index 284bcb49..00000000 --- a/core/Http/Response/ResponseInterface.php +++ /dev/null @@ -1,14 +0,0 @@ -inputs = $inputs; - $this->errors = GUMP::is_valid($this->inputs, $this->rules(), $this->messages()); + $this->rules = empty($this->rules) ? $this->rules() : $this->rules; + $this->messages = empty($this->messages) ? $this->messages() : $this->messages; + $this->errors = GUMP::is_valid($this->inputs, $this->rules, $this->messages); - if ($this->fails()) $response->redirect()->back()->withErrors($this->errors())->withInputs($this->inputs)->go(); + if ($this->fails() && !is_null($response)) { + $response->redirectBack()->withErrors($this->errors())->withInputs($this->inputs)->send(302); + } + return $this; } diff --git a/core/Http/Validator/ValidatorInterface.php b/core/Http/Validator/ValidatorInterface.php index f7d2f409..648629e4 100644 --- a/core/Http/Validator/ValidatorInterface.php +++ b/core/Http/Validator/ValidatorInterface.php @@ -8,7 +8,7 @@ namespace Core\Http\Validator; -use Core\Http\Response\Response; +use Core\Http\Response; interface ValidatorInterface { diff --git a/core/Routing/Route.php b/core/Routing/Route.php index ce2ebe9e..a6a464b5 100644 --- a/core/Routing/Route.php +++ b/core/Routing/Route.php @@ -10,7 +10,7 @@ use Core\Exceptions\RoutesPathsNotDefinedException; use Core\Support\Storage; -use Core\Http\Response\Response; +use Core\Http\Response; /** * Manage routes @@ -63,15 +63,15 @@ public static function any(string $uri, $handler): self return static::add('GET|POST|DELETE|PUT|OPTIONS|PATCH ' . $uri, $handler); } - public static function all(string $name, string $controller): self - { - return self::group(function() use ($name, $controller) { - self::get('/' . $name, 'index')->name('index'); - self::post('/' . $name, 'store')->name('store'); - self::match('PATCH|PUT', '/' . $name . '/{id:num}', 'update')->name('update'); - self::get('/' . $name . '/{id:num}', 'show')->name('show'); - self::get('/' . $name . '/{id:num}/edit', 'edit')->name('edit'); - self::delete('/' . $name . '/{id:num}', 'delete')->name('delete'); + public static function all(string $name, string $controller, array $excepts = []): self + { + return self::group(function() use ($name, $excepts) { + if (!in_array('index', $excepts)) self::get('/' . $name, 'index')->name('index'); + if (!in_array('store', $excepts)) self::post('/' . $name, 'store')->name('store'); + if (!in_array('update', $excepts)) self::match('PATCH|PUT', '/' . $name . '/{id:num}', 'update')->name('update'); + if (!in_array('show', $excepts)) self::get('/' . $name . '/{id:num}', 'show')->name('show'); + if (!in_array('edit', $excepts)) self::get('/' . $name . '/{id:num}/edit', 'edit')->name('edit'); + if (!in_array('delete', $excepts)) self::delete('/' . $name . '/{id:num}', 'delete')->name('delete'); })->byController($controller)->byName($name); } @@ -83,7 +83,7 @@ public static function match(string $methods, string $uri, $handler): self public static function view(string $uri, string $view, array $params = []): self { return static::get($uri, function (Response $response) use ($view, $params) { - $response->view($view, $params); + $response->view($view, $params)->send(); }); } diff --git a/core/Routing/Router.php b/core/Routing/Router.php index 768eba97..d3632818 100644 --- a/core/Routing/Router.php +++ b/core/Routing/Router.php @@ -11,7 +11,7 @@ use Closure; use Core\Http\Request; use Core\Support\Session; -use Core\Http\Response\Response; +use Core\Http\Response; use Core\Support\DependencyInjection; use Core\Exceptions\RoutesNotDefinedException; use Core\Exceptions\ControllerNotFoundException; @@ -54,14 +54,14 @@ private static function executeMiddlewares(array $middlewares) private static function executeHandler($handler, array $params) { if ($handler instanceof Closure) { - (new DependencyInjection())->resolveClosure($handler, $params); + return (new DependencyInjection())->resolveClosure($handler, $params); } if (is_array($handler)) { list($controller, $action) = $handler; if (class_exists($controller) && method_exists($controller, $action)) { - (new DependencyInjection())->resolve($controller, $action, $params); + return (new DependencyInjection())->resolve($controller, $action, $params); } throw new ControllerNotFoundException("$controller/$action"); @@ -69,7 +69,7 @@ private static function executeHandler($handler, array $params) if (is_string($handler)) { if (class_exists($handler)) { - (new DependencyInjection())->resolve($handler, '__invoke', $params); + return (new DependencyInjection())->resolve($handler, '__invoke', $params); } throw new ControllerNotFoundException($handler); @@ -107,6 +107,6 @@ public static function dispatch(Request $request, Response $response) } } - $response->view(view: config('errors.views.404'), code: 404); + $response->view(view: config('errors.views.404'))->send(404); } } diff --git a/core/Support/Auth.php b/core/Support/Auth.php index 189d3239..750d8964 100644 --- a/core/Support/Auth.php +++ b/core/Support/Auth.php @@ -15,7 +15,7 @@ use Core\Support\Encryption; use App\Database\Models\User; use App\Database\Models\Token; -use Core\Http\Response\Response; +use Core\Http\Response; /** * Manage authentications @@ -33,7 +33,7 @@ public static function attempt(Response $response, array $credentials, bool $rem if (!self::checkCredentials($credentials['email'], $credentials['password'], $user)) { if (config('security.auth.max_attempts') > 0 && Auth::getAttempts() >= config('security.auth.max_attempts')) { - $response->redirect()->back()->with('auth_attempts_timeout', Carbon::now()->addMinutes(config('security.auth.unlock_timeout'))->toDateTimeString())->go(); + $response->redirectBack()->with('auth_attempts_timeout', Carbon::now()->addMinutes(config('security.auth.unlock_timeout'))->toDateTimeString())->send(302); } return false; diff --git a/core/Support/DependencyInjection.php b/core/Support/DependencyInjection.php index cbf4fa6e..d4ffce16 100644 --- a/core/Support/DependencyInjection.php +++ b/core/Support/DependencyInjection.php @@ -47,7 +47,7 @@ public function resolve(string $class, string $method, array $params = []) $dependencies = $this->getDependencies($parameters); - call_user_func_array([$class, $method], array_merge($dependencies, $params)); + return call_user_func_array([$class, $method], array_merge($dependencies, $params)); } /** @@ -59,13 +59,13 @@ public function resolveClosure(Closure $closure, array $params = []) $parameters = $reflector->getParameters(); $dependencies = $this->getDependencies($parameters); - call_user_func_array($closure, array_merge($dependencies, $params)); + return call_user_func_array($closure, array_merge($dependencies, $params)); } /** * Generate new instance of dependencies */ - public function getDependencies(array $parameters) + public function getDependencies(array $parameters): array { $dependencies = []; diff --git a/core/Support/Metrics.php b/core/Support/Metrics.php index 1762e70e..510e2ba4 100644 --- a/core/Support/Metrics.php +++ b/core/Support/Metrics.php @@ -53,7 +53,10 @@ class Metrics 'november', ]; - public function __construct(public readonly string $table) {} + public function __construct(public readonly string $table, private string $driver = '') + { + $this->driver = config('app.env') === 'test' ? $driver = config('testing.database.driver') : config('database.driver'); + } /** * @link https://www.tutsmake.com/mysql-get-data-of-current-date-week-month-year/ @@ -243,22 +246,10 @@ private function getPeriod(string $period) private function formatPeriod(string $period) { switch ($period) { - case self::DAY: - return config('database.driver') === 'mysql' ? 'weekday(created_at)' - : "strftime('%w', created_at)"; - - case self::WEEK: - return config('database.driver') === 'mysql' ? 'week(created_at)' - : "strftime('%W', created_at)"; - - case self::MONTH: - return config('database.driver') === 'mysql' ? 'month(created_at)' - : "strftime('%m', created_at)"; - - case self::YEAR: - return config('database.driver') === 'mysql' ? 'year(created_at)' - : "strftime('%Y', created_at)"; - + case self::DAY: return $this->driver === 'mysql' ? 'weekday(created_at)' : "strftime('%w', created_at)"; + case self::WEEK: return $this->driver === 'mysql' ? 'week(created_at)' : "strftime('%W', created_at)"; + case self::MONTH: return $this->driver === 'mysql' ? 'month(created_at)' : "strftime('%m', created_at)"; + case self::YEAR: return $this->driver === 'mysql' ? 'year(created_at)' : "strftime('%Y', created_at)"; default: return ''; } } @@ -271,7 +262,7 @@ private function formatDate(array $data, string $period) if ($period === self::MONTH) { $data->$period = self::MONTHS[intval($data->$period)]; } else if ($period === self::DAY || $period === self::TODAY) { - $data->$period = config('database.driver') === 'mysql' ? self::DAYS[intval($data->$period) + 1] + $data->$period = $this->driver === 'mysql' ? self::DAYS[intval($data->$period) + 1] : self::DAYS[intval($data->$period)]; } else if ($period === self::WEEK) { $data->$period = __('week') . ' ' . $data->$period; diff --git a/core/Testing/ApplicationTestCase.php b/core/Testing/ApplicationTestCase.php index 9fb8f471..32ce7276 100644 --- a/core/Testing/ApplicationTestCase.php +++ b/core/Testing/ApplicationTestCase.php @@ -32,6 +32,8 @@ protected function setUp(): void $this->token = ''; $this->headers = []; + + parent::setUp(); } protected function tearDown(): void @@ -87,14 +89,14 @@ protected function getSessionKey(string $name) public function auth($user) { $this->token = Auth::createToken($user->email); - $this->headers = ['Authorization' => "Bearer {$this->token}"]; + $this->headers = array_merge($this->headers, ['Authorization' => "Bearer $this->token"]); return $this; } public function createFileUpload(string $filename, ?string $mime_type = null, ?string $name = null) { - $this->headers = ['Content-Type' => 'multipart/form-data']; + $this->headers = array_merge($this->headers, ['Content-Type' => 'multipart/form-data']); return curl_file_create($filename, $mime_type, $name); } @@ -216,8 +218,7 @@ public function assertSessionDoesNotExists(string $expected) public function assertSessionHas(string $key, $value) { if (!isset($this->getSession()[$this->getSessionKey($key)])) { - $this->assertFalse(false); - return; + return $this->assertFalse(false); } $this->assertEquals($value, $this->getSession()[$this->getSessionKey($key)]); @@ -226,8 +227,7 @@ public function assertSessionHas(string $key, $value) public function assertSessionDoesNotHave(string $key, $value) { if (!isset($this->getSession()[$this->getSessionKey($key)])) { - $this->assertFalse(false); - return; + return $this->assertFalse(false); } $this->assertNotEquals($value, $this->getSession()[$this->getSessionKey($key)]); diff --git a/resources/stubs/Controller.stub b/resources/stubs/Controller.stub index 3557a79b..148884f4 100644 --- a/resources/stubs/Controller.stub +++ b/resources/stubs/Controller.stub @@ -9,12 +9,12 @@ namespace NAMESPACE; use Core\Http\Request; -use Core\Http\Response\Response; +use Core\Http\Response; class CLASSNAME { public function __invoke(Request $request, Response $response) { - $response->send('Hello from CLASSNAME'); + $response->data('Hello from CLASSNAME')->send(); } } diff --git a/resources/stubs/Validator.stub b/resources/stubs/Validator.stub index 3cea7af7..e10e7c2a 100644 --- a/resources/stubs/Validator.stub +++ b/resources/stubs/Validator.stub @@ -12,6 +12,11 @@ use Core\Http\Validator\Validator; class CLASSNAME extends Validator { + public function __construct() + { + // + } + /** * Validation rules */ diff --git a/routes/auth.php b/routes/auth.php index d5466efe..fce86e4e 100644 --- a/routes/auth.php +++ b/routes/auth.php @@ -8,7 +8,7 @@ use Core\Http\Request; use Core\Routing\Route; -use Core\Http\Response\Response; +use Core\Http\Response; use App\Http\Controllers\Auth\LoginController; use App\Http\Controllers\Auth\LogoutController; use App\Http\Controllers\Auth\RegisterController; @@ -33,7 +33,7 @@ Route::view('/forgot', 'auth.password.forgot'); Route::get('/new', function (Request $request, Response $response) { - $response->view('auth.password.new', $request->only('email')); + $response->view('auth.password.new', $request->only('email'))->send(); }); })->byPrefix('password')->register();