diff --git a/.gitignore b/.gitignore index 57799008..b66dc047 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ /vendor/ /storage/**/*.key /storage/**/*.log -/storage/postman/*.json +/storage/postman/ /tests/build/ /vite/ /app/ diff --git a/composer.json b/composer.json index e6700da2..e97eb32d 100644 --- a/composer.json +++ b/composer.json @@ -52,7 +52,7 @@ "fakerphp/faker": "^1.23", "guzzlehttp/guzzle": "^7.9", "lion/command": "^5.1", - "lion/database": "^11.2", + "lion/database": "^11.3", "lion/dependency-injection": "^4.2", "lion/exceptions": "^2.0", "lion/files": "^8.1", @@ -74,7 +74,7 @@ "squizlabs/php_codesniffer": "^3.11" }, "suggest": { - "ext-gd": "Required to use LionSpreadsheet.", + "ext-gd": "Required to use spreadsheet/files.", "ext-pdo": "Required to use all database features.", "ext-redis": "Required to use the Redis cache.", "fakerphp/faker": "Required to use the factory builder.", diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 00000000..4274dd7c --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,5 @@ +parameters: + level: max + + excludePaths: + - %currentWorkingDirectory%/src/LionBundle/Traits/ diff --git a/phpunit.xml b/phpunit.xml index 65eba8b6..0db14ead 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -24,6 +24,7 @@ > + @@ -44,33 +45,5 @@ tests/ - - - tests/Commands/ - - - - tests/Enums/ - - - - tests/Exceptions/ - - - - tests/Helpers/ - - - - tests/Middleware/ - - - - tests/Traits/ - - - - tests/MailhogTest.php - diff --git a/src/LionBundle/Commands/Lion/Route/PostmanCollectionCommand.php b/src/LionBundle/Commands/Lion/Route/PostmanCollectionCommand.php index ad63b154..d424694d 100644 --- a/src/LionBundle/Commands/Lion/Route/PostmanCollectionCommand.php +++ b/src/LionBundle/Commands/Lion/Route/PostmanCollectionCommand.php @@ -4,13 +4,11 @@ namespace Lion\Bundle\Commands\Lion\Route; -use Carbon\Carbon; use DI\Attribute\Inject; use GuzzleHttp\Exception\GuzzleException; use Lion\Bundle\Helpers\Commands\ClassFactory; use Lion\Bundle\Helpers\Commands\PostmanCollection; use Lion\Bundle\Helpers\Http\Fetch; -use Lion\Bundle\Helpers\Http\Routes; use Lion\Command\Command; use Lion\Files\Store; use Lion\Helpers\Str; @@ -141,7 +139,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->postmanCollection->addRoutes($this->routes); - $path = storage_path('postman/', false); + $this->postmanCollection->generateItems(); + + $path = storage_path('postman/'); $this->store->folder($path); @@ -185,20 +185,41 @@ private function fetchRoutes(): void { $this->postmanCollection->init($_ENV['SERVER_URL']); - $this->jsonName = $this->str->of(Carbon::now()->format('Y_m_d'))->concat('_lion_collection')->lower()->get(); - - $this->routes = json_decode( - fetch( - new Fetch(Route::GET, ($_ENV['SERVER_URL'] . '/route-list'), [ - 'headers' => [ - 'Lion-Auth' => $_ENV['SERVER_HASH'], - ], - ]) - ) - ->getBody() - ->getContents(), - true - ); + $this->jsonName = $this->str + ->of(now()->format('Y_m_d')) + ->concat('_lion_collection') + ->lower() + ->get(); + + $json = fetch( + new Fetch(Route::GET, ($_ENV['SERVER_URL'] . '/route-list'), [ + 'headers' => [ + 'Lion-Auth' => $_ENV['SERVER_HASH'], + ], + ]) + ) + ->getBody() + ->getContents(); + + $decode = json_decode($json, true); + + /** + * @var array{ + * array, + * handler: array{ + * controller: bool|array{ + * name: string, + * function: string + * }, + * callback: bool + * } + * }> + * } $routes + */ + $routes = $decode; + + $this->routes = $routes; array_pop($this->routes); } diff --git a/src/LionBundle/Enums/TaskStatusEnum.php b/src/LionBundle/Enums/TaskStatusEnum.php deleted file mode 100644 index 2e223722..00000000 --- a/src/LionBundle/Enums/TaskStatusEnum.php +++ /dev/null @@ -1,43 +0,0 @@ - - */ - public static function values(): array - { - return array_map(fn (object $value) => $value->value, self::cases()); - } -} diff --git a/src/LionBundle/Helpers/Commands/Migrations/Migrations.php b/src/LionBundle/Helpers/Commands/Migrations/Migrations.php index 1e423fe1..a4c9d8af 100644 --- a/src/LionBundle/Helpers/Commands/Migrations/Migrations.php +++ b/src/LionBundle/Helpers/Commands/Migrations/Migrations.php @@ -12,6 +12,7 @@ use Lion\Bundle\Interface\SeedInterface; use Lion\Command\Command; use Lion\Files\Store; +use stdClass; use Symfony\Component\Console\Output\OutputInterface; /** @@ -50,8 +51,7 @@ public function setStore(Store $store): Migrations /** * Sorts the list of elements by the value defined in the INDEX constant * - * @param array $list [Class - * List] + * @param array $list [Class List] * * @return array * @@ -72,6 +72,7 @@ public function orderList(array $list): array return -1; } + /** @phpstan-ignore-next-line */ return $classA::INDEX <=> $classB::INDEX; }); @@ -99,7 +100,10 @@ public function getMigrations(): array $namespace = $this->store->getNamespaceFromFile($migration, 'Database\\Migrations\\', 'Migrations/'); if (!isset($this->loadedMigrations[$migration])) { - $this->loadedMigrations[$migration] = new $namespace(); + /** @var MigrationUpInterface $migrationInstance */ + $migrationInstance = new $namespace(); + + $this->loadedMigrations[$migration] = $migrationInstance; } $tableMigration = $this->loadedMigrations[$migration]; @@ -138,16 +142,17 @@ public function getMigrations(): array public function executeMigrations(Command $command, OutputInterface $output, array $files): void { foreach ($files as $namespace => $classObject) { - if ($classObject instanceof MigrationUpInterface) { - $response = $classObject->up(); + $response = $classObject->up(); - $output->writeln($command->warningOutput("\t>> MIGRATION: {$namespace}")); + /** @phpstan-ignore-next-line */ + $message = "\t>> MIGRATION: {$response->message}"; - if (isError($response)) { - $output->writeln($command->errorOutput("\t>> MIGRATION: {$response->message}")); - } else { - $output->writeln($command->successOutput("\t>> MIGRATION: {$response->message}")); - } + $output->writeln($command->warningOutput("\t>> MIGRATION: {$namespace}")); + + if (isError($response)) { + $output->writeln($command->errorOutput($message)); + } else { + $output->writeln($command->successOutput($message)); } } } @@ -155,7 +160,7 @@ public function executeMigrations(Command $command, OutputInterface $output, arr /** * Run the migrations * - * @param array $list [List of classes] + * @param array $list [List of classes] * * @return void */ @@ -192,10 +197,12 @@ public function executeMigrationsGroup(array $list): void */ $run = function (array $list): void { foreach ($list as $migration) { + /** @phpstan-ignore-next-line */ $migration->up(); } }; + /** @phpstan-ignore-next-line */ $run($this->orderList($migrations[TableInterface::class])); $run($migrations[ViewInterface::class]); diff --git a/src/LionBundle/Helpers/Commands/PostmanCollection.php b/src/LionBundle/Helpers/Commands/PostmanCollection.php index cd2c3fca..5e9d2a6e 100644 --- a/src/LionBundle/Helpers/Commands/PostmanCollection.php +++ b/src/LionBundle/Helpers/Commands/PostmanCollection.php @@ -7,15 +7,12 @@ use DI\Attribute\Inject; use Lion\Helpers\Arr; use Lion\Helpers\Str; +use Lion\Route\Helpers\Rules; use Lion\Route\Route; /** * Generate structures to create Postman collections * - * @property Arr $arr [Arr class object] - * @property Str $str [Str class object] - * @property array $postman [List of configuration data for postman collection] - * * @package Lion\Bundle\Helpers\Commands */ class PostmanCollection @@ -48,9 +45,76 @@ class PostmanCollection /** * [List of configuration data for postman collection] * - * @var array $postman + * @var array{ + * params?: array{ + * routes?: array, + * host?: array{ + * url: string, + * params: array{ + * host: array + * } + * }, + * items?: array, + * request?: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * }, + * items?: array, + * request: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * } + * }> + * }> + * } + * } $postman */ - private array $postman = []; + private array $postman; #[Inject] public function setArr(Arr $arr): PostmanCollection @@ -78,14 +142,14 @@ public function setStr(Str $str): PostmanCollection public function init(string $host): void { $this->postman['params'] = [ - 'routes' => [], - 'items' => [], 'host' => [ 'url' => $host, 'params' => [ - 'host' => ["{{base_url}}"] - ] - ] + 'host' => [ + "{{base_url}}", + ], + ], + ], ]; } @@ -115,10 +179,21 @@ private function addValuesParam(string $params, string $value, string $key, bool * * @param string $jsonParams [JSON object with parameters] * - * @return array + * @return array{ + * raw: string, + * query: array + * } */ private function createQueryParams(string $jsonParams): array { + /** @var array $query + */ $query = []; $params = ''; @@ -126,18 +201,21 @@ private function createQueryParams(string $jsonParams): array $cont = 0; if (!empty($jsonParams)) { - foreach (json_decode($jsonParams, true) as $key => $data) { + /** @var array $jsonParamsDecode */ + $jsonParamsDecode = json_decode($jsonParams, true); + + foreach ($jsonParamsDecode as $key => $value) { if ($cont === 0) { - $params = $this->addValuesParam($params, $data, $key, true); + $params = $this->addValuesParam($params, $value, $key, true); $cont++; } else { - $params = $this->addValuesParam($params, $data, $key); + $params = $this->addValuesParam($params, $value, $key); } $query[] = [ 'key' => $key, - 'value' => ('' === $data ? null : $data) + 'value' => ('' === $value ? null : $value) ]; } } @@ -151,24 +229,28 @@ private function createQueryParams(string $jsonParams): array /** * Gets the structure of the body with its respective keys and values * - * @param array $rules [List of defined rules] + * @param array $rules [List of defined rules] * - * @return array|string + * @return string */ - private function addParams(array $rules): array|string + private function addParams(array $rules): string { $newParams = []; foreach ($rules as $rule) { + /** @var Rules $objectRuleClass */ $objectRuleClass = new $rule(); - if (!empty($objectRuleClass->field)) { + if (!empty($objectRuleClass->field) && isset($objectRuleClass->value)) { $newParams[$objectRuleClass->field] = $objectRuleClass->value; } } if (count($newParams) > 0) { - return json_encode($newParams); + /** @var non-empty-string $jsonParams */ + $jsonParams = json_encode($newParams); + + return $jsonParams; } return ''; @@ -179,9 +261,34 @@ private function addParams(array $rules): array|string * * @param string $name [Request name] * @param string $route [Route name] - * @param array $params [Parameters defined for routes] + * @param array $params [Parameters defined for routes] * - * @return array + * @return array{ + * name: string, + * response: array, + * request: array{ + * method: string, + * header: array, + * body: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array + * } + * } + * } */ private function addPatch(string $name, string $route, array $params): array { @@ -190,22 +297,28 @@ private function addPatch(string $name, string $route, array $params): array 'response' => [], 'request' => [ 'method' => Route::PATCH, - 'header' => [self::HEADERS], + 'header' => [ + self::HEADERS, + ], 'body' => [ 'mode' => 'raw', 'raw' => $this->addParams($params), 'options' => [ 'raw' => [ - 'language' => 'json' - ] - ] + 'language' => 'json', + ], + ], ], 'url' => [ - ...$this->postman['params']['host']['params'], + 'host' => [ + '{{base_url}}', + ], 'raw' => '{{base_url}}/' . $route, - 'path' => [...explode('/', $route)] - ] - ] + 'path' => [ + ...explode('/', $route), + ], + ], + ], ]; } @@ -214,16 +327,35 @@ private function addPatch(string $name, string $route, array $params): array * * @param string $name [Request name] * @param string $route [Route name] - * @param array $params [Parameters defined for routes] + * @param array $params [Parameters defined for routes] * - * @return array + * @return array{ + * name: string, + * response: array, + * request: array{ + * method: string, + * header: array, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query: array + * } + * } + * } */ private function addGet(string $name, string $route, array $params): array { - $paramsJson = $this->addParams($params); - - $createParams = self::createQueryParams($paramsJson); + $createParams = self::createQueryParams($this->addParams($params)); + /** @var string $newRoute */ $newRoute = $this->str ->of("{{base_url}}/{$route}{$createParams['raw']}") ->replace("//", '/') @@ -234,12 +366,16 @@ private function addGet(string $name, string $route, array $params): array 'response' => [], 'request' => [ 'method' => Route::GET, - 'header' => [self::HEADERS], + 'header' => [ + self::HEADERS, + ], 'url' => [ - ...$this->postman['params']['host']['params'], + 'host' => [ + '{{base_url}}', + ], 'raw' => $newRoute, 'path' => '/' === $route ? [''] : explode('/', $route), - 'query' => $createParams['query'] + 'query' => $createParams['query'], ], ] ]; @@ -250,9 +386,34 @@ private function addGet(string $name, string $route, array $params): array * * @param string $name [Request name] * @param string $route [Route name] - * @param array $params [Parameters defined for routes] + * @param array $params [Parameters defined for routes] * - * @return array + * @return array{ + * name: string, + * response: array, + * request: array{ + * method: string, + * header: array, + * body: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array + * } + * } + * } */ private function addDelete(string $name, string $route, array $params): array { @@ -261,22 +422,28 @@ private function addDelete(string $name, string $route, array $params): array 'response' => [], 'request' => [ 'method' => Route::DELETE, - 'header' => [self::HEADERS], + 'header' => [ + self::HEADERS, + ], 'body' => [ 'mode' => 'raw', 'raw' => $this->addParams($params), 'options' => [ 'raw' => [ - 'language' => 'json' - ] - ] + 'language' => 'json', + ], + ], ], 'url' => [ - ...$this->postman['params']['host']['params'], + 'host' => [ + '{{base_url}}', + ], 'raw' => '{{base_url}}/' . $route, - 'path' => [...explode('/', $route)] - ] - ] + 'path' => [ + ...explode('/', $route), + ] + ], + ], ]; } @@ -285,9 +452,34 @@ private function addDelete(string $name, string $route, array $params): array * * @param string $name [Request name] * @param string $route [Route name] - * @param array $params [Parameters defined for routes] + * @param array $params [Parameters defined for routes] * - * @return array + * @return array{ + * name: string, + * response: array, + * request: array{ + * method: string, + * header: array, + * body: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array + * } + * } + * } */ private function addPost(string $name, string $route, array $params): array { @@ -296,22 +488,28 @@ private function addPost(string $name, string $route, array $params): array 'response' => [], 'request' => [ 'method' => Route::POST, - 'header' => [self::HEADERS], + 'header' => [ + self::HEADERS, + ], 'body' => [ 'mode' => 'raw', 'raw' => $this->addParams($params), 'options' => [ 'raw' => [ - 'language' => 'json' - ] - ] + 'language' => 'json', + ], + ], ], 'url' => [ - ...$this->postman['params']['host']['params'], + 'host' => [ + '{{base_url}}', + ], 'raw' => '{{base_url}}/' . $route, - 'path' => [...explode('/', $route)] - ] - ] + 'path' => [ + ...explode('/', $route), + ], + ], + ], ]; } @@ -320,9 +518,34 @@ private function addPost(string $name, string $route, array $params): array * * @param string $name [Request name] * @param string $route [Route name] - * @param array $params [Parameters defined for routes] + * @param array $params [Parameters defined for routes] * - * @return array + * @return array{ + * name: string, + * response: array, + * request: array{ + * method: string, + * header: array, + * body: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array + * } + * } + * } */ private function addPut(string $name, string $route, array $params): array { @@ -331,22 +554,28 @@ private function addPut(string $name, string $route, array $params): array 'response' => [], 'request' => [ 'method' => Route::PUT, - 'header' => [self::HEADERS], + 'header' => [ + self::HEADERS, + ], 'body' => [ 'mode' => 'raw', 'raw' => $this->addParams($params), 'options' => [ 'raw' => [ - 'language' => 'json' - ] - ] + 'language' => 'json', + ], + ], ], 'url' => [ - ...$this->postman['params']['host']['params'], + 'host' => [ + '{{base_url}}', + ], 'raw' => '{{base_url}}/' . $route, - 'path' => [...explode('/', $route)] - ] - ] + 'path' => [ + ...explode('/', $route), + ], + ], + ], ]; } @@ -356,11 +585,40 @@ private function addPut(string $name, string $route, array $params): array * @param string $name [Request name] * @param string $route [Route name] * @param string $method [Defined HTTP method] - * @param array $params [Parameters defined for routes] + * @param array $params [Parameters defined for routes] * - * @return array + * @return array{ + * name: string, + * response: array, + * request: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * } + * } */ - private function addRequest(string $name, string $route, string $method, array $params): array + protected function addRequest(string $name, string $route, string $method, array $params = []): array { $name = '' === $name ? 'index' : $name; @@ -383,32 +641,30 @@ private function addRequest(string $name, string $route, string $method, array $ * Add the available web routes to create a new data structure to generate * collections * - * @param array $routes [List of defined web routes] - * @param array $rules [List of defined web rules] + * @param array, + * handler: array{ + * controller: bool|array{ + * name: string, + * function: string + * }, + * callback: bool + * } + * }>> $routes [List of defined web routes] * * @return void */ - public function addRoutes(array $routes, array $rules = []): void + public function addRoutes(array $routes): void { foreach ($routes as $routeUrl => $allRoutes) { foreach ($allRoutes as $routeMethod => $routeInfo) { - $params = []; - - $pathRoute = '/' === $routeUrl ? '/' : "/{$routeUrl}"; - - if (isset($rules[$routeMethod][$pathRoute])) { - $params = $rules[$routeMethod][$pathRoute]; - } - $this->postman['params']['routes'][] = [ 'url' => $routeUrl, 'method' => $routeMethod, - 'params' => $params + 'params' => [], ]; } } - - $this->generateItems(); } /** @@ -416,75 +672,257 @@ public function addRoutes(array $routes, array $rules = []): void * * @return void */ - private function generateItems(): void + public function generateItems(): void { - foreach ($this->postman['params']['routes'] as $route) { - $splitAll = null; - - if ('/' === $route['url']) { - $splitAll = [$this->str->of("index-{$route['method']}")->lower()->get()]; - } else { - $splitAll = explode('/', $route['url']); - } - - $reverse = $this->reverseArray($splitAll); + if (isset($this->postman['params'], $this->postman['params']['routes'])) { + foreach ($this->postman['params']['routes'] as $route) { + $splitAll = null; + + if ('/' === $route['url']) { + /** @var array $splitAll */ + $splitAll = [ + $this->str + ->of("index-{$route['method']}") + ->lower() + ->get(), + ]; + } else { + $splitAll = explode('/', $route['url']); + } - $size = count($reverse) - 1; + /** @var array $reverse */ + $reverse = $this->reverseArray($splitAll); - $request = null; + $size = count($reverse) - 1; - $initial = true; + $request = null; - $lastArray = []; + $initial = true; - foreach ($reverse as $keySplit => $split) { - if ($keySplit === 0) { - $request = $this->addRequest( - $split, - $route['url'], - (Route::ANY === $route['method'] ? Route::GET : $route['method']), - $route['params'] - ); + $lastArray = []; - if ($keySplit === $size) { - $this->postman['params']['items'][] = $request; - } - } else { - if ($initial) { - $initial = false; + foreach ($reverse as $keySplit => $split) { + if ($keySplit === 0) { + $request = $this->addRequest( + $split, + $route['url'], + (Route::ANY === $route['method'] ? Route::GET : $route['method']) + ); - $lastArray = ['name' => $split, 'item' => [$request]]; + if ($keySplit === $size) { + $this->postman['params']['items'][] = $request; + } } else { - $lastArray = ['name' => $split, 'item' => [$lastArray]]; - } - - if ($keySplit === $size) { - $this->postman['params']['items'][] = $lastArray; + if ($initial) { + $initial = false; + + $lastArray = [ + 'name' => $split, + 'item' => [ + $request, + ], + ]; + } else { + $lastArray = [ + 'name' => $split, + 'item' => [ + $lastArray, + ], + ]; + } + + if ($keySplit === $size) { + $this->postman['params']['items'][] = $lastArray; + } } } } - - $initial = true; - - $lastArray = []; } } /** * Organizes HTTP request structures for collections * - * @param array $items [Data structure] - * @param &$result [List the data structure organized as a result] + * @param array{ + * name: string, + * response?: array, + * request?: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * }, + * items?: array, + * request: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * } + * }> + * } $items [Data structure] + * + * @param array, + * request?: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * }, + * items?: array, + * request?: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * }, + * item?: array + * }> + * }> &$result [List the data structure organized as a result] + * + * @return array, + * request?: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * }, + * items?: array, + * request?: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * }, + * item?: array + * }> + * }> * - * @return array + * @phpstan-ignore-next-line */ - public function createCollection(array $items, &$result = null): array + public function createCollection(array $items, ?array &$result = null): array { if ($result === null) { $result = []; } foreach ($items as $json) { + if (!isset($json['name'])) { + continue; + } + $name = $json['name']; $lastIndex = count($result) - 1; @@ -495,6 +933,7 @@ public function createCollection(array $items, &$result = null): array if ($lastIndex >= 0 && isset($result[$lastIndex]['item'])) { if (isset($json['item'])) { + /** @phpstan-ignore-next-line */ $this->createCollection($json['item'], $result[$lastIndex]['item']); } @@ -502,46 +941,108 @@ public function createCollection(array $items, &$result = null): array // $result[$lastIndex]['item'][] = $json; // } } else { + /** @phpstan-ignore-next-line */ $result[] = $json; } } + /** @phpstan-ignore-next-line */ return $result; } /** * Returns the routes available for the collection * - * @return array> + * @return array */ public function getRoutes(): array { - return $this->postman['params']['routes']; + return $this->postman['params']['routes'] ?? []; } /** * You get the data structures constructed from HTTP requests * - * @return array + * @return array, + * request?: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * }, + * items?: array, + * request: array{ + * method: string, + * header: array, + * body?: array{ + * mode: string, + * raw: string, + * options: array{ + * raw: array{ + * language: string + * } + * } + * }, + * url: array{ + * host: array, + * raw: string, + * path: array, + * query?: array + * } + * } + * }> + * }> */ public function getItems(): array { - return $this->postman['params']['items']; + return $this->postman['params']['items'] ?? []; } /** * Create an array with the data in reverse order * - * @param array $items [List of defined elements] + * @param array $items [List of defined elements] * - * @return array + * @return array */ private function reverseArray(array $items): array { $newItems = []; foreach ($items as $route) { - $newItems = $this->arr->of($newItems)->prepend($route)->get(); + /** @var array $newItems */ + $newItems = $this->arr + ->of($newItems) + ->prepend($route) + ->get(); } return $newItems; diff --git a/src/LionBundle/Helpers/Commands/ProcessCommand.php b/src/LionBundle/Helpers/Commands/ProcessCommand.php index c73df255..adb00a3d 100644 --- a/src/LionBundle/Helpers/Commands/ProcessCommand.php +++ b/src/LionBundle/Helpers/Commands/ProcessCommand.php @@ -44,7 +44,7 @@ public static function run(string $commandString, bool $showOutput = true): void $process->run(); } else { - $process->run(function ($type, $buffer): void { + $process->run(function ($type, string $buffer): void { echo $buffer; }); } diff --git a/src/LionBundle/Helpers/Commands/Schedule/Schedule.php b/src/LionBundle/Helpers/Commands/Schedule/Schedule.php index acf420bb..2cdf9ce6 100644 --- a/src/LionBundle/Helpers/Commands/Schedule/Schedule.php +++ b/src/LionBundle/Helpers/Commands/Schedule/Schedule.php @@ -7,13 +7,6 @@ /** * Create settings for scheduled tasks * - * @property string $cron [Define crontab configuration] - * @property string $command [Command defined for execution] - * @property array $options [Defines the command options and arguments for - * execution] - * @property string $logName [Defines the name of the log file to record the - * outputs] - * * @package Lion\Bundle\Helpers\Commands\Schedule */ class Schedule @@ -35,7 +28,7 @@ class Schedule /** * [Defines the command options and arguments for execution] * - * @var array $options + * @var array $options */ private array $options; @@ -64,7 +57,7 @@ public function cron(string $cron): Schedule * Define the command * * @param string $command [Command defined for execution] - * @param array $options [Defines the command options and arguments for + * @param array $options [Defines the command options and arguments for * execution] * * @return Schedule @@ -96,7 +89,12 @@ public function log(string $logName): Schedule /** * Returns the configuration of the scheduled task * - * @return array + * @return array{ + * cron: string, + * command: string, + * options: array, + * logName: string + * } */ public function getConfig(): array { diff --git a/src/LionBundle/Helpers/Commands/Schedule/Task.php b/src/LionBundle/Helpers/Commands/Schedule/Task.php index 470db362..a94db119 100644 --- a/src/LionBundle/Helpers/Commands/Schedule/Task.php +++ b/src/LionBundle/Helpers/Commands/Schedule/Task.php @@ -10,10 +10,6 @@ /** * Tasks class to encapsulate tasks in queue * - * @property string|null $namespace [Property for namespace] - * @property string|null $method [Property for method] - * @property array|null $data [Property for data] - * * @package Lion\Bundle\Helpers\Commands\Schedule */ class Task @@ -35,29 +31,31 @@ class Task /** * [Property for data] * - * @var array|null $data + * @var array $data */ - private ?array $data = null; + private array $data; /** * Class Constructor * * @param string|null $namespace [Property for namespace] * @param string|null $method [Property for method] - * @param array|null $data [Property for data] + * @param array $data [Property for data] + * + * @throws InvalidArgumentException */ - public function __construct(?string $namespace = null, ?string $method = null, ?array $data = []) + public function __construct(?string $namespace = null, ?string $method = null, array $data = []) { if (null === $namespace) { - throw new InvalidArgumentException('namespace is null', Http::INTERNAL_SERVER_ERROR); + throw new InvalidArgumentException('Namespace is null', Http::INTERNAL_SERVER_ERROR); } if (null === $method) { - throw new InvalidArgumentException('method is null', Http::INTERNAL_SERVER_ERROR); + throw new InvalidArgumentException('The method is null', Http::INTERNAL_SERVER_ERROR); } - if (null === $data) { - throw new InvalidArgumentException('data is null', Http::INTERNAL_SERVER_ERROR); + if (empty($data)) { + throw new InvalidArgumentException('The data is empty', Http::INTERNAL_SERVER_ERROR); } $this->namespace = $namespace; diff --git a/src/LionBundle/Helpers/Commands/Schedule/TaskQueue.php b/src/LionBundle/Helpers/Commands/Schedule/TaskQueue.php index 0b4cb75b..19e4ce09 100644 --- a/src/LionBundle/Helpers/Commands/Schedule/TaskQueue.php +++ b/src/LionBundle/Helpers/Commands/Schedule/TaskQueue.php @@ -49,6 +49,7 @@ public function push(Task $task): TaskQueue { $this->redis ->getClient() + /** @phpstan-ignore-next-line */ ->lpush(self::LION_TASKS, $task->getTask()); return $this; diff --git a/src/LionBundle/Helpers/Commands/Seeds/Seeds.php b/src/LionBundle/Helpers/Commands/Seeds/Seeds.php index 1ca153a0..5dd5a5a8 100644 --- a/src/LionBundle/Helpers/Commands/Seeds/Seeds.php +++ b/src/LionBundle/Helpers/Commands/Seeds/Seeds.php @@ -42,7 +42,7 @@ public function setMigrations(Migrations $migrations): Seeds */ public function executeSeedsGroup(array $list): void { - /** @var array $migrations */ + /** @var array $seeds */ $seeds = []; foreach ($list as $namespace) { @@ -59,10 +59,15 @@ public function executeSeedsGroup(array $list): void */ $run = function (array $list): void { foreach ($list as $seed) { - $seed->run(); + if ($seed instanceof SeedInterface) { + $seed->run(); + } } }; - $run($this->migrations->orderList($seeds)); + /** @var array $orderSeeds */ + $orderSeeds = $this->migrations->orderList($seeds); + + $run($orderSeeds); } } diff --git a/src/LionBundle/Helpers/Commands/Selection/MenuCommand.php b/src/LionBundle/Helpers/Commands/Selection/MenuCommand.php index 2e81b9ff..89ce8aef 100644 --- a/src/LionBundle/Helpers/Commands/Selection/MenuCommand.php +++ b/src/LionBundle/Helpers/Commands/Selection/MenuCommand.php @@ -132,15 +132,19 @@ protected function selectedProject(InputInterface $input, OutputInterface $outpu { $projects = []; - foreach ($this->store->view('resources/') as $folder) { - $split = $this->str - ->of($folder) - ->split('resources/'); + $resources = $this->store->view('resources/'); - $project = end($split); + if (is_array($resources)) { + foreach ($resources as $folder) { + $split = $this->str + ->of($folder) + ->split('resources/'); - if ($project != '.' && $project != '..') { - $projects[] = $project; + $project = end($split); + + if ($project != '.' && $project != '..') { + $projects[] = $project; + } } } @@ -148,24 +152,28 @@ protected function selectedProject(InputInterface $input, OutputInterface $outpu throw new Exception('there are no projects available', Http::INTERNAL_SERVER_ERROR); } + /** @var string $defaultProject */ + $defaultProject = reset($projects); + if (count($projects) <= 1) { - $output->writeln($this->warningOutput('(default: ' . reset($projects) . ')')); + $output->writeln($this->warningOutput('(default: ' . $defaultProject . ')')); - return reset($projects); + return $defaultProject; } /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); - return $helper->ask( - $input, - $output, - new ChoiceQuestion( - ('Select project ' . $this->warningOutput('(default: ' . reset($projects) . ')')), - $projects, - 0 - ) + $choiseQuestion = new ChoiceQuestion( + ('Select project ' . $this->warningOutput('(default: ' . $defaultProject . ')')), + $projects, + 0 ); + + /** @var string $response */ + $response = $helper->ask($input, $output, $choiseQuestion); + + return $response; } /** @@ -175,7 +183,7 @@ protected function selectedProject(InputInterface $input, OutputInterface $outpu * implemented by all input classes] * @param OutputInterface $output [OutputInterface is the interface * implemented by all Output classes] - * @param array $templates [List of available templates] + * @param array $templates [List of available templates] * @param string $defaultTemplate [Default template] * @param int $defaultIndex [Default index] * @@ -194,12 +202,15 @@ protected function selectedTemplate( $helper = $this->getHelper('question'); $choiceQuestion = new ChoiceQuestion( - "Select the type of template {$this->warningOutput("(default: {$defaultTemplate})")}", + "Select the type of template {$this->warningOutput("(default: '{$defaultTemplate}')")}", $templates, $defaultIndex ); - return $helper->ask($input, $output, $choiceQuestion); + /** @var string $template */ + $template = $helper->ask($input, $output, $choiceQuestion); + + return $template; } /** @@ -209,7 +220,7 @@ protected function selectedTemplate( * implemented by all input classes] * @param OutputInterface $output [OutputInterface is the interface * implemented by all Output classes] - * @param array $types [description] + * @param array $types [description] * * @return string * @@ -220,11 +231,12 @@ protected function selectedTypes(InputInterface $input, OutputInterface $output, /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); - return $helper->ask( - $input, - $output, - new ChoiceQuestion("Select type {$this->warningOutput('(default: js)')}", $types, 0) - ); + $choiceQuestion = new ChoiceQuestion("Select type {$this->warningOutput("(default: 'js')")}", $types, 0); + + /** @var string $type */ + $type = $helper->ask($input, $output, $choiceQuestion); + + return $type; } /** @@ -246,19 +258,25 @@ protected function selectConnection(InputInterface $input, OutputInterface $outp $connections = Connection::getConnections(); - $selectedConnection = null; - $connectionKeys = array_keys($connections); + /** @var string $defaultConnection */ $defaultConnection = reset($connectionKeys); if ($this->arr->of($connections)->length() > 1) { + /** @var array $choiseConnections */ + $choiseConnections = $this->arr + ->of($connections) + ->keys() + ->get(); + $choiseQuestion = new ChoiceQuestion( 'Select a connection ' . $this->warningOutput("(default: {$defaultConnection})"), - $this->arr->of($connections)->keys()->get(), + $choiseConnections, 0 ); + /** @var string $selectedConnection */ $selectedConnection = $helper->ask($input, $output, $choiseQuestion); } else { $output->writeln($this->warningOutput("default connection: ({$defaultConnection})")); @@ -285,11 +303,11 @@ protected function selectConnection(InputInterface $input, OutputInterface $outp */ protected function selectConnectionByEnviroment(InputInterface $input, OutputInterface $output): string { - if (empty($_ENV['SELECTED_CONNECTION'])) { - return $this->selectConnection($input, $output); - } else { + if (!empty($_ENV['SELECTED_CONNECTION']) && is_string($_ENV['SELECTED_CONNECTION'])) { return $_ENV['SELECTED_CONNECTION']; } + + return $this->selectConnection($input, $output); } /** @@ -299,7 +317,7 @@ protected function selectConnectionByEnviroment(InputInterface $input, OutputInt * implemented by all input classes] * @param OutputInterface $output [OutputInterface is the interface * implemented by all Output classes] - * @param array $options [List of available migration types] + * @param array $options [List of available migration types] * * @return string * @@ -310,11 +328,16 @@ protected function selectMigrationType(InputInterface $input, OutputInterface $o /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); - return $helper->ask( - $input, - $output, - new ChoiceQuestion("Select the type of migration {$this->warningOutput('(default: Table)')}", $options, 0) + $choiceQuestion = new ChoiceQuestion( + "Select the type of migration {$this->warningOutput('(default: Table)')}", + $options, + 0 ); + + /** @var string $migrationType */ + $migrationType = $helper->ask($input, $output, $choiceQuestion); + + return $migrationType; } /** @@ -419,15 +442,12 @@ protected function getTableColumns( * @param string $selectedConnection [Database connection] * @param string $entity [Entity name] * - * @return stdClass|array|DatabaseCapsuleInterface + * @return array|DatabaseCapsuleInterface>|stdClass * * @internal */ - protected function getTableForeigns( - string $driver, - string $selectedConnection, - string $entity - ): stdClass|array|DatabaseCapsuleInterface { + protected function getTableForeigns(string $driver, string $selectedConnection, string $entity): array|stdClass + { if (Driver::MYSQL === $driver) { return MySQL::connection($selectedConnection) ->table('INFORMATION_SCHEMA.KEY_COLUMN_USAGE', false) @@ -465,9 +485,9 @@ protected function getTableForeigns( * * @param string $connectionName [Connection name] * - * @return stdClass|array + * @return array|DatabaseCapsuleInterface>|stdClass */ - protected function getTables(string $connectionName): stdClass|array + protected function getTables(string $connectionName): array|stdClass { $connections = Connection::getConnections(); diff --git a/src/LionBundle/Helpers/FileWriter.php b/src/LionBundle/Helpers/FileWriter.php index f711677f..cca265ae 100644 --- a/src/LionBundle/Helpers/FileWriter.php +++ b/src/LionBundle/Helpers/FileWriter.php @@ -10,8 +10,6 @@ /** * Class that allows writing system files * - * @property Str $str [Str class object] - * * @package Lion\Bundle\Helpers */ class FileWriter @@ -32,15 +30,21 @@ public function setStr(Str $str): void /** * Replaces the content of a string with another * - * @param array $row [Row to modify] - * @param string $modifiedLine [Modified row content] + * @param array{ + * search: string, + * content: string + * } $row [Row to modify] * @param string $originalLine [Original row content] * * @return string */ - private function replaceContent(array $row, string $modifiedLine, string $originalLine): string + private function replaceContent(array $row, string $originalLine): string { - $newLine = $this->str->of($originalLine)->replace($row['search'], $row['content'])->get(); + /** @var string $newLine */ + $newLine = $this->str + ->of($originalLine) + ->replace($row['search'], $row['content']) + ->get(); return str_pad($newLine, strlen($originalLine)); } @@ -49,46 +53,76 @@ private function replaceContent(array $row, string $modifiedLine, string $origin * Reads all rows from a file and modifies them as defined * * @param string $path [Defined route] - * @param array $rows [list of rows to modify] + * @param array + * }> $rows [list of rows to modify] * * @return void */ public function readFileRows(string $path, array $rows): void { + /** @var resource $file */ $file = fopen($path, 'r+'); + /** @var list $rowsFile */ $rowsFile = file($path); + /** + * @var array{ + * replace?: bool, + * remove?: bool, + * content?: string, + * search?: string, + * multiple?: array + * } $row + */ foreach ($rows as $key => $row) { if ($key >= 1 && $key <= count($rowsFile)) { fseek($file, 0); - if (isset($row['remove'])) { - $total = $key - 1; + $total = $key - 1; + + $modifiedLine = ''; + if (isset($row['remove'])) { unset($rowsFile[$total]); } else { - $total = $key - 1; - $originalLine = $rowsFile[$total]; - $modifiedLine = ''; - - if ($row['replace'] === false) { + if (isset($row['replace'], $row['content']) && !$row['replace']) { $modifiedLine = str_pad($row['content'], strlen($originalLine)); - } else { + } + + if (isset($row['replace']) && $row['replace']) { if (isset($row['multiple'])) { - foreach ($row['multiple'] as $key => $content) { - $originalLine = $this->replaceContent( - $content, - ($key === 0 ? $originalLine : $modifiedLine), - $originalLine - ); + /** + * @var array{ + * search: string, + * content: string + * } $content + */ + foreach ($row['multiple'] as $content) { + $originalLine = $this->replaceContent($content, $originalLine); } $modifiedLine = $originalLine; } else { - $modifiedLine = $this->replaceContent($row, $modifiedLine, $originalLine); + if (isset($row['search'], $row['content'])) { + $modifiedLine = $this->replaceContent([ + 'search' => $row['search'], + 'content' => $row['content'], + ], $originalLine); + } } } diff --git a/src/LionBundle/Helpers/Http/Routes.php b/src/LionBundle/Helpers/Http/Routes.php index 4965d6e1..9a27931f 100644 --- a/src/LionBundle/Helpers/Http/Routes.php +++ b/src/LionBundle/Helpers/Http/Routes.php @@ -4,11 +4,11 @@ namespace Lion\Bundle\Helpers\Http; +use Lion\Route\Middleware; + /** * Initializes the defined web rules and filters * - * @property array $middleware [List of defined web filters] - * * @package Lion\Bundle\Helpers\Http */ class Routes @@ -16,14 +16,14 @@ class Routes /** * [List of defined web filters] * - * @var array $middleware + * @var array $middleware */ private static array $middleware; /** * Returns the list of defined web filters * - * @return array + * @return array */ public static function getMiddleware(): array { @@ -33,14 +33,12 @@ public static function getMiddleware(): array /** * Change the list of defined web filters * - * @param array $middleware [List of defined web filters] + * @param array $middleware [List of defined web filters] * - * @return Routes + * @return void */ - public static function setMiddleware(array $middleware): Routes + public static function setMiddleware(array $middleware): void { self::$middleware = $middleware; - - return new static(); } } diff --git a/src/LionBundle/Helpers/Redis.php b/src/LionBundle/Helpers/Redis.php index c23081c0..130488be 100644 --- a/src/LionBundle/Helpers/Redis.php +++ b/src/LionBundle/Helpers/Redis.php @@ -40,6 +40,16 @@ class Redis /** * Class Constructor + * + * @param array{ + * scheme?: string, + * host?: string, + * port?: int|string, + * parameters?: array{ + * password?: string, + * database?: int|string + * } + * } $options [Configuration data for connecting to Redis] */ public function __construct(array $options = []) { @@ -77,13 +87,13 @@ private function connect(): void /** * Converts string in JSON format to array * - * @param string|null $data [String in JSON format] + * @param string $data [String in JSON format] * - * @return array + * @return mixed */ - private function toArray(?string $data): array + private function toArray(string $data): mixed { - return null === $data ? [] : json_decode($data, true); + return json_decode($data, true); } /** @@ -132,19 +142,18 @@ public function set(string $key, mixed $value): Redis * * @param string $key [Index name] * - * @return array|null + * @return mixed */ - public function get(string $key): ?array + public function get(string $key): mixed { $this->connect(); $key = trim($key); - if (!$this->client->exists($key)) { - return null; - } + /** @var string $value */ + $value = $this->client->get($key); - return $this->toArray($this->client->get($key)); + return empty($value) ? null : $this->toArray($value); } /** diff --git a/src/LionBundle/Interface/FactoryInterface.php b/src/LionBundle/Interface/FactoryInterface.php index 4bf580d6..24a957d2 100644 --- a/src/LionBundle/Interface/FactoryInterface.php +++ b/src/LionBundle/Interface/FactoryInterface.php @@ -21,7 +21,7 @@ public static function columns(): array; /** * Define the model's default state * - * @return array + * @return array **/ public static function definition(): array; } diff --git a/src/LionBundle/Test/Test.php b/src/LionBundle/Test/Test.php index 3c45278d..72d91a91 100644 --- a/src/LionBundle/Test/Test.php +++ b/src/LionBundle/Test/Test.php @@ -4,6 +4,8 @@ namespace Lion\Bundle\Test; +use DI\DependencyException; +use DI\NotFoundException; use Lion\Bundle\Helpers\Commands\Migrations\Migrations; use Lion\Bundle\Helpers\Commands\Seeds\Seeds; use Lion\Bundle\Interface\CapsuleInterface; @@ -47,9 +49,12 @@ class Test extends Testing /** * Run a group of migrations * - * @param array $migrations [List of classes] + * @param array $migrations [List of classes] * * @return void + * + * @throws DependencyException + * @throws NotFoundException */ protected function executeMigrationsGroup(array $migrations): void { @@ -58,7 +63,10 @@ protected function executeMigrationsGroup(array $migrations): void } if (null === $this->migrations) { - $this->migrations = $this->container->resolve(Migrations::class); + /** @var Migrations $migrationsInstance */ + $migrationsInstance = $this->container->resolve(Migrations::class); + + $this->migrations = $migrationsInstance; } $this->migrations->executeMigrationsGroup($migrations); @@ -67,9 +75,12 @@ protected function executeMigrationsGroup(array $migrations): void /** * Run a group of seeds * - * @param array $seeds [List of classes] + * @param array $seeds [List of classes] * * @return void + * + * @throws DependencyException + * @throws NotFoundException */ protected function executeSeedsGroup(array $seeds): void { @@ -78,7 +89,10 @@ protected function executeSeedsGroup(array $seeds): void } if (null === $this->seeds) { - $this->seeds = $this->container->resolve(Seeds::class); + /** @var Seeds $seedsInstance */ + $seedsInstance = $this->container->resolve(Seeds::class); + + $this->seeds = $seedsInstance; } $this->seeds->executeSeedsGroup($seeds); @@ -98,7 +112,6 @@ public function assertCapsule(CapsuleInterface $capsuleInterface, string $entity { $this->assertInstanceOf(CapsuleInterface::class, $capsuleInterface->capsule()); $this->assertIsArray($capsuleInterface->jsonSerialize()); - $this->assertIsString($capsuleInterface->getTableName()); $this->assertSame($entity, $capsuleInterface->getTableName()); } } diff --git a/tests/Commands/Lion/Route/PostmanCollectionCommandTest.php b/tests/Commands/Lion/Route/PostmanCollectionCommandTest.php index 43a102ed..0d707249 100644 --- a/tests/Commands/Lion/Route/PostmanCollectionCommandTest.php +++ b/tests/Commands/Lion/Route/PostmanCollectionCommandTest.php @@ -4,7 +4,6 @@ namespace Tests\Commands\Lion\Route; -use Carbon\Carbon; use Lion\Bundle\Commands\Lion\New\RulesCommand; use Lion\Bundle\Commands\Lion\Route\PostmanCollectionCommand; use Lion\Command\Command; @@ -53,7 +52,7 @@ public function execute(): void $this->assertSame(Command::SUCCESS, $this->commandTester->execute([])); - $jsonFile = self::URL_PATH . Carbon::now()->format('Y_m_d') . '_lion_collection.json'; + $jsonFile = self::URL_PATH . now()->format('Y_m_d') . '_lion_collection.json'; $this->assertFileExists($jsonFile); diff --git a/tests/Enums/TaskStatusEnumTest.php b/tests/Enums/TaskStatusEnumTest.php deleted file mode 100644 index 9dfa26e3..00000000 --- a/tests/Enums/TaskStatusEnumTest.php +++ /dev/null @@ -1,21 +0,0 @@ -assertSame([ - TaskStatusEnum::PENDING->value, - TaskStatusEnum::IN_PROGRESS->value, - TaskStatusEnum::COMPLETED->value, - TaskStatusEnum::FAILED->value - ], TaskStatusEnum::values()); - } -} diff --git a/tests/Helpers/Commands/PostmanCollectionTest.php b/tests/Helpers/Commands/PostmanCollectionTest.php index 32e95763..03381db1 100644 --- a/tests/Helpers/Commands/PostmanCollectionTest.php +++ b/tests/Helpers/Commands/PostmanCollectionTest.php @@ -4,6 +4,8 @@ namespace Tests\Helpers\Commands; +use DI\DependencyException; +use DI\NotFoundException; use GuzzleHttp\Exception\GuzzleException; use Lion\Bundle\Helpers\Commands\PostmanCollection; use Lion\Bundle\Helpers\Http\Fetch; @@ -23,25 +25,27 @@ class PostmanCollectionTest extends Test private const string HOST = 'http://127.0.0.1:8000'; private const array POSTMAN_CONFIG = [ 'params' => [ - 'routes' => [], - 'items' => [], 'host' => [ 'url' => self::HOST, 'params' => [ - 'host' => ["{{base_url}}"] - ] - ] - ] + 'host' => [ + "{{base_url}}", + ], + ], + ], + ], ]; private PostmanCollection $postmanCollection; /** * @throws ReflectionException + * @throws DependencyException + * @throws NotFoundException */ protected function setUp(): void { - $this->postmanCollection = (new Container())->resolve(PostmanCollection::class); + $this->postmanCollection = new Container()->resolve(PostmanCollection::class); $this->initReflection($this->postmanCollection); } @@ -88,7 +92,9 @@ public function createQueryParams(string $jsonParams, array $return): void #[DataProvider('addParamsProvider')] public function addParams(array $rules, array|string $return): void { - $returnMethod = $this->getPrivateMethod('addParams', [$rules]); + $returnMethod = $this->getPrivateMethod('addParams', [ + 'rules' => $rules, + ]); $this->assertSame($return, $returnMethod); } @@ -217,6 +223,8 @@ public function addRoutes(): void $this->postmanCollection->addRoutes($routes); + $this->postmanCollection->generateItems(); + $addRoutes = json_encode($this->getPrivateProperty('postman'), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $this->assertJsonStringEqualsJsonFile('./tests/Providers/Helpers/Commands/AddRoutesProvider.json', $addRoutes); @@ -250,6 +258,8 @@ public function createCollection(): void $this->postmanCollection->addRoutes($routes); + $this->postmanCollection->generateItems(); + $addRoutes = json_encode($this->getPrivateProperty('postman'), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $this->assertJsonStringEqualsJsonFile('./tests/Providers/Helpers/Commands/AddRoutesProvider.json', $addRoutes); @@ -257,7 +267,7 @@ public function createCollection(): void $collection = $this->postmanCollection->createCollection($this->postmanCollection->getItems()); $jsonProvider = json_decode( - (new Store())->get('./tests/Providers/Helpers/Commands/PostmanProvider.json'), + new Store()->get('./tests/Providers/Helpers/Commands/PostmanProvider.json'), true ); @@ -292,6 +302,8 @@ public function getRoutes(): void $this->postmanCollection->addRoutes($routes); + $this->postmanCollection->generateItems(); + $addRoutes = json_encode($this->getPrivateProperty('postman'), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $this->assertJsonStringEqualsJsonFile('./tests/Providers/Helpers/Commands/AddRoutesProvider.json', $addRoutes); @@ -329,7 +341,9 @@ public function getItems(): void $this->postmanCollection->addRoutes($routes); - $jsonProvider = json_decode((new Store())->get('./tests/Providers/Helpers/Commands/AddRoutesProvider.json'), true); + $this->postmanCollection->generateItems(); + + $jsonProvider = json_decode(new Store()->get('./tests/Providers/Helpers/Commands/AddRoutesProvider.json'), true); $this->assertJsonStringEqualsJsonString( json_encode($jsonProvider['params']['items']), diff --git a/tests/Helpers/Commands/Schedule/TaskTest.php b/tests/Helpers/Commands/Schedule/TaskTest.php index f8caeb7f..01d4131f 100644 --- a/tests/Helpers/Commands/Schedule/TaskTest.php +++ b/tests/Helpers/Commands/Schedule/TaskTest.php @@ -33,7 +33,7 @@ public function construct(): void public function constructInvalidNamespace(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('namespace is null'); + $this->expectExceptionMessage('Namespace is null'); $this->expectExceptionCode(Http::INTERNAL_SERVER_ERROR); new Task(); @@ -53,10 +53,10 @@ public function constructInvalidMethod(): void public function constructInvalidData(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('data is null'); + $this->expectExceptionMessage('The data is empty'); $this->expectExceptionCode(Http::INTERNAL_SERVER_ERROR); - new Task(self::class, 'construct', null); + new Task(self::class, 'construct'); } #[Testing] diff --git a/tests/Helpers/FileWriterTest.php b/tests/Helpers/FileWriterTest.php index 1a624308..00c609fb 100644 --- a/tests/Helpers/FileWriterTest.php +++ b/tests/Helpers/FileWriterTest.php @@ -41,12 +41,14 @@ protected function setUp(): void */ #[Testing] #[DataProvider('replaceContentProvider')] - public function testReplaceContent(array $row, string $modifiedLine, string $originalLine): void + public function testReplaceContent(array $row, string $originalLine, string $return): void { - $returnMethod = $this->getPrivateMethod('replaceContent', [$row, $modifiedLine, $originalLine]); + $returnMethod = $this->getPrivateMethod('replaceContent', [ + 'row' => $row, + 'originalLine' => $originalLine, + ]); - $this->assertEquals(strlen($modifiedLine), strlen($returnMethod)); - $this->assertEquals($modifiedLine, $returnMethod); + $this->assertSame($return, $returnMethod); } #[Testing] diff --git a/tests/Helpers/Http/RoutesTest.php b/tests/Helpers/Http/RoutesTest.php index af031880..6a8aff68 100644 --- a/tests/Helpers/Http/RoutesTest.php +++ b/tests/Helpers/Http/RoutesTest.php @@ -5,29 +5,39 @@ namespace Tests\Helpers\Http; use Lion\Bundle\Helpers\Http\Routes; +use Lion\Bundle\Middleware\RouteMiddleware; +use Lion\Route\Middleware; use Lion\Test\Test; +use PHPUnit\Framework\Attributes\Test as Testing; class RoutesTest extends Test { - const MIDDLEWARE = ['app' => [], 'framework' => []]; + private array $middelware; private Routes $routes; protected function setUp(): void { $this->routes = new Routes(); + + $this->middelware = [ + new Middleware('protect-route-list', RouteMiddleware::class, 'protectRouteList'), + ]; } - public function testGetMiddleware(): void + #[Testing] + public function getMiddleware(): void { - $this->routes->setMiddleware(self::MIDDLEWARE); + $this->routes->setMiddleware($this->middelware); - $this->assertSame(self::MIDDLEWARE, $this->routes->getMiddleware()); + $this->assertSame($this->middelware, $this->routes->getMiddleware()); } - public function testSetMiddleware(): void + #[Testing] + public function setMiddleware(): void { - $this->assertInstanceOf(Routes::class, $this->routes->setMiddleware(self::MIDDLEWARE)); - $this->assertSame(self::MIDDLEWARE, $this->routes->getMiddleware()); + $this->routes->setMiddleware($this->middelware); + + $this->assertSame($this->middelware, $this->routes->getMiddleware()); } } diff --git a/tests/Helpers/RedisTest.php b/tests/Helpers/RedisTest.php index d67e5c0a..c8182099 100644 --- a/tests/Helpers/RedisTest.php +++ b/tests/Helpers/RedisTest.php @@ -78,18 +78,6 @@ public function toArray(array $data): void $this->assertSame($return['name'], $data['name']); } - /** - * @throws ReflectionException - */ - #[Testing] - public function toArrayWithParamNull(): void - { - $return = $this->getPrivateMethod('toArray', [null]); - - $this->assertIsArray($return); - $this->assertempty($return); - } - /** * @throws ReflectionException */ diff --git a/tests/Providers/Helpers/FileWriterProviderTrait.php b/tests/Providers/Helpers/FileWriterProviderTrait.php index 801f7999..eede57ce 100644 --- a/tests/Providers/Helpers/FileWriterProviderTrait.php +++ b/tests/Providers/Helpers/FileWriterProviderTrait.php @@ -14,8 +14,8 @@ public static function replaceContentProvider(): array 'search' => 'Search', 'content' => 'Replacement' ], - 'modifiedLine' => 'Original Replacement Line', 'originalLine' => 'Original Search Line', + 'return' => 'Original Replacement Line', ], ]; } diff --git a/tests/Providers/Helpers/PostmanCollectionProviderTrait.php b/tests/Providers/Helpers/PostmanCollectionProviderTrait.php index 44d653af..3affb5fa 100644 --- a/tests/Providers/Helpers/PostmanCollectionProviderTrait.php +++ b/tests/Providers/Helpers/PostmanCollectionProviderTrait.php @@ -118,7 +118,7 @@ public static function addParamsProvider(): array return [ [ 'rules' => [], - 'return' => "" + 'return' => '', ], [ 'rules' => [ @@ -133,7 +133,7 @@ public static function addParamsProvider(): array public string $field = 'last_name'; public string $value = 'lion'; - } + }, ], 'return' => '{"name":"root","last_name":"lion"}', ], @@ -156,10 +156,10 @@ public static function addParamsProvider(): array public string $field = 'rol'; public string $value = ''; - } + }, ], 'return' => '{"name":"root","rol":""}', - ] + ], ]; }