From 0e618062a21b895216565fac683a97fc5860a753 Mon Sep 17 00:00:00 2001 From: eliseekn Date: Sun, 6 Aug 2023 10:08:19 +0000 Subject: [PATCH] Remove spread (...) operator in function parameters --- .../Auth/EmailVerificationController.php | 4 +- .../Auth/ForgotPasswordController.php | 2 +- app/Http/Controllers/Auth/LoginController.php | 4 +- app/Http/Middlewares/CsrfProtection.php | 2 +- .../Validators/Auth/RegisterValidator.php | 2 +- config/routes.php | 2 +- core/Console/Database/Create.php | 2 +- core/Console/Database/Delete.php | 2 +- core/Console/Make/Exception.php | 2 +- core/Console/Make/Helper.php | 2 +- core/Console/Server.php | 2 +- core/Database/Model.php | 13 ++++--- core/Database/QueryBuilder.php | 8 ++-- core/Database/Repository.php | 16 ++++---- core/Http/Request.php | 28 +++++++++----- core/Routing/Route.php | 7 +++- core/Support/Alert.php | 10 ----- core/Support/Auth.php | 6 +-- core/Support/Helpers.php | 18 ++++++++- core/Support/Metrics.php | 38 +++++++++---------- core/Support/Session.php | 3 +- core/Support/Uploader.php | 8 ++-- tests/Application/Auth/AuthenticationTest.php | 4 +- 23 files changed, 102 insertions(+), 83 deletions(-) diff --git a/app/Http/Controllers/Auth/EmailVerificationController.php b/app/Http/Controllers/Auth/EmailVerificationController.php index 44a34df..138b642 100644 --- a/app/Http/Controllers/Auth/EmailVerificationController.php +++ b/app/Http/Controllers/Auth/EmailVerificationController.php @@ -56,7 +56,7 @@ public function notify(Request $request, Response $response): void public function verify(Request $request, Response $response, UpdateAction $updateAction): void { - if (!$request->hasQuery('email', 'token')) { + if (!$request->hasQuery(['email', 'token'])) { $response->data(__('bad_request'))->send(400); } @@ -72,7 +72,7 @@ public function verify(Request $request, Response $response, UpdateAction $updat $token->delete(); - $user = $updateAction->handle(['email_verified' => Carbon::now()->toDateTimeString()], $request->queries('email')); + $user = $updateAction->handle(['email_verified' => Carbon::now()->toDateTimeString()], $request->email); if (!$user) { Alert::default(__('account_not_found'))->error(); diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index 762aad0..c841dca 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -56,7 +56,7 @@ public function notify(Request $request, Response $response): void public function reset(Request $request, Response $response): void { - if (!$request->hasQuery('email', 'token')) { + if (!$request->hasQuery(['email', 'token'])) { $response->data(__('bad_request'))->send(400); } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index db08584..b4dc43d 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -31,7 +31,7 @@ public function authenticate(Request $request, Response $response, LoginValidato { $loginValidator->validate($request->inputs(), $response); - if (Auth::attempt($response, $request->only('email', 'password'), $request->has('remember'))) { + if (Auth::attempt($response, $request->only(['email', 'password']), $request->has('remember'))) { $uri = !Session::has('intended') ? config('app.home') : Session::pull('intended'); Alert::toast(__('welcome', ['name' => Auth::get('name')]))->success(); @@ -39,6 +39,6 @@ public function authenticate(Request $request, Response $response, LoginValidato } Alert::default(__('login_failed'))->error(); - $response->url('/login')->withInputs($request->only('email', 'password'))->withErrors([__('login_failed')])->send(); + $response->url('/login')->withInputs($request->only(['email', 'password']))->withErrors([__('login_failed')])->send(); } } diff --git a/app/Http/Middlewares/CsrfProtection.php b/app/Http/Middlewares/CsrfProtection.php index e7bbd14..bf593f3 100644 --- a/app/Http/Middlewares/CsrfProtection.php +++ b/app/Http/Middlewares/CsrfProtection.php @@ -26,7 +26,7 @@ public function handle(Request $request): void return; } - if (!$request->filled('_csrf_token')) { + if (!$request->filled(['_csrf_token'])) { throw new MissingCsrfTokenException(); } diff --git a/app/Http/Validators/Auth/RegisterValidator.php b/app/Http/Validators/Auth/RegisterValidator.php index 4f77678..a4d6fb1 100644 --- a/app/Http/Validators/Auth/RegisterValidator.php +++ b/app/Http/Validators/Auth/RegisterValidator.php @@ -16,7 +16,7 @@ class RegisterValidator extends Validator public function __construct() { $this->addCustomRule('unique', function($field, array $input, array $params, $value) { - $data = (new Repository($params[0]))->select('*')->where($field, $value); + $data = (new Repository($params[0]))->select(['*'])->where($field, $value); return !$data->exists(); }, 'This {field} is already registered'); } diff --git a/config/routes.php b/config/routes.php index 54a3d8a..36f7af6 100644 --- a/config/routes.php +++ b/config/routes.php @@ -7,7 +7,7 @@ */ /** - * Routes paths configuration + * Routes paths configuration with base directory '/views' */ return [ diff --git a/core/Console/Database/Create.php b/core/Console/Database/Create.php index 5ac0866..fabe170 100644 --- a/core/Console/Database/Create.php +++ b/core/Console/Database/Create.php @@ -35,7 +35,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $databases = $input->getArgument('database'); - if (is_null($databases) || empty($databases)) { + if (empty($databases)) { $db = config('app.env') !== 'test' ? config('database.name') : config('database.name') . config('tests.database.suffix') ; diff --git a/core/Console/Database/Delete.php b/core/Console/Database/Delete.php index ab024bc..2a07179 100644 --- a/core/Console/Database/Delete.php +++ b/core/Console/Database/Delete.php @@ -35,7 +35,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $databases = $input->getArgument('database'); - if (is_null($databases) || empty($databases)) { + if (empty($databases)) { $db = config('app.env') !== 'test' ? config('database.name') : config('database.name') . config('tests.database.suffix') ; diff --git a/core/Console/Make/Exception.php b/core/Console/Make/Exception.php index a3a81b5..567fad8 100644 --- a/core/Console/Make/Exception.php +++ b/core/Console/Make/Exception.php @@ -33,7 +33,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $exception = $input->getArgument('exception'); $message = $input->getOption('message'); - list(, $class) = Make::generateClass($exception, ''); + list(, $class) = Make::generateClass($exception); if (!Make::createException($exception, $message)) { $output->writeln('Failed to create exception "' . $class . '"'); diff --git a/core/Console/Make/Helper.php b/core/Console/Make/Helper.php index d48fc65..bb17f7a 100644 --- a/core/Console/Make/Helper.php +++ b/core/Console/Make/Helper.php @@ -31,7 +31,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $helpers = $input->getArgument('helper'); foreach ($helpers as $helper) { - list(, $class) = Make::generateClass($helper, ''); + list(, $class) = Make::generateClass($helper); if (!Make::createHelper($helper)) { $output->writeln('Failed to create helper "' . $class . '"'); diff --git a/core/Console/Server.php b/core/Console/Server.php index b405baa..ef8ab60 100644 --- a/core/Console/Server.php +++ b/core/Console/Server.php @@ -27,7 +27,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $host = $input->getOption('host') ?? '127.0.0.1'; $port = $input->getOption('port') ?? 8080; - $process = new Process(['php', '-S', "{$host}:{$port}"]); + $process = new Process(['php', '-S', "$host:$port"]); $process->setTimeout(null); $process->start(); diff --git a/core/Database/Model.php b/core/Database/Model.php index a0ba82f..ad4eb99 100644 --- a/core/Database/Model.php +++ b/core/Database/Model.php @@ -80,9 +80,9 @@ public static function latest(string $column = 'id', $subquery = null): array|fa return self::select('*')->subQuery($subquery)->latest($column)->getAll(); } - public static function select(string ...$columns): Repository + public static function select(array|string $columns): Repository { - return (new Repository(static::$table))->select(...$columns); + return (new Repository(static::$table))->select($columns); } public static function where(string $column, $operator = null, $value = null): Repository @@ -231,13 +231,16 @@ public function decrement(string $column, $value = null): void $this->{$column} = $this->{$column} - $value; } - public function toArray(string ...$attributes): array + public function toArray(array|string $attributes = null): array { $data = (array) $this; - if (is_null($this->id)) unset($data['id']); + if (is_null($this->id)) { + unset($data['id']); + } - if (!empty($attributes)) { + if (!is_null($attributes)) { + $attributes = parse_array($attributes); $d = []; foreach ($attributes as $attribute) { diff --git a/core/Database/QueryBuilder.php b/core/Database/QueryBuilder.php index 40551c7..7ae2d50 100644 --- a/core/Database/QueryBuilder.php +++ b/core/Database/QueryBuilder.php @@ -97,12 +97,13 @@ public static function deleteColumn(string $table, string $column): self return new self(); } - public function select(string ...$columns): self + public function select(array|string $columns): self { + $columns = parse_array($columns); self::$query = 'SELECT '; foreach ($columns as $column) { - self::$query .= "{$column}, "; + self::$query .= "$column, "; } self::$query = rtrim(self::$query, ', '); @@ -469,8 +470,9 @@ public function orderBy(string $column, string $direction): self return $this; } - public function groupBy(string ...$columns): self + public function groupBy(array|string $columns): self { + $columns = parse_array($columns); self::$query .= ' GROUP BY '; foreach ($columns as $column) { diff --git a/core/Database/Repository.php b/core/Database/Repository.php index d2515ee..e789718 100644 --- a/core/Database/Repository.php +++ b/core/Database/Repository.php @@ -21,20 +21,20 @@ class Repository public function __construct(private readonly string $table) {} - public function select(string ...$columns): self + public function select(array|string $columns): self { - $this->qb = QueryBuilder::table($this->table)->select(...$columns); + $this->qb = QueryBuilder::table($this->table)->select($columns); return $this; } - public function selectOne(string ...$columns): mixed + public function selectOne(array|string $columns): mixed { - return $this->select(...$columns)->get(); + return $this->select($columns)->get(); } - public function selectAll(string ...$columns): array|false + public function selectAll(array|string $columns): array|false { - return $this->select(...$columns)->getAll(); + return $this->select($columns)->getAll(); } public function selectRaw(string $query, array $args = []): self @@ -561,9 +561,9 @@ public function latest(string $column = 'id'): self return $this->orderDesc($column); } - public function groupBy(string ...$columns): self + public function groupBy(array|string $columns): self { - $this->qb->groupBy(...$columns); + $this->qb->groupBy($columns); return $this; } diff --git a/core/Http/Request.php b/core/Http/Request.php index 64c5f1a..bb29d5b 100644 --- a/core/Http/Request.php +++ b/core/Http/Request.php @@ -160,8 +160,9 @@ public function remoteIP(): string return $this->headers('REMOTE_ADDR', ''); } - public function has(string ...$items): bool + public function has(array|string $items): bool { + $items = parse_array($items); $result = false; foreach ($items as $item) { @@ -171,8 +172,9 @@ public function has(string ...$items): bool return $result; } - public function hasQuery(string ...$items): bool + public function hasQuery(array|string $items): bool { + $items = parse_array($items); $result = false; foreach ($items as $item) { @@ -182,8 +184,9 @@ public function hasQuery(string ...$items): bool return $result; } - public function hasInput(string ...$items): bool + public function hasInput(array|string $items): bool { + $items = parse_array($items); $result = false; foreach ($items as $item) { @@ -193,11 +196,14 @@ public function hasInput(string ...$items): bool return $result; } - public function filled(string ...$items): bool + public function filled(array|string $items): bool { - $result = $this->has(...$items); + $items = parse_array($items); + $result = $this->has($items); - if (!$result) return false; + if (!$result) { + return false; + } foreach ($items as $item) { $result = !empty($this->{$item}); @@ -225,8 +231,9 @@ public function set(string $item, $value): void $this->{$item} = $value; } - public function only(string ...$items): array + public function only(array|string $items): array { + $items = parse_array($items); $result = []; foreach ($items as $item) { @@ -238,11 +245,14 @@ public function only(string ...$items): array return $result; } - public function except(string ...$items): array + public function except(array|string $items): array { + $items = parse_array($items); $result = []; - if (empty($this->all())) return $result; + if (empty($this->all())) { + return $result; + } foreach ($items as $item) { foreach ($this->all() as $key => $input) { diff --git a/core/Routing/Route.php b/core/Routing/Route.php index 8aa3c61..9f88a36 100644 --- a/core/Routing/Route.php +++ b/core/Routing/Route.php @@ -99,14 +99,17 @@ public static function group($callback): self return new static(); } - public function middleware(string ...$middlewares): self + public function middleware(array|string $middlewares): self { + $middlewares = parse_array($middlewares); static::$tmp_routes[static::$route]['middlewares'] = $middlewares; return $this; } - public function byMiddleware(string ...$middlewares): self + public function byMiddleware(array|string $middlewares): self { + $middlewares = parse_array($middlewares); + foreach (static::$tmp_routes as $route => $options) { if (isset($options['middlewares'])) { static::$tmp_routes[$route]['middlewares'] = array_merge($middlewares, $options['middlewares']); diff --git a/core/Support/Alert.php b/core/Support/Alert.php index 9783376..4a86fc8 100644 --- a/core/Support/Alert.php +++ b/core/Support/Alert.php @@ -25,16 +25,6 @@ public static function default($message, bool $dismiss = true): self return new self(); } - - public static function popup($message): self - { - self::$alert = [ - 'message' => $message, - 'display' => 'popup' - ]; - - return new self(); - } public static function toast($message) : self { diff --git a/core/Support/Auth.php b/core/Support/Auth.php index 106fcb3..cfd8fbd 100644 --- a/core/Support/Auth.php +++ b/core/Support/Auth.php @@ -36,13 +36,13 @@ public static function attempt(Response $response, array $credentials, bool $rem $response ->back() ->with('auth_attempts_timeout', Carbon::now()->addMinutes(config('security.auth.unlock_timeout'))->toDateTimeString()) - ->send(302); + ->send(); } return false; } - Session::forget('auth_attempts', 'auth_attempts_timeout'); + Session::forget(['auth_attempts', 'auth_attempts_timeout']); Session::create('user', $user); if ($remember) { @@ -127,7 +127,7 @@ public static function get(?string $key = null): mixed public static function forget(): void { - Session::forget('user', 'history', 'csrf_token'); + Session::forget(['user', 'history', 'csrf_token']); if (self::remember()) { Cookies::delete('user'); diff --git a/core/Support/Helpers.php b/core/Support/Helpers.php index baea388..064cf4c 100644 --- a/core/Support/Helpers.php +++ b/core/Support/Helpers.php @@ -84,9 +84,9 @@ function session_has(string $name): bool } if (!function_exists('session_forget')) { - function session_forget(string ...$names): void + function session_forget(array|string $names): void { - Session::forget(...$names); + Session::forget($names); } } @@ -461,6 +461,20 @@ function env(string $key, $default = null): mixed } } +if (!function_exists('parse_array')) { + /** + * Convert string to array + */ + function parse_array(array|string $value): array + { + if (is_array($value)) { + return $value; + } + + return [$value]; + } +} + /** * Laravel helpers from \Illuminate\Support\helpers.php */ diff --git a/core/Support/Metrics.php b/core/Support/Metrics.php index f140bce..2b3ea16 100644 --- a/core/Support/Metrics.php +++ b/core/Support/Metrics.php @@ -71,21 +71,21 @@ public function getTrends(string $column, string $type, string $period, int $int switch ($period) { case self::TODAY: - $data = $qb->select($type . '(' . $column . ') AS data', $this->getPeriod(self::DAY)) + $data = $qb->select([$type . '(' . $column . ') AS data', $this->getPeriod(self::DAY)]) ->where('date(created_at)', Carbon::now()->toDateString()) ->subQuery(function ($q) use ($query) { if (!empty($query)) { $q->rawQuery($query[0], $query[1]); } }) - ->groupBy(self::DAY) + ->groupBy([self::DAY]) ->orderBy(self::DAY, 'asc') ->fetchAll(); return $this->formatDate($data, self::DAY); case self::DAY: - $qb->select($type . '(' . $column . ') AS data', $this->getPeriod(self::DAY)); + $qb->select([$type . '(' . $column . ') AS data', $this->getPeriod(self::DAY)]); $interval > 0 ? $qb->where('date(created_at)', '>=', Carbon::now()->subDays($interval)->toDateString()) : $qb->whereColumn($this->formatPeriod(self::YEAR))->like($year) @@ -97,14 +97,14 @@ public function getTrends(string $column, string $type, string $period, int $int $q->rawQuery($query[0], $query[1]); } }) - ->groupBy(self::DAY) + ->groupBy([self::DAY]) ->orderBy(self::DAY, 'asc') ->fetchAll(); return $this->formatDate($data, self::DAY); case self::WEEK: - $qb->select($type . '(' . $column . ') AS data', $this->getPeriod(self::WEEK)); + $qb->select([$type . '(' . $column . ') AS data', $this->getPeriod(self::WEEK)]); $interval > 0 ? $qb->where('date(created_at)', '>', Carbon::now()->subWeeks($interval)->toDateString()) : $qb->whereColumn($this->formatPeriod(self::YEAR))->like($year) @@ -115,14 +115,14 @@ public function getTrends(string $column, string $type, string $period, int $int $q->rawQuery($query[0], $query[1]); } }) - ->groupBy(self::WEEK) + ->groupBy([self::WEEK]) ->orderBy(self::WEEK, 'asc') ->fetchAll(); return $this->formatDate($data, self::WEEK); case self::MONTH: - $qb->select($type . '(' . $column . ') AS data', $this->getPeriod(self::MONTH)); + $qb->select([$type . '(' . $column . ') AS data', $this->getPeriod(self::MONTH)]); $interval > 0 ? $qb->where($this->formatPeriod(self::MONTH), '>', Carbon::now()->subMonths($interval)->month) : $qb->where($this->formatPeriod(self::YEAR), $year); @@ -132,14 +132,14 @@ public function getTrends(string $column, string $type, string $period, int $int $q->rawQuery($query[0], $query[1]); } }) - ->groupBy(self::MONTH) + ->groupBy([self::MONTH]) ->orderBy(self::MONTH, 'asc') ->fetchAll(); return $this->formatDate($data, self::MONTH); case self::YEAR: - $qb->select($type . '(' . $column . ') AS data', $this->getPeriod(self::YEAR)); + $qb->select([$type . '(' . $column . ') AS data', $this->getPeriod(self::YEAR)]); if ($interval > 0) { $qb->where($this->formatPeriod(self::YEAR), '>', Carbon::now()->subYears($interval)->year); @@ -150,7 +150,7 @@ public function getTrends(string $column, string $type, string $period, int $int $q->rawQuery($query[0], $query[1]); } }) - ->groupBy(self::YEAR) + ->groupBy([self::YEAR]) ->orderBy(self::YEAR, 'asc') ->fetchAll(); @@ -245,18 +245,18 @@ private function getPeriod(string $period): string private function formatPeriod(string $period): string { - switch ($period) { - 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 ''; - } + return match ($period) { + self::DAY => $this->driver === 'mysql' ? 'weekday(created_at)' : "strftime('%w', created_at)", + self::WEEK => $this->driver === 'mysql' ? 'week(created_at)' : "strftime('%W', created_at)", + self::MONTH => $this->driver === 'mysql' ? 'month(created_at)' : "strftime('%m', created_at)", + self::YEAR => $this->driver === 'mysql' ? 'year(created_at)' : "strftime('%Y', created_at)", + default => '', + }; } private function formatDate(array $data, string $period): array { - $data = array_map(function ($data) use ($period) { + return array_map(function ($data) use ($period) { $data->data = intval($data->data); if ($period === self::MONTH) { @@ -272,7 +272,5 @@ private function formatDate(array $data, string $period): array return $data; }, $data); - - return $data; } } diff --git a/core/Support/Session.php b/core/Support/Session.php index 26122d0..8023a3c 100644 --- a/core/Support/Session.php +++ b/core/Support/Session.php @@ -40,8 +40,9 @@ public static function has(string $name): bool return isset($_SESSION[strtolower(config('app.name')) . '_' . $name]); } - public static function forget(string ...$names): void + public static function forget(array|string $names): void { + $names = parse_array($names); self::start(); foreach ($names as $name) { diff --git a/core/Support/Uploader.php b/core/Support/Uploader.php index 20aebac..763415b 100644 --- a/core/Support/Uploader.php +++ b/core/Support/Uploader.php @@ -8,8 +8,6 @@ namespace Core\Support; -use Core\Support\Storage; - /** * Manage uploaded files */ @@ -17,7 +15,7 @@ class Uploader { public string $filename = ''; - public function __construct(private array $file = [], private array $allowed_extensions = []) {} + public function __construct(private readonly array $file = [], private readonly array $allowed_extensions = []) {} public function getOriginalFilename(): string { @@ -80,11 +78,11 @@ public function getError(): string UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder', UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk', 8 => 'File upload stopped by extension', - default => 'Unknow error', + default => 'Unknown error', }; } - return 'Unknow error'; + return 'Unknown error'; } public function save(?string $destination = null, ?string $filename = null): bool diff --git a/tests/Application/Auth/AuthenticationTest.php b/tests/Application/Auth/AuthenticationTest.php index 15ea4f3..1b158f2 100644 --- a/tests/Application/Auth/AuthenticationTest.php +++ b/tests/Application/Auth/AuthenticationTest.php @@ -20,7 +20,7 @@ public function test_can_not_authenticate_with_unregistered_user_credentials(): { $user = (new UserFactory())->make(['password' => 'password']); - $client = $this->post('authenticate', $user->toArray('email', 'password')); + $client = $this->post('authenticate', $user->toArray(['email', 'password'])); $client->assertSessionHasErrors(); $client->assertRedirectedToUrl(url('login')); } @@ -47,7 +47,7 @@ public function test_can_register_user(): void $client->assertRedirectedToUrl(url('email/notify?email=' . $user->email)); } - $this->assertDatabaseHas('users', $user->toArray('name', 'email')); + $this->assertDatabaseHas('users', $user->toArray(['name', 'email'])); } public function test_can_logout(): void