From 95fe3477a02d7763311a263bbbee60b5b1188536 Mon Sep 17 00:00:00 2001 From: loks0n <22452787+loks0n@users.noreply.github.com> Date: Fri, 24 Apr 2026 12:35:35 +0100 Subject: [PATCH] Chore: Add Rector with safe rule bucket and CI refactor check Introduces Rector for automated refactoring, wired up via: - rector.php config targeting src/ and tests/ with PHP 8.3 level set plus CODE_QUALITY, DEAD_CODE, EARLY_RETURN, and INSTANCEOF sets. Rules with BC risk or behavioural shifts (readonly, explicit bool compare, empty() rewrites, type-hint additions, random_int swaps) are explicitly skipped. - composer refactor / refactor:check scripts. - Checks / Refactor CI job running rector in dry-run. - Safe-bucket refactor applied across the codebase: strict_types declarations, #[\Override] attributes, str_contains / str_starts_with, null-coalescing, match over switch where safe, dead code removal, and docblock cleanup. --- .github/workflows/ci.yml | 28 ++++ composer.json | 3 + composer.lock | 68 +++++++++- rector.php | 71 ++++++++++ src/Http/Adapter.php | 2 + src/Http/Adapter/FPM/Request.php | 76 ++--------- src/Http/Adapter/FPM/Response.php | 14 +- src/Http/Adapter/FPM/Server.php | 5 +- src/Http/Adapter/Swoole/Request.php | 66 +-------- src/Http/Adapter/Swoole/Response.php | 12 -- src/Http/Adapter/SwooleCoroutine/Request.php | 2 + src/Http/Adapter/SwooleCoroutine/Response.php | 2 + src/Http/Adapter/SwooleCoroutine/Server.php | 2 +- src/Http/Exception.php | 2 + src/Http/Files.php | 31 +---- src/Http/Http.php | 121 ++--------------- src/Http/Request.php | 125 +++--------------- src/Http/Response.php | 101 +------------- src/Http/Route.php | 33 ----- src/Http/Router.php | 16 --- src/Http/View.php | 57 ++------ tests/HttpTest.php | 8 +- tests/RequestTest.php | 1 - tests/RouterTest.php | 2 + tests/UtopiaFPMRequestTest.php | 7 +- tests/e2e/Client.php | 8 +- tests/e2e/ResponseFPMTest.php | 2 + tests/e2e/ResponseSwooleTest.php | 2 + tests/e2e/init.php | 2 +- tests/e2e/server-fpm.php | 2 + tests/e2e/server-swoole.php | 2 + 31 files changed, 250 insertions(+), 623 deletions(-) create mode 100644 rector.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7ff1fe3..291ab1e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,34 @@ jobs: - name: PHPStan run: composer analyze + refactor: + name: Checks / Refactor + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + extensions: swoole + coverage: none + + - name: Get composer cache directory + id: composer-cache + run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT" + + - uses: actions/cache@v5 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: composer-${{ hashFiles('composer.lock') }} + restore-keys: composer- + + - name: Install dependencies + run: composer install --prefer-dist --no-progress --no-interaction --ignore-platform-req=ext-opentelemetry + + - name: Rector (dry run) + run: composer refactor:check + unit: name: Tests / Unit / PHP ${{ matrix.php }} runs-on: ubuntu-latest diff --git a/composer.json b/composer.json index bfdaf2d..f4dbb75 100644 --- a/composer.json +++ b/composer.json @@ -25,6 +25,8 @@ "format": "vendor/bin/pint", "format:check": "vendor/bin/pint --test", "analyze": "vendor/bin/phpstan analyse -c phpstan.neon --memory-limit 512M", + "refactor": "vendor/bin/rector process", + "refactor:check": "vendor/bin/rector process --dry-run", "test": "vendor/bin/phpunit --configuration phpunit.xml" }, "require": { @@ -54,6 +56,7 @@ "laravel/pint": "1.*", "phpstan/phpstan": "^2.0", "phpunit/phpunit": "^9.5.25", + "rector/rector": "^2.0", "swoole/ide-helper": "4.8.3" } } diff --git a/composer.lock b/composer.lock index 394f4e0..0ee4ed2 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "1a86b04c686d8b6853cbeaeb62a137b9", + "content-hash": "3634d82a116d09c1fb571f7b0294ee89", "packages": [ { "name": "brick/math", @@ -2977,6 +2977,66 @@ ], "time": "2026-01-27T05:45:00+00:00" }, + { + "name": "rector/rector", + "version": "2.4.2", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "e645b6463c6a88ea5b44b17d3387d35a912c7946" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/e645b6463c6a88ea5b44b17d3387d35a912c7946", + "reference": "e645b6463c6a88ea5b44b17d3387d35a912c7946", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0", + "phpstan/phpstan": "^2.1.48" + }, + "conflict": { + "rector/rector-doctrine": "*", + "rector/rector-downgrade-php": "*", + "rector/rector-phpunit": "*", + "rector/rector-symfony": "*" + }, + "suggest": { + "ext-dom": "To manipulate phpunit.xml via the custom-rule command" + }, + "bin": [ + "bin/rector" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "homepage": "https://getrector.com/", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/2.4.2" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "time": "2026-04-16T13:07:34+00:00" + }, { "name": "sebastian/cli-parser", "version": "1.0.2", @@ -4083,17 +4143,17 @@ ], "aliases": [], "minimum-stability": "stable", - "stability-flags": [], + "stability-flags": {}, "prefer-stable": false, "prefer-lowest": false, "platform": { "php": ">=8.3" }, - "platform-dev": [], + "platform-dev": {}, "platform-overrides": { "php": "8.3", "ext-opentelemetry": "1.0.0", "ext-protobuf": "4.26.1" }, - "plugin-api-version": "2.6.0" + "plugin-api-version": "2.9.0" } diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..416d1a7 --- /dev/null +++ b/rector.php @@ -0,0 +1,71 @@ +withPaths([ + __DIR__ . '/src', + __DIR__ . '/tests', + ]) + ->withPhpSets(php83: true) + ->withSets([ + LevelSetList::UP_TO_PHP_83, + SetList::CODE_QUALITY, + SetList::DEAD_CODE, + SetList::EARLY_RETURN, + SetList::INSTANCEOF, + ]) + ->withImportNames(importShortClasses: false, removeUnusedImports: true) + ->withSkip([ + // BC breaks in a published library + ReadOnlyPropertyRector::class, + ReadOnlyClassRector::class, + + // Changes truthy semantics — "0", null, "" behave differently + ExplicitBoolCompareRector::class, + SimplifyEmptyCheckOnEmptyArrayRector::class, + + // Can throw TypeError on previously-working callers (library is public API) + TypedPropertyFromAssignsRector::class, + TypedPropertyFromStrictConstructorRector::class, + ParamTypeByParentCallTypeRector::class, + + // Different distribution and failure mode than rand() + RandomFunctionRector::class, + + // Subtle casting/control-flow shifts — apply manually + RecastingRemovalRector::class, + FlipTypeControlToUseExclusiveTypeRector::class, + SwitchNegatedTernaryRector::class, + StringClassNameToClassConstantRector::class, + + // Promoted properties / nullable defaults — BC shape changes for library + ClassPropertyAssignToConstructorPromotionRector::class, + RestoreDefaultNullToNullableTypePropertyRector::class, + + // empty() replacement rarely covers every falsy case Rector's type info misses + DisallowedEmptyRuleFixerRector::class, + + // Throws TypeError when args are objects/arrays — review per-call + NullToStrictStringFuncCallArgRector::class, + ]); diff --git a/src/Http/Adapter.php b/src/Http/Adapter.php index a56c2ac..0b0e478 100755 --- a/src/Http/Adapter.php +++ b/src/Http/Adapter.php @@ -1,5 +1,7 @@ getServer('REQUEST_URI') ?? ''; @@ -172,9 +148,6 @@ public function getURI(): string * Get Path * * Return HTTP request path - * - * @param string $uri - * @return static */ public function setURI(string $uri): static { @@ -188,21 +161,17 @@ public function setURI(string $uri): static * * Method for querying upload files data. If $key is not found empty array will be returned. * - * @param string $key * @return array */ public function getFiles(string $key): array { - return (isset($_FILES[$key])) ? $_FILES[$key] : []; + return $_FILES[$key] ?? []; } /** * Get Referer * * Return HTTP referer header - * - * @param string $default - * @return string */ public function getReferer(string $default = ''): string { @@ -213,9 +182,6 @@ public function getReferer(string $default = ''): string * Get Origin * * Return HTTP origin header - * - * @param string $default - * @return string */ public function getOrigin(string $default = ''): string { @@ -226,9 +192,6 @@ public function getOrigin(string $default = ''): string * Get User Agent * * Return HTTP user agent header - * - * @param string $default - * @return string */ public function getUserAgent(string $default = ''): string { @@ -239,9 +202,6 @@ public function getUserAgent(string $default = ''): string * Get Accept * * Return HTTP accept header - * - * @param string $default - * @return string */ public function getAccept(string $default = ''): string { @@ -252,24 +212,16 @@ public function getAccept(string $default = ''): string * Get cookie * * Method for querying HTTP cookie parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param string $default - * @return string */ public function getCookie(string $key, string $default = ''): string { - return (isset($_COOKIE[$key])) ? $_COOKIE[$key] : $default; + return $_COOKIE[$key] ?? $default; } /** * Get header * * Method for querying HTTP header parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param string $default - * @return string */ public function getHeader(string $key, string $default = ''): string { @@ -288,10 +240,6 @@ public function getHeader(string $key, string $default = ''): string * Set header * * Method for adding HTTP header parameters. - * - * @param string $key - * @param string $value - * @return static */ public function addHeader(string $key, string $value): static { @@ -304,9 +252,6 @@ public function addHeader(string $key, string $value): static * Remvoe header * * Method for removing HTTP header parameters. - * - * @param string $key - * @return static */ public function removeHeader(string $key): static { @@ -339,14 +284,10 @@ protected function generateInput(): array $this->rawPayload = \file_get_contents('php://input') ?: ''; - switch ($contentType) { - case 'application/json': - $this->payload = \json_decode($this->rawPayload, true); - break; - default: - $this->payload = $_POST; - break; - } + $this->payload = match ($contentType) { + 'application/json' => \json_decode($this->rawPayload, true), + default => $_POST, + }; if (empty($this->payload)) { // Make sure we return same data type even if json payload is empty or failed $this->payload = []; @@ -369,6 +310,7 @@ protected function generateInput(): array * * @return array> */ + #[\Override] protected function generateHeaders(): array { if (null === $this->headers) { @@ -380,7 +322,7 @@ protected function generateHeaders(): array $headers = []; foreach ($_SERVER as $name => $value) { - if (\substr($name, 0, 5) == 'HTTP_') { + if (str_starts_with($name, 'HTTP_')) { $headers[\str_replace(' ', '-', \strtolower(\str_replace('_', ' ', \substr($name, 5))))] = $value; } } diff --git a/src/Http/Adapter/FPM/Response.php b/src/Http/Adapter/FPM/Response.php index 461c4a3..f0aaaa1 100644 --- a/src/Http/Adapter/FPM/Response.php +++ b/src/Http/Adapter/FPM/Response.php @@ -1,5 +1,7 @@ $value - * @return void */ public function sendHeader(string $key, mixed $value): void { @@ -72,10 +65,7 @@ public function sendHeader(string $key, mixed $value): void * * Output Cookie * - * @param string $name - * @param string $value * @param array $options - * @return void */ protected function sendCookie(string $name, string $value, array $options): void { diff --git a/src/Http/Adapter/FPM/Server.php b/src/Http/Adapter/FPM/Server.php index 4b19e8e..2b56568 100755 --- a/src/Http/Adapter/FPM/Server.php +++ b/src/Http/Adapter/FPM/Server.php @@ -30,8 +30,5 @@ public function getContainer(): Container return $this->container; } - public function start(): void - { - return; - } + public function start(): void {} } diff --git a/src/Http/Adapter/Swoole/Request.php b/src/Http/Adapter/Swoole/Request.php index 45c89e7..e8ee638 100644 --- a/src/Http/Adapter/Swoole/Request.php +++ b/src/Http/Adapter/Swoole/Request.php @@ -9,8 +9,6 @@ class Request extends UtopiaRequest { /** * Swoole Request Object - * - * @var SwooleRequest */ protected SwooleRequest $swoole; @@ -26,8 +24,6 @@ public function __construct(SwooleRequest $request) * Get raw payload * * Method for getting the HTTP request payload as a raw string. - * - * @return string */ public function getRawPayload(): string { @@ -38,10 +34,6 @@ public function getRawPayload(): string * Get server * * Method for querying server parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param string|null $default - * @return string|null */ public function getServer(string $key, ?string $default = null): ?string { @@ -52,10 +44,6 @@ public function getServer(string $key, ?string $default = null): ?string * Set server * * Method for setting server parameters. - * - * @param string $key - * @param string $value - * @return static */ public function setServer(string $key, string $value): static { @@ -101,8 +89,6 @@ public function getIP(): string * Returns request protocol. * Support HTTP_X_FORWARDED_PROTO header usually return * from different proxy servers or PHP default REQUEST_SCHEME - * - * @return string */ public function getProtocol(): string { @@ -122,8 +108,6 @@ public function getProtocol(): string * Get Port * * Returns request port. - * - * @return string */ public function getPort(): string { @@ -134,8 +118,6 @@ public function getPort(): string * Get Hostname * * Returns request hostname. - * - * @return string */ public function getHostname(): string { @@ -147,8 +129,6 @@ public function getHostname(): string * Get Method * * Return HTTP request method - * - * @return string */ public function getMethod(): string { @@ -159,9 +139,6 @@ public function getMethod(): string * Set method * * Set HTTP request method - * - * @param string $method - * @return static */ public function setMethod(string $method): static { @@ -174,9 +151,8 @@ public function setMethod(string $method): static * Get URI * * Return HTTP request URI - * - * @return string */ + #[\Override] public function getURI(): string { return $this->getServer('request_uri') ?? ''; @@ -186,9 +162,6 @@ public function getURI(): string * Set URI * * Set HTTP request URI - * - * @param string $uri - * @return static */ public function setURI(string $uri): static { @@ -201,8 +174,6 @@ public function setURI(string $uri): static * Get Referer * * Return HTTP referer header - * - * @return string */ public function getReferer(string $default = ''): string { @@ -213,8 +184,6 @@ public function getReferer(string $default = ''): string * Get Origin * * Return HTTP origin header - * - * @return string */ public function getOrigin(string $default = ''): string { @@ -225,8 +194,6 @@ public function getOrigin(string $default = ''): string * Get User Agent * * Return HTTP user agent header - * - * @return string */ public function getUserAgent(string $default = ''): string { @@ -237,8 +204,6 @@ public function getUserAgent(string $default = ''): string * Get Accept * * Return HTTP accept header - * - * @return string */ public function getAccept(string $default = ''): string { @@ -264,10 +229,6 @@ public function getFiles($key): array * Get cookie * * Method for querying HTTP cookie parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param string $default - * @return string */ public function getCookie(string $key, string $default = ''): string { @@ -280,10 +241,6 @@ public function getCookie(string $key, string $default = ''): string * Get header * * Method for querying HTTP header parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param string $default - * @return string */ public function getHeader(string $key, string $default = ''): string { @@ -292,10 +249,6 @@ public function getHeader(string $key, string $default = ''): string /** * Method for adding HTTP header parameters. - * - * @param string $key - * @param string $value - * @return static */ public function addHeader(string $key, string $value): static { @@ -306,9 +259,6 @@ public function addHeader(string $key, string $value): static /** * Method for removing HTTP header parameters. - * - * @param string $key - * @return static */ public function removeHeader(string $key): static { @@ -344,15 +294,10 @@ protected function generateInput(): array $length = (empty($length)) ? strlen($contentType) : $length; $contentType = substr($contentType, 0, $length); - switch ($contentType) { - case 'application/json': - $this->payload = json_decode(strval($this->swoole->rawContent()), true); - break; - - default: - $this->payload = $this->swoole->post; - break; - } + $this->payload = match ($contentType) { + 'application/json' => json_decode(strval($this->swoole->rawContent()), true), + default => $this->swoole->post, + }; if (empty($this->payload)) { // Make sure we return same data type even if json payload is empty or failed $this->payload = []; @@ -375,6 +320,7 @@ protected function generateInput(): array * * @return array */ + #[\Override] protected function generateHeaders(): array { return $this->swoole->header; diff --git a/src/Http/Adapter/Swoole/Response.php b/src/Http/Adapter/Swoole/Response.php index 3eb2041..d72615a 100644 --- a/src/Http/Adapter/Swoole/Response.php +++ b/src/Http/Adapter/Swoole/Response.php @@ -31,7 +31,6 @@ public function getSwooleResponse(): SwooleResponse /** * Write * - * @param string $content * @return bool False if write cannot complete, such as request ended by client */ public function write(string $content): bool @@ -41,9 +40,6 @@ public function write(string $content): bool /** * End - * - * @param string|null $content - * @return void */ public function end(?string $content = null): void { @@ -52,9 +48,6 @@ public function end(?string $content = null): void /** * Send Status Code - * - * @param int $statusCode - * @return void */ protected function sendStatus(int $statusCode): void { @@ -64,9 +57,7 @@ protected function sendStatus(int $statusCode): void /** * Send Header * - * @param string $key * @param string|array $value - * @return void */ public function sendHeader(string $key, mixed $value): void { @@ -78,10 +69,7 @@ public function sendHeader(string $key, mixed $value): void * * Send a cookie * - * @param string $name - * @param string $value * @param array $options - * @return void */ protected function sendCookie(string $name, string $value, array $options): void { diff --git a/src/Http/Adapter/SwooleCoroutine/Request.php b/src/Http/Adapter/SwooleCoroutine/Request.php index 8522b2e..b176e52 100644 --- a/src/Http/Adapter/SwooleCoroutine/Request.php +++ b/src/Http/Adapter/SwooleCoroutine/Request.php @@ -1,5 +1,7 @@ $settings diff --git a/src/Http/Exception.php b/src/Http/Exception.php index 98814f4..657cd15 100644 --- a/src/Http/Exception.php +++ b/src/Http/Exception.php @@ -1,5 +1,7 @@ loaded)) { - return false; - } - - return true; + return array_key_exists($uri, $this->loaded); } /** * Get file contents. * - * @param string $uri * @return string - * * @throws \Exception */ public function getFileContents(string $uri): mixed @@ -176,9 +153,7 @@ public function getFileContents(string $uri): mixed /** * Get file MIME type. * - * @param string $uri * @return string - * * @throws \Exception */ public function getFileMimeType(string $uri): mixed @@ -192,8 +167,6 @@ public function getFileMimeType(string $uri): mixed /** * Reset. - * - * @return void */ public function reset(): void { diff --git a/src/Http/Http.php b/src/Http/Http.php index 5134b8e..da93d66 100755 --- a/src/Http/Http.php +++ b/src/Http/Http.php @@ -44,9 +44,6 @@ class Http public const MODE_TYPE_PRODUCTION = 'production'; - /** - * @var Files - */ protected Files $files; protected Container $container; @@ -55,8 +52,6 @@ class Http /** * Current running mode - * - * @var string */ protected static string $mode = ''; @@ -114,16 +109,12 @@ class Http * Route * * Memory cached result for chosen route - * - * @var Route|null */ protected ?Route $route = null; /** * Wildcard route * If set, this get's executed if no other route is matched - * - * @var Route|null */ protected static ?Route $wildcardRoute = null; @@ -144,16 +135,10 @@ class Http private Histogram $responseBodySize; - /** - * @var Adapter - */ protected Adapter $server; /** * Http - * - * @param Adapter $server - * @param string $timezone */ public function __construct(Adapter $server, string $timezone) { @@ -166,9 +151,6 @@ public function __construct(Adapter $server, string $timezone) /** * Set telemetry adapter. - * - * @param Telemetry $telemetry - * @return void */ public function setTelemetry(Telemetry $telemetry): void { @@ -216,9 +198,6 @@ public function setCompressionSupported(mixed $compressionSupported): void * GET * * Add GET request route - * - * @param string $url - * @return Route */ public static function get(string $url): Route { @@ -229,9 +208,6 @@ public static function get(string $url): Route * POST * * Add POST request route - * - * @param string $url - * @return Route */ public static function post(string $url): Route { @@ -242,9 +218,6 @@ public static function post(string $url): Route * PUT * * Add PUT request route - * - * @param string $url - * @return Route */ public static function put(string $url): Route { @@ -255,9 +228,6 @@ public static function put(string $url): Route * PATCH * * Add PATCH request route - * - * @param string $url - * @return Route */ public static function patch(string $url): Route { @@ -268,9 +238,6 @@ public static function patch(string $url): Route * DELETE * * Add DELETE request route - * - * @param string $url - * @return Route */ public static function delete(string $url): Route { @@ -281,8 +248,6 @@ public static function delete(string $url): Route * Wildcard * * Add Wildcard route - * - * @return Route */ public static function wildcard(): Route { @@ -295,8 +260,6 @@ public static function wildcard(): Route * Init * * Set a callback function that will be initialized on application start - * - * @return Hook */ public static function init(): Hook { @@ -312,8 +275,6 @@ public static function init(): Hook * Shutdown * * Set a callback function that will be initialized on application end - * - * @return Hook */ public static function shutdown(): Hook { @@ -329,8 +290,6 @@ public static function shutdown(): Hook * Options * * Set a callback function for all request with options method - * - * @return Hook */ public static function options(): Hook { @@ -346,8 +305,6 @@ public static function options(): Hook * Error * * An error callback for failed or no matched requests - * - * @return Hook */ public static function error(): Hook { @@ -363,10 +320,6 @@ public static function error(): Hook * Get env var * * Method for querying env varialbles. If $key is not found $default value will be returned. - * - * @param string $key - * @param string|null $default - * @return string|null */ public static function getEnv(string $key, ?string $default = null): ?string { @@ -377,8 +330,6 @@ public static function getEnv(string $key, ?string $default = null): ?string * Get Mode * * Get current mode - * - * @return string */ public static function getMode(): string { @@ -389,9 +340,6 @@ public static function getMode(): string * Set Mode * * Set current mode - * - * @param string $value - * @return void */ public static function setMode(string $value): void { @@ -401,8 +349,6 @@ public static function setMode(string $value): void /** * Get allow override * - * - * @return bool */ public static function getAllowOverride(): bool { @@ -412,9 +358,6 @@ public static function getAllowOverride(): bool /** * Set Allow override * - * - * @param bool $value - * @return void */ public static function setAllowOverride(bool $value): void { @@ -483,8 +426,6 @@ protected function setRequestResource(string $name, callable $callback, array $i /** * Is http in production mode? - * - * @return bool */ public static function isProduction(): bool { @@ -493,8 +434,6 @@ public static function isProduction(): bool /** * Is http in development mode? - * - * @return bool */ public static function isDevelopment(): bool { @@ -503,8 +442,6 @@ public static function isDevelopment(): bool /** * Is http in stage mode? - * - * @return bool */ public static function isStage(): bool { @@ -525,8 +462,6 @@ public static function getRoutes(): array /** * Get the current route - * - * @return null|Route */ public function getRoute(): ?Route { @@ -535,8 +470,6 @@ public function getRoute(): ?Route /** * Set the current route - * - * @param Route $route */ public function setRoute(Route $route): self { @@ -549,10 +482,6 @@ public function setRoute(Route $route): self * Add Route * * Add routing route method, path and callback - * - * @param string $method - * @param string $url - * @return Route */ public static function addRoute(string $method, string $url): Route { @@ -566,12 +495,9 @@ public static function addRoute(string $method, string $url): Route /** * Load directory. * - * @param string $directory - * @param string|null $root - * @return void * * @throws \Exception - */ + */ public function loadFiles(string $directory, ?string $root = null): void { $this->files->load($directory, $root); @@ -579,9 +505,6 @@ public function loadFiles(string $directory, ?string $root = null): void /** * Is file loaded. - * - * @param string $uri - * @return bool */ protected function isFileLoaded(string $uri): bool { @@ -591,9 +514,7 @@ protected function isFileLoaded(string $uri): bool /** * Get file contents. * - * @param string $uri * @return string - * * @throws \Exception */ protected function getFileContents(string $uri): mixed @@ -604,9 +525,7 @@ protected function getFileContents(string $uri): mixed /** * Get file MIME type. * - * @param string $uri * @return string - * * @throws \Exception */ protected function getFileMimeType(string $uri): mixed @@ -636,9 +555,7 @@ public function start(): void ); $this->server->onStart(function ($server) { - $this->setResource('server', function () use ($server) { - return $server; - }); + $this->setResource('server', fn() => $server); try { foreach (self::$startHooks as $hook) { @@ -669,9 +586,7 @@ public function start(): void * * Find matching route given current user request * - * @param Request $request * @param bool $fresh If true, will not match any cached route - * @return null|Route */ public function match(Request $request, bool $fresh = true): ?Route { @@ -682,7 +597,7 @@ public function match(Request $request, bool $fresh = true): ?Route $url = \parse_url($request->getURI(), PHP_URL_PATH); $url = \is_string($url) ? ($url === '' ? '/' : $url) : '/'; $method = $request->getMethod(); - $method = (self::REQUEST_METHOD_HEAD == $method) ? self::REQUEST_METHOD_GET : $method; + $method = (self::REQUEST_METHOD_HEAD === $method) ? self::REQUEST_METHOD_GET : $method; $this->route = Router::match($method, $url); @@ -691,9 +606,6 @@ public function match(Request $request, bool $fresh = true): ?Route /** * Execute a given route with middlewares and error handling - * - * @param Route $route - * @param Request $request */ public function execute(Route $route, Request $request, Response $response): static { @@ -778,11 +690,9 @@ public function execute(Route $route, Request $request, Response $response): sta /** * Get Arguments * - * @param Hook $hook * @param array $values * @param array $requestParams * @return array - * * @throws Exception */ protected function getArguments(Hook $hook, array $values, array $requestParams): array @@ -813,7 +723,7 @@ protected function getArguments(Hook $hook, array $values, array $requestParams) $arguments[$param['order']] = $value; } - foreach ($hook->getInjections() as $key => $injection) { + foreach ($hook->getInjections() as $injection) { $arguments[$injection['order']] = $this->getResource($injection['name']); } @@ -857,7 +767,6 @@ public function run(Request $request, Response $response): static * This is the place to initialize any pre routing logic. * This is where you might want to parse the application current URL by any desired logic * - * @param Request $request * @param Response $response; */ private function runInternal(Request $request, Response $response): static @@ -909,12 +818,12 @@ private function runInternal(Request $request, Response $response): static $this->setRequestResource('route', fn() => $route, []); - if (self::REQUEST_METHOD_HEAD == $method) { + if (self::REQUEST_METHOD_HEAD === $method) { $method = self::REQUEST_METHOD_GET; $response->disablePayload(); } - if (self::REQUEST_METHOD_OPTIONS == $method) { + if (self::REQUEST_METHOD_OPTIONS === $method) { try { foreach ($groups as $group) { foreach (self::$options as $option) { // Group options hooks @@ -935,9 +844,7 @@ private function runInternal(Request $request, Response $response): static foreach (self::$errors as $error) { // Global error hooks /** @var Hook $error */ if (\in_array('*', $error->getGroups())) { - $this->setRequestResource('error', function () use ($e) { - return $e; - }, []); + $this->setRequestResource('error', fn() => $e, []); \call_user_func_array($error->getAction(), $this->getArguments($error, [], $request->getParams())); } } @@ -955,10 +862,11 @@ private function runInternal(Request $request, Response $response): static $this->setRequestResource('route', fn() => $route, []); } - if (null !== $route) { return $this->execute($route, $request, $response); - } elseif (self::REQUEST_METHOD_OPTIONS == $method) { + } + + if (self::REQUEST_METHOD_OPTIONS === $method) { try { foreach ($groups as $group) { foreach (self::$options as $option) { // Group options hooks @@ -976,9 +884,7 @@ private function runInternal(Request $request, Response $response): static } catch (\Throwable $e) { foreach (self::$errors as $error) { // Global error hooks if (\in_array('*', $error->getGroups())) { - $this->setRequestResource('error', function () use ($e) { - return $e; - }, []); + $this->setRequestResource('error', fn() => $e, []); \call_user_func_array($error->getAction(), $this->getArguments($error, [], $request->getParams())); } } @@ -1001,10 +907,7 @@ private function runInternal(Request $request, Response $response): static * * Creates an validator instance and validate given value with given rules. * - * @param string $key * @param array $param - * @param mixed $value - * @return void * * @throws Exception */ @@ -1031,8 +934,6 @@ protected function validate(string $key, array $param, mixed $value): void /** * Reset all the static variables - * - * @return void */ public static function reset(): void { diff --git a/src/Http/Request.php b/src/Http/Request.php index b273b5a..b8618bb 100755 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -30,21 +30,21 @@ abstract class Request * * @var array|null */ - protected $payload = null; + protected $payload; /** * Container for parsed query string params * * @var array|null */ - protected $queryString = null; + protected $queryString; /** * Container for parsed headers * * @var array>|null */ - protected $headers = null; + protected $headers; /** * @var array @@ -55,16 +55,12 @@ abstract class Request * Get Param * * Get param by current method name - * - * @param string $key - * @param mixed $default - * @return mixed */ public function getParam(string $key, mixed $default = null): mixed { $params = $this->getParams(); - return (isset($params[$key])) ? $params[$key] : $default; + return $params[$key] ?? $default; } /** @@ -83,10 +79,6 @@ public function getParams(): array * Get Query * * Method for querying HTTP GET request parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param mixed $default - * @return mixed */ public function getQuery(string $key, mixed $default = null): mixed { @@ -99,10 +91,6 @@ public function getQuery(string $key, mixed $default = null): mixed * Get payload * * Method for querying HTTP request payload parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param mixed $default - * @return mixed */ public function getPayload(string $key, mixed $default = null): mixed { @@ -115,8 +103,6 @@ public function getPayload(string $key, mixed $default = null): mixed * Get raw payload * * Method for getting the HTTP request payload as a raw string. - * - * @return string */ abstract public function getRawPayload(): string; @@ -124,10 +110,6 @@ abstract public function getRawPayload(): string; * Get server * * Method for querying server parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param string|null $default - * @return string|null */ abstract public function getServer(string $key, ?string $default = null): ?string; @@ -135,10 +117,6 @@ abstract public function getServer(string $key, ?string $default = null): ?strin * Set server * * Method for setting server parameters. - * - * @param string $key - * @param string $value - * @return static */ abstract public function setServer(string $key, string $value): static; @@ -149,12 +127,11 @@ abstract public function setServer(string $key, string $value): static; * Headers are checked in order; the first one found with a valid IP is used. * * @param array $headers - * @return static */ public function setTrustedIpHeaders(array $headers): static { - $normalized = \array_map('strtolower', $headers); - $trimmed = \array_map('trim', $normalized); + $normalized = \array_map(strtolower(...), $headers); + $trimmed = \array_map(trim(...), $normalized); $this->trustedIpHeaders = \array_filter($trimmed); return $this; @@ -166,8 +143,6 @@ public function setTrustedIpHeaders(array $headers): static * Returns users IP address. * Support HTTP_X_FORWARDED_FOR header usually return * from different proxy servers or PHP default REMOTE_ADDR - * - * @return string */ abstract public function getIP(): string; @@ -177,8 +152,6 @@ abstract public function getIP(): string; * Returns request protocol. * Support HTTP_X_FORWARDED_PROTO header usually return * from different proxy servers or PHP default REQUEST_SCHEME - * - * @return string */ abstract public function getProtocol(): string; @@ -186,8 +159,6 @@ abstract public function getProtocol(): string; * Get Port * * Returns request port. - * - * @return string */ abstract public function getPort(): string; @@ -195,8 +166,6 @@ abstract public function getPort(): string; * Get Hostname * * Returns request hostname. - * - * @return string */ abstract public function getHostname(): string; @@ -204,8 +173,6 @@ abstract public function getHostname(): string; * Get Method * * Return HTTP request method - * - * @return string */ abstract public function getMethod(): string; @@ -213,9 +180,6 @@ abstract public function getMethod(): string; * Set Method * * Set HTTP request method - * - * @param string $method - * @return static */ abstract public function setMethod(string $method): static; @@ -223,8 +187,6 @@ abstract public function setMethod(string $method): static; * Get URI * * Return HTTP request URI - * - * @return string */ public function getURI(): string { @@ -235,9 +197,6 @@ public function getURI(): string * Get Path * * Return HTTP request path - * - * @param string $uri - * @return static */ abstract public function setURI(string $uri): static; @@ -246,7 +205,6 @@ abstract public function setURI(string $uri): static; * * Method for querying upload files data. If $key is not found empty array will be returned. * - * @param string $key * @return array */ abstract public function getFiles(string $key): array; @@ -255,9 +213,6 @@ abstract public function getFiles(string $key): array; * Get Referer * * Return HTTP referer header - * - * @param string $default - * @return string */ abstract public function getReferer(string $default = ''): string; @@ -265,9 +220,6 @@ abstract public function getReferer(string $default = ''): string; * Get Origin * * Return HTTP origin header - * - * @param string $default - * @return string */ abstract public function getOrigin(string $default = ''): string; @@ -275,9 +227,6 @@ abstract public function getOrigin(string $default = ''): string; * Get User Agent * * Return HTTP user agent header - * - * @param string $default - * @return string */ abstract public function getUserAgent(string $default = ''): string; @@ -285,9 +234,6 @@ abstract public function getUserAgent(string $default = ''): string; * Get Accept * * Return HTTP accept header - * - * @param string $default - * @return string */ abstract public function getAccept(string $default = ''): string; @@ -295,10 +241,6 @@ abstract public function getAccept(string $default = ''): string; * Get cookie * * Method for querying HTTP cookie parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param string $default - * @return string */ abstract public function getCookie(string $key, string $default = ''): string; @@ -306,10 +248,6 @@ abstract public function getCookie(string $key, string $default = ''): string; * Get header * * Method for querying HTTP header parameters. If $key is not found $default value will be returned. - * - * @param string $key - * @param string $default - * @return string */ abstract public function getHeader(string $key, string $default = ''): string; @@ -329,10 +267,6 @@ public function getHeaders(): array * Set header * * Method for adding HTTP header parameters. - * - * @param string $key - * @param string $value - * @return static */ abstract public function addHeader(string $key, string $value): static; @@ -340,9 +274,6 @@ abstract public function addHeader(string $key, string $value): static; * Remvoe header * * Method for removing HTTP header parameters. - * - * @param string $key - * @return static */ abstract public function removeHeader(string $key): static; @@ -350,19 +281,13 @@ abstract public function removeHeader(string $key): static; * Get Request Size * * Returns request size in bytes - * - * @return int */ public function getSize(): int { $headers = $this->generateHeaders(); $headerStrings = []; foreach ($headers as $key => $value) { - if (\is_array($value)) { - $headerStrings[] = $key . ': ' . \implode(', ', $value); - } else { - $headerStrings[] = $key . ': ' . $value; - } + $headerStrings[] = \is_array($value) ? $key . ': ' . \implode(', ', $value) : $key . ': ' . $value; } return \mb_strlen(\implode("\n", $headerStrings), '8bit') + \mb_strlen(\file_get_contents('php://input') ?: '', '8bit'); } @@ -371,76 +296,62 @@ public function getSize(): int * Get Content Range Start * * Returns the start of content range - * - * @return int|null */ public function getContentRangeStart(): ?int { $data = $this->parseContentRange(); if (!empty($data)) { return $data['start']; - } else { - return null; } + return null; } /** * Get Content Range End * * Returns the end of content range - * - * @return int|null */ public function getContentRangeEnd(): ?int { $data = $this->parseContentRange(); if (!empty($data)) { return $data['end']; - } else { - return null; } + return null; } /** * Get Content Range Size * * Returns the size of content range - * - * @return int|null */ public function getContentRangeSize(): ?int { $data = $this->parseContentRange(); if (!empty($data)) { return $data['size']; - } else { - return null; } + return null; } /** * Get Content Range Unit * * Returns the unit of content range - * - * @return string|null */ public function getContentRangeUnit(): ?string { $data = $this->parseContentRange(); if (!empty($data)) { return $data['unit']; - } else { - return null; } + return null; } /** * Get Range Start * * Returns the start of range header - * - * @return int|null */ public function getRangeStart(): ?int { @@ -456,8 +367,6 @@ public function getRangeStart(): ?int * Get Range End * * Returns the end of range header - * - * @return int|null */ public function getRangeEnd(): ?int { @@ -473,8 +382,6 @@ public function getRangeEnd(): ?int * Get Range Unit * * Returns the unit of range header - * - * @return string|null */ public function getRangeUnit(): ?string { @@ -490,7 +397,6 @@ public function getRangeUnit(): ?string * Set query string parameters * * @param array $params - * @return static */ public function setQueryString(array $params): static { @@ -503,7 +409,6 @@ public function setQueryString(array $params): static * Set payload parameters * * @param array $params - * @return static */ public function setPayload(array $params): static { @@ -530,7 +435,7 @@ protected function generateHeaders(): array $headers = []; foreach ($_SERVER as $name => $value) { - if (\substr($name, 0, 5) == 'HTTP_') { + if (str_starts_with($name, 'HTTP_')) { $headers[\str_replace(' ', '-', \strtolower(\str_replace('_', ' ', \substr($name, 5))))] = $value; } } @@ -589,7 +494,7 @@ protected function parseContentRange(): ?array $data['size'] = (int) $rangeData[1]; $parts = explode('-', $rangeData[0]); - if (count($parts) != 2) { + if (count($parts) !== 2) { return null; } @@ -631,7 +536,7 @@ protected function parseRange(): ?array $data['unit'] = $ranges[0]; $ranges = explode('-', $ranges[1]); - if (count($ranges) !== 2 || strlen($ranges[0]) === 0) { + if (count($ranges) !== 2 || $ranges[0] === '') { return null; } @@ -641,7 +546,7 @@ protected function parseRange(): ?array $data['start'] = (int) $ranges[0]; - if (strlen($ranges[1]) === 0) { + if ($ranges[1] === '') { $data['end'] = null; } else { if (!ctype_digit($ranges[1])) { diff --git a/src/Http/Response.php b/src/Http/Response.php index 1418da8..cf3dac6 100755 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -261,25 +261,12 @@ abstract class Response public const COOKIE_SAMESITE_LAX = 'Lax'; public const CHUNK_SIZE = 2000000; //2mb - - /** - * @var int - */ protected int $statusCode = self::STATUS_CODE_OK; - /** - * @var string - */ protected string $contentType = ''; - /** - * @var bool - */ protected bool $disablePayload = false; - /** - * @var bool - */ protected bool $sent = false; protected bool $headersSent = false; @@ -294,29 +281,14 @@ abstract class Response */ protected array $cookies = []; - /** - * @var float - */ protected float $startTime = 0; - /** - * @var int - */ protected int $size = 0; - /** - * @var string - */ protected string $acceptEncoding = ''; - /** - * @var int - */ protected int $compressionMinSize = Http::COMPRESSION_MIN_SIZE_DEFAULT; - /** - * @var mixed - */ protected mixed $compressionSupported = []; /** @@ -345,8 +317,6 @@ private function isCompressible(?string $contentType): bool * Set accept encoding * * Set HTTP accept encoding header. - * - * @param string $acceptEncoding */ public function setAcceptEncoding(string $acceptEncoding): static { @@ -359,8 +329,6 @@ public function setAcceptEncoding(string $acceptEncoding): static * Set min compression size * * Set minimum size for compression to be applied in bytes. - * - * @param int $compressionMinSize */ public function setCompressionMinSize(int $compressionMinSize): static { @@ -371,8 +339,6 @@ public function setCompressionMinSize(int $compressionMinSize): static /** * Set supported compression algorithms - * - * @param mixed $compressionSupported */ public function setCompressionSupported(mixed $compressionSupported): static { @@ -385,9 +351,6 @@ public function setCompressionSupported(mixed $compressionSupported): static * Set content type * * Set HTTP content type header. - * - * @param string $type - * @param string $charset */ public function setContentType(string $type, string $charset = ''): static { @@ -400,8 +363,6 @@ public function setContentType(string $type, string $charset = ''): static * Get content type * * Get HTTP content type header. - * - * @return string */ public function getContentType(): string { @@ -410,8 +371,6 @@ public function getContentType(): string /** * Get if response was already sent - * - * @return bool */ public function isSent(): bool { @@ -423,7 +382,6 @@ public function isSent(): bool * * Set HTTP response status code between available options. if status code is unknown an exception will be thrown * - * @param int $code * * @throws Exception */ @@ -442,8 +400,6 @@ public function setStatusCode(int $code = 200): static * Get status code * * Get HTTP response status code - * - * @return int **/ public function getStatusCode(): int { @@ -454,8 +410,6 @@ public function getStatusCode(): int * Get Response Size * * Return output response size in bytes - * - * @return int */ public function getSize(): int { @@ -486,9 +440,6 @@ public function enablePayload(): static * Add header * * Add an HTTP response header - * - * @param string $key - * @param string $value */ public function addHeader(string $key, string $value): static { @@ -509,8 +460,6 @@ public function addHeader(string $key, string $value): static * Remove header * * Remove HTTP response header - * - * @param string $key */ public function removeHeader(string $key): static { @@ -537,15 +486,6 @@ public function getHeaders(): array * Add cookie * * Add an HTTP cookie to response header - * - * @param string $name - * @param string|null $value - * @param int|null $expire - * @param string|null $path - * @param string|null $domain - * @param bool|null $secure - * @param bool|null $httponly - * @param string|null $sameSite */ public function addCookie(string $name, ?string $value = null, ?int $expire = null, ?string $path = null, ?string $domain = null, ?bool $secure = null, ?bool $httponly = null, ?string $sameSite = null): static { @@ -569,14 +509,10 @@ public function addCookie(string $name, ?string $value = null, ?int $expire = nu * Remove cookie * * Remove HTTP response cookie - * - * @param string $name */ public function removeCookie(string $name): static { - $this->cookies = array_filter($this->cookies, function ($cookie) use ($name) { - return $cookie['name'] !== $name; - }); + $this->cookies = array_filter($this->cookies, fn($cookie) => $cookie['name'] !== $name); return $this; } @@ -597,9 +533,6 @@ public function getCookies(): array * Output response * * Generate HTTP response output including the response header (+cookies) and body and prints them. - * - * @param string $body - * @return void */ public function send(string $body = ''): void { @@ -689,7 +622,6 @@ public function send(string $body = ''): void * * Send output * - * @param string $content * @return bool False if write cannot complete, such as request ended by client */ abstract public function write(string $content): bool; @@ -698,9 +630,6 @@ abstract public function write(string $content): bool; * End * * Send optional content and end - * - * @param string|null $content - * @return void */ abstract public function end(?string $content = null): void; @@ -709,10 +638,7 @@ abstract public function end(?string $content = null): void; * * Generate HTTP response output including the response header (+cookies) and body and prints them. * - * @param string $body - * @param bool $end * - * @return void */ public function chunk(string $body = '', bool $end = false): void { @@ -771,9 +697,6 @@ protected function appendHeaders(): static /** * Send Status Code - * - * @param int $statusCode - * @return void */ abstract protected function sendStatus(int $statusCode): void; @@ -782,9 +705,7 @@ abstract protected function sendStatus(int $statusCode): void; * * Output Header * - * @param string $key * @param string|array $value - * @return void */ abstract public function sendHeader(string $key, mixed $value): void; @@ -793,10 +714,7 @@ abstract public function sendHeader(string $key, mixed $value): void; * * Output Cookie * - * @param string $name - * @param string $value * @param array $options - * @return void */ abstract protected function sendCookie(string $name, string $value, array $options): void; @@ -834,15 +752,13 @@ protected function appendCookies(): static * * @param string $url complete absolute URI for redirection as required by the internet standard RFC 2616 (HTTP 1.1) * @param int $statusCode valid HTTP status code - * @return void * * @throws Exception - * * @see http://tools.ietf.org/html/rfc2616 */ public function redirect(string $url, int $statusCode = 301): void { - if (300 == $statusCode) { + if (300 === $statusCode) { \trigger_error('It seems webkit based browsers have problems redirecting link with 300 status codes!', E_USER_NOTICE); } @@ -858,9 +774,6 @@ public function redirect(string $url, int $statusCode = 301): void * This helper is for sending an HTML HTTP response and sets relevant content type header ('text/html'). * * @see http://en.wikipedia.org/wiki/JSON - * - * @param string $data - * @return void */ public function html(string $data): void { @@ -875,9 +788,6 @@ public function html(string $data): void * This helper is for sending plain text HTTP response and sets relevant content type header ('text/plain'). * * @see http://en.wikipedia.org/wiki/JSON - * - * @param string $data - * @return void */ public function text(string $data): void { @@ -895,7 +805,6 @@ public function text(string $data): void * @see http://en.wikipedia.org/wiki/JSON * * @param mixed $data - * @return void */ public function json($data): void { @@ -916,9 +825,7 @@ public function json($data): void * * @see http://en.wikipedia.org/wiki/JSONP * - * @param string $callback * @param array $data - * @return void */ public function jsonp(string $callback, array $data): void { @@ -933,9 +840,7 @@ public function jsonp(string $callback, array $data): void * This helper is for sending iframe HTTP response. * It sets relevant content type header ('text/html') and convert a PHP array ($data) to valid JSON using native json_encode * - * @param string $callback * @param array $data - * @return void */ public function iframe(string $callback, array $data): void { @@ -951,8 +856,6 @@ public function iframe(string $callback, array $data): void * * The server has successfully fulfilled the request * and that there is no additional content to send in the response payload body. - * - * @return void */ public function noContent(): void { diff --git a/src/Http/Route.php b/src/Http/Route.php index 68e6eff..46bfb29 100755 --- a/src/Http/Route.php +++ b/src/Http/Route.php @@ -8,22 +8,16 @@ class Route extends Hook { /** * HTTP Method - * - * @var string */ protected string $method = ''; /** * Whether to use hook - * - * @var bool */ protected bool $hook = true; /** * Path - * - * @var string */ protected string $path = ''; @@ -36,15 +30,11 @@ class Route extends Hook /** * Internal counter. - * - * @var int */ protected static int $counter = 0; /** * Route order ID. - * - * @var int */ protected int $order; @@ -71,8 +61,6 @@ public function getMatchedPath(): string /** * Get Route Order ID - * - * @return int */ public function getOrder(): int { @@ -81,9 +69,6 @@ public function getOrder(): int /** * Add path - * - * @param string $path - * @return self */ public function path(string $path): self { @@ -94,9 +79,6 @@ public function path(string $path): self /** * Add alias - * - * @param string $path - * @return self */ public function alias(string $path): self { @@ -107,9 +89,6 @@ public function alias(string $path): self /** * When set false, hooks for this route will be skipped. - * - * @param bool $hook - * @return self */ public function hook(bool $hook = true): self { @@ -120,8 +99,6 @@ public function hook(bool $hook = true): self /** * Get HTTP Method - * - * @return string */ public function getMethod(): string { @@ -130,8 +107,6 @@ public function getMethod(): string /** * Get path - * - * @return string */ public function getPath(): string { @@ -140,8 +115,6 @@ public function getPath(): string /** * Get hook status - * - * @return bool */ public function getHook(): bool { @@ -150,10 +123,6 @@ public function getHook(): bool /** * Set path param. - * - * @param string $key - * @param int $index - * @return void */ public function setPathParam(string $key, int $index, string $path = ''): void { @@ -163,8 +132,6 @@ public function setPathParam(string $key, int $index, string $path = ''): void /** * Get path params. * - * @param \Utopia\Http\Request $request - * @param string $path * @return array */ public function getPathValues(Request $request, string $path = ''): array diff --git a/src/Http/Router.php b/src/Http/Router.php index 9496e95..45fde18 100644 --- a/src/Http/Router.php +++ b/src/Http/Router.php @@ -45,8 +45,6 @@ public static function getRoutes(): array /** * Get allow override * - * - * @return bool */ public static function getAllowOverride(): bool { @@ -56,9 +54,6 @@ public static function getAllowOverride(): bool /** * Set Allow override * - * - * @param bool $value - * @return void */ public static function setAllowOverride(bool $value): void { @@ -69,8 +64,6 @@ public static function setAllowOverride(bool $value): void /** * Add route to router. * - * @param \Utopia\Http\Route $route - * @return void * @throws \Exception */ public static function addRoute(Route $route): void @@ -95,8 +88,6 @@ public static function addRoute(Route $route): void /** * Add route to router. * - * @param \Utopia\Http\Route $route - * @return void * @throws \Exception */ public static function addRouteAlias(string $path, Route $route): void @@ -116,10 +107,6 @@ public static function addRouteAlias(string $path, Route $route): void /** * Match route against the method and path. - * - * @param string $method - * @param string $path - * @return \Utopia\Http\Route|null */ public static function match(string $method, string $path): ?Route { @@ -199,7 +186,6 @@ protected static function combinations(array $set): iterable /** * Prepare path for matching * - * @param string $path * @return array{0: string, 1: array} */ public static function preparePath(string $path): array @@ -229,8 +215,6 @@ public static function preparePath(string $path): array /** * Reset router - * - * @return void */ public static function reset(): void { diff --git a/src/Http/View.php b/src/Http/View.php index 4075d60..a2d1705 100644 --- a/src/Http/View.php +++ b/src/Http/View.php @@ -15,14 +15,8 @@ class View */ protected ?self $parent = null; - /** - * @var string - */ protected string $path = ''; - /** - * @var bool - */ protected bool $rendered = false; /** @@ -40,7 +34,6 @@ class View * * You can optionally initialize the View object with a template path, although this can also be set later using the $this->setPath($path) method * - * @param string $path * * @throws Exception */ @@ -49,9 +42,7 @@ public function __construct(string $path = '') $this->setPath($path); $this - ->addFilter(self::FILTER_ESCAPE, function (string $value) { - return \htmlentities($value, ENT_QUOTES, 'UTF-8'); - }) + ->addFilter(self::FILTER_ESCAPE, fn(string $value) => \htmlentities($value, ENT_QUOTES, 'UTF-8')) ->addFilter(self::FILTER_NL2P, function (string $value) { $paragraphs = ''; @@ -61,9 +52,7 @@ public function __construct(string $path = '') } } - $paragraphs = \str_replace("\n", '
', $paragraphs); - - return $paragraphs; + return \str_replace("\n", '
', $paragraphs); }); } @@ -72,14 +61,12 @@ public function __construct(string $path = '') * * Assign a parameter by key * - * @param string $key - * @param mixed $value * * @throws Exception */ public function setParam(string $key, mixed $value, bool $escapeHtml = true): static { - if (\strpos($key, '.') !== false) { + if (str_contains($key, '.')) { throw new Exception('$key can\'t contain a dot "." character'); } @@ -94,8 +81,6 @@ public function setParam(string $key, mixed $value, bool $escapeHtml = true): st /** * Set parent View object conatining this object - * - * @param self $view */ public function setParent(self $view): static { @@ -111,7 +96,7 @@ public function setParent(self $view): static */ public function getParent(): ?self { - if (!empty($this->parent)) { + if ($this->parent instanceof \Utopia\Http\View) { return $this->parent; } @@ -123,9 +108,7 @@ public function getParent(): ?self * * Returns an assigned parameter by its key or $default if param key doesn't exists * - * @param string $path * @param mixed $default (optional) - * @return mixed */ public function getParam(string $path, mixed $default = null): mixed { @@ -133,7 +116,7 @@ public function getParam(string $path, mixed $default = null): mixed $temp = $this->params; foreach ($path as $key) { - $temp = (isset($temp[$key])) ? $temp[$key] : null; + $temp = $temp[$key] ?? null; if (null !== $temp) { $value = $temp; @@ -150,7 +133,6 @@ public function getParam(string $path, mixed $default = null): mixed * * Set object template path that will be used to render view output * - * @param string $path * * @throws Exception */ @@ -165,8 +147,6 @@ public function setPath(string $path): static * Set rendered * * By enabling rendered state to true, the object will not render its template and will return an empty string instead - * - * @param bool $state */ public function setRendered(bool $state = true): static { @@ -179,8 +159,6 @@ public function setRendered(bool $state = true): static * Is rendered * * Return whether current View rendering state is set to true or false - * - * @return bool */ public function isRendered(): bool { @@ -189,9 +167,6 @@ public function isRendered(): bool /** * Add Filter - * - * @param string $name - * @param callable $callback */ public function addFilter(string $name, callable $callback): static { @@ -203,9 +178,7 @@ public function addFilter(string $name, callable $callback): static /** * Output and filter value * - * @param mixed $value * @param string|array $filter - * @return mixed * * @throws Exception */ @@ -238,8 +211,6 @@ public function print(mixed $value, string|array $filter = ''): mixed * Render view .phtml template file if template has not been set as rendered yet using $this->setRendered(true). * In case path is not readable throws Exception. * - * @param bool $minify - * @return string * * @throws Exception */ @@ -273,12 +244,8 @@ public function render(bool $minify = true): string \preg_match_all('#\.*\<\/pre\>#Uis', $html, $foundPre); // replacing both with /
$index
- $html = \str_replace($foundTxt[0], \array_map(function ($el) { - return ''; - }, \array_keys($foundTxt[0])), $html); - $html = \str_replace($foundPre[0], \array_map(function ($el) { - return '
' . $el . '
'; - }, \array_keys($foundPre[0])), $html); + $html = \str_replace($foundTxt[0], \array_map(fn($el) => '', \array_keys($foundTxt[0])), $html); + $html = \str_replace($foundPre[0], \array_map(fn($el) => '
' . $el . '
', \array_keys($foundPre[0])), $html); // your stuff $search = [ @@ -296,26 +263,20 @@ public function render(bool $minify = true): string $html = \preg_replace($search, $replace, $html) ?? $html; // Replacing back with content - $html = \str_replace(\array_map(function ($el) { - return ''; - }, \array_keys($foundTxt[0])), $foundTxt[0], $html); - $html = \str_replace(\array_map(function ($el) { - return '
' . $el . '
'; - }, \array_keys($foundPre[0])), $foundPre[0], $html); + $html = \str_replace(\array_map(fn($el) => '', \array_keys($foundTxt[0])), $foundTxt[0], $html); + $html = \str_replace(\array_map(fn($el) => '
' . $el . '
', \array_keys($foundPre[0])), $foundPre[0], $html); } return $html; } /* View Helpers */ - /** * Exec * * Exec child View components * * @param array|self $view - * @return string * * @throws Exception */ diff --git a/tests/HttpTest.php b/tests/HttpTest.php index 17ecaac..1df4ac5 100755 --- a/tests/HttpTest.php +++ b/tests/HttpTest.php @@ -501,8 +501,8 @@ public function testCanRunRequest(): void { // Test head requests - $method = (isset($_SERVER['REQUEST_METHOD'])) ? $_SERVER['REQUEST_METHOD'] : null; - $uri = (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : null; + $method = $_SERVER['REQUEST_METHOD'] ?? null; + $uri = $_SERVER['REQUEST_URI'] ?? null; $_SERVER['REQUEST_METHOD'] = 'HEAD'; $_SERVER['REQUEST_URI'] = '/path'; @@ -637,9 +637,7 @@ public function testCallableStringParametersNotExecuted(): void $route3 = new Route('GET', '/test-callable-closure'); $route3 - ->param('generated', function () { - return 'generated-value'; - }, new Text(200), 'generated param', true) + ->param('generated', fn() => 'generated-value', new Text(200), 'generated param', true) ->action(function ($generated) { echo 'generated: ' . $generated; }); diff --git a/tests/RequestTest.php b/tests/RequestTest.php index a10a4dc..5236fff 100755 --- a/tests/RequestTest.php +++ b/tests/RequestTest.php @@ -319,7 +319,6 @@ public function testCanGetSizeWithArrayHeaders(): void $reflection = new \ReflectionClass($this->request); $headersProperty = $reflection->getProperty('headers'); - $headersProperty->setAccessible(true); $headers = $headersProperty->getValue($this->request) ?? []; $headers['accept'] = ['application/json', 'text/html']; diff --git a/tests/RouterTest.php b/tests/RouterTest.php index bfaa544..4ca0134 100644 --- a/tests/RouterTest.php +++ b/tests/RouterTest.php @@ -1,5 +1,7 @@ */ + #[\Override] public function getParams(): array { $paramsArray = []; @@ -51,7 +51,6 @@ public function getParams(): array * Function to set a response filter * * @param array|null $params - * @return void */ public static function _setParams(?array $params): void { @@ -70,8 +69,6 @@ public static function _getParams(): ?array /** * Check if a filter has been set - * - * @return bool */ public static function _hasParams(): bool { diff --git a/tests/e2e/Client.php b/tests/e2e/Client.php index 3efe23f..511aff7 100644 --- a/tests/e2e/Client.php +++ b/tests/e2e/Client.php @@ -44,8 +44,6 @@ public function __construct(string $baseUrl = 'http://fpm') * * Make an API call * - * @param string $method - * @param string $path * @param array $headers * @param array $params * @return array @@ -59,10 +57,9 @@ public function call(string $method, string $path = '', array $headers = [], arr } usleep(50000); - $ch = curl_init($this->baseUrl . $path . (($method == self::METHOD_GET && !empty($params)) ? '?' . http_build_query($params) : '')); + $ch = curl_init($this->baseUrl . $path . (($method === self::METHOD_GET && !empty($params)) ? '?' . http_build_query($params) : '')); $responseHeaders = []; $responseStatus = -1; - $responseType = ''; $responseBody = ''; $cookies = []; @@ -82,7 +79,7 @@ public function call(string $method, string $path = '', array $headers = [], arr return $len; } - if (strtolower(trim($header[0])) == 'set-cookie') { + if (strtolower(trim($header[0])) === 'set-cookie') { $parsed = $this->parseCookie((string) trim($header[1])); $name = array_key_first($parsed); $cookies[$name] = $parsed[$name]; @@ -118,7 +115,6 @@ public function call(string $method, string $path = '', array $headers = [], arr /** * Parse Cookie String * - * @param string $cookie * @return array */ public function parseCookie(string $cookie): array diff --git a/tests/e2e/ResponseFPMTest.php b/tests/e2e/ResponseFPMTest.php index cd04bcd..ccd2144 100644 --- a/tests/e2e/ResponseFPMTest.php +++ b/tests/e2e/ResponseFPMTest.php @@ -1,5 +1,7 @@ inject('response') ->action(function (Response $response) { foreach (['Hello ', 'World!'] as $key => $word) { - $response->chunk($word, $key == 1); + $response->chunk($word, $key === 1); } }); diff --git a/tests/e2e/server-fpm.php b/tests/e2e/server-fpm.php index bb451a4..610bee1 100644 --- a/tests/e2e/server-fpm.php +++ b/tests/e2e/server-fpm.php @@ -1,5 +1,7 @@