From aa03986fd9674bec0068dd009277acd94bc687e4 Mon Sep 17 00:00:00 2001 From: noelma Date: Wed, 5 Jan 2022 18:24:49 +0100 Subject: [PATCH] fix: phpstan correction --- phpstan.neon.dist | 13 ++- src/App.php | 11 ++- src/Components/Form/FormGroupBuilder.php | 34 +++---- src/Components/Http/Message.php | 42 ++++----- src/Components/Http/Request.php | 16 ++-- src/Components/Http/Response.php | 4 +- src/Components/Http/ServerRequest.php | 58 ++++++------ src/Components/Http/Stream.php | 49 +++++----- src/Components/Http/UploadedFile.php | 37 +++++--- src/Components/Http/Uri.php | 64 +++++++------ src/Components/Http/Utils.php | 30 ++++++ src/Components/HttpClient/Client.php | 11 ++- src/Components/Paginate/Paginator.php | 16 ++-- src/Components/Router/Router.php | 19 ++-- src/Components/Util/Util.php | 92 ++++++++++++++++--- src/Components/Validator/Filters/ToBool.php | 2 +- src/Components/Validator/Filters/ToFloat.php | 4 +- src/Components/Validator/Filters/ToHtmlsc.php | 2 +- src/Components/Validator/Filters/ToInt.php | 2 +- src/Components/Validator/Filters/ToLtrim.php | 16 ++-- src/Components/Validator/Filters/ToRtrim.php | 12 ++- .../Validator/Filters/ToStripTags.php | 9 +- src/Components/Validator/Filters/ToTrim.php | 14 ++- src/Components/Validator/Rule.php | 20 ++-- src/Components/Validator/Rules/Accepted.php | 8 +- src/Components/Validator/Rules/AlphaNum.php | 8 +- .../Validator/Rules/AlphaNumText.php | 8 +- src/Components/Validator/Rules/ArrayType.php | 2 +- src/Components/Validator/Rules/Base64.php | 8 +- src/Components/Validator/Rules/Between.php | 16 ++-- .../Validator/Rules/BetweenNumeric.php | 5 +- src/Components/Validator/Rules/BoolType.php | 8 +- .../Validator/Rules/ClassExists.php | 8 +- src/Components/Validator/Rules/ColorHex.php | 8 +- src/Components/Validator/Rules/Date.php | 8 +- src/Components/Validator/Rules/DateAfter.php | 6 +- .../Validator/Rules/DateAfterOrEqual.php | 2 +- src/Components/Validator/Rules/DateBefore.php | 6 +- .../Validator/Rules/DateBeforeOrEqual.php | 2 +- src/Components/Validator/Rules/DateFormat.php | 5 +- src/Components/Validator/Rules/Dir.php | 8 +- src/Components/Validator/Rules/Email.php | 8 +- src/Components/Validator/Rules/Equal.php | 2 +- .../Validator/Rules/EqualStrict.php | 2 +- src/Components/Validator/Rules/File.php | 11 ++- .../Validator/Rules/FileExtensions.php | 5 +- src/Components/Validator/Rules/FileMimes.php | 14 ++- .../Validator/Rules/FileMimetypes.php | 6 +- src/Components/Validator/Rules/FloatType.php | 8 +- .../Validator/Rules/FontAwesome.php | 5 +- src/Components/Validator/Rules/Image.php | 8 +- .../Validator/Rules/ImageDimensions.php | 12 ++- src/Components/Validator/Rules/InArray.php | 10 +- src/Components/Validator/Rules/Instance.php | 2 +- src/Components/Validator/Rules/IntType.php | 8 +- src/Components/Validator/Rules/Ip.php | 8 +- src/Components/Validator/Rules/IsFile.php | 8 +- .../Validator/Rules/IterableType.php | 2 +- src/Components/Validator/Rules/Json.php | 8 +- src/Components/Validator/Rules/Max.php | 13 ++- src/Components/Validator/Rules/MaxNumeric.php | 5 +- src/Components/Validator/Rules/Min.php | 13 ++- src/Components/Validator/Rules/MinNumeric.php | 5 +- src/Components/Validator/Rules/NullValue.php | 8 +- .../Validator/Rules/NumericType.php | 8 +- src/Components/Validator/Rules/Regex.php | 5 +- src/Components/Validator/Rules/Required.php | 8 +- .../Validator/Rules/RequiredWith.php | 11 ++- .../Validator/Rules/RequiredWithAll.php | 11 ++- .../Validator/Rules/RequiredWithout.php | 11 ++- .../Validator/Rules/RequiredWithoutAll.php | 11 ++- .../Validator/Rules/RessourceType.php | 8 +- src/Components/Validator/Rules/Size.php | 2 +- src/Components/Validator/Rules/Slug.php | 8 +- src/Components/Validator/Rules/StringType.php | 8 +- src/Components/Validator/Rules/Timezone.php | 8 +- src/Components/Validator/Rules/Token.php | 12 +-- src/Components/Validator/Rules/Url.php | 8 +- src/Components/Validator/Rules/Uuid.php | 8 +- src/Components/Validator/Rules/Version.php | 8 +- src/Components/Validator/Validator.php | 18 +++- src/Config.php | 36 ++++++-- src/Container.php | 8 +- src/Controller.php | 6 +- tests/AppTest.php | 3 +- tests/Components/Form/FormTest.php | 15 ++- tests/Components/Http/MessageTest.php | 2 + tests/Components/Http/RequestTest.php | 1 + tests/Components/Http/ResponseTest.php | 1 + tests/Components/Http/ServerRequestTest.php | 1 + tests/Components/Http/StreamTest.php | 3 + .../Http/UploadedFileRessourceTest.php | 1 + tests/Components/Http/UploadedFileTest.php | 1 + tests/Components/Http/UriTest.php | 7 ++ tests/Components/Paginate/PaginatorTest.php | 8 +- tests/Components/Util/UtilTest.php | 5 +- .../Validator/Rules/FileSizeTest.php | 4 +- .../Components/Validator/Rules/TokenTest.php | 12 --- tests/ContainerTest.php | 4 +- tests/Resources/Container/Service2.php | 2 +- tests/Traits/DateTime.php | 16 ++++ 101 files changed, 705 insertions(+), 448 deletions(-) create mode 100644 src/Components/Http/Utils.php create mode 100644 tests/Traits/DateTime.php diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 53f82fb..f9fdf90 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -3,8 +3,19 @@ includes: - vendor/phpstan/phpstan-phpunit/rules.neon parameters: level: max + paths: - src - tests + + excludePaths: + - tests\Resources\Template\* + + ignoreErrors: + - '#Call to an undefined method Psr\\Http\\Message\\ServerRequestInterface::getBasePath\(\).#' + tmpDir: build/phpStan - checkMissingIterableValueType: false \ No newline at end of file + + checkMissingIterableValueType: false + # Pour les objets \ReflectionClass + checkGenericClassInNonGenericObjectType: false \ No newline at end of file diff --git a/src/App.php b/src/App.php index 21648d2..d4612f7 100644 --- a/src/App.php +++ b/src/App.php @@ -103,6 +103,12 @@ final private function __construct(ServerRequestInterface $request) public static function getInstance(?ServerRequestInterface $request = null): self { if (self::$instance === null) { + if (!$request instanceof ServerRequestInterface) { + throw new \InvalidArgumentException( + 'The request must be an implementation of Psr\Http\Message\ServerRequestInterface.' + ); + } + self::$instance = new static($request); } @@ -377,6 +383,9 @@ public function getDir( bool $addEnv = true ): string { $root = $this->getSetting('root', ''); + if (!is_string($root)) { + throw new \InvalidArgumentException('The root parameter must be a string.'); + } $dir = $this->getSettingEnv($key, $default, $addEnv); return Util::cleanDir("$root/$dir"); @@ -450,7 +459,7 @@ protected function loadRoutesAndServices(): void * * Les données doivent pouvoir être prise en charge par le Stream de la réponse. * - * @param ResponseInterface|bool|float|int|object|ressource|string|null $response + * @param mixed $response * * @return ResponseInterface */ diff --git a/src/Components/Form/FormGroupBuilder.php b/src/Components/Form/FormGroupBuilder.php index 609ae36..4e5be50 100644 --- a/src/Components/Form/FormGroupBuilder.php +++ b/src/Components/Form/FormGroupBuilder.php @@ -836,33 +836,25 @@ protected function addEnd(FormGroupBuilder $form): void * * @see http://php.net/manual/fr/function.array-slice.php * - * @param array $input Tableau associatif. - * @param int|string $offset - * @param int|string $length - * @param array $replacement - * @param bool $after Si le tableau de remplacement doit être intègré après. + * @param array $input Tableau associatif. + * @param string $key + * @param array $replacement + * @param bool $after Si le tableau de remplacement doit être intègré après. * * @return void */ private function arraySpliceAssoc( array &$input, - $offset, - $length, + string $key, array $replacement, - bool $after = false + bool $after ): void { - $keyIndices = array_flip(array_keys($input)); - - if (isset($input[ $offset ]) && is_string($offset)) { - $offset = $keyIndices[ $offset ]; - } - if (isset($input[ $length ]) && is_string($length)) { - $length = $keyIndices[ $length ] - $offset; - } + /** @var int $offset */ + $offset = array_flip(array_keys($input))[$key]; - $input = array_slice($input, 0, $offset + ($after - ? 1 - : 0), true) + $replacement + array_slice($input, $offset + $length, null, true); + $input = array_slice($input, 0, $offset + ($after ? 1 : 0), true) + + $replacement + + array_slice($input, $offset, null, true); } /** @@ -882,9 +874,7 @@ private function addItem( if (isset($this->form[ $key ])) { $subform = new FormGroupBuilder; $callback($subform); - $this->arraySpliceAssoc($this->form, $key, ($after - ? $key - : 0), $subform->getForm(), $after); + $this->arraySpliceAssoc($this->form, $key, $subform->getForm(), $after); return true; } diff --git a/src/Components/Http/Message.php b/src/Components/Http/Message.php index d489ecf..1ed93b0 100644 --- a/src/Components/Http/Message.php +++ b/src/Components/Http/Message.php @@ -42,7 +42,7 @@ class Message implements MessageInterface /** * Les entêtes. * - * @var array + * @var string[][] */ protected $headers = []; @@ -65,7 +65,7 @@ class Message implements MessageInterface * * @return string */ - public function getProtocolVersion() + public function getProtocolVersion(): string { return $this->protocolVersion; } @@ -75,9 +75,9 @@ public function getProtocolVersion() * * @param string $version Version du protocole HTTP. * - * @return $this + * @return static */ - public function withProtocolVersion($version) + public function withProtocolVersion($version): MessageInterface { $clone = clone $this; $clone->protocolVersion = $this->filterProtocolVersion($version); @@ -88,9 +88,9 @@ public function withProtocolVersion($version) /** * Renvoie le tableau d'en-tête. * - * @return array + * @return string[][] */ - public function getHeaders() + public function getHeaders(): array { return $this->headers; } @@ -102,7 +102,7 @@ public function getHeaders() * * @return bool Renvoie true si l'en-tête est trouvé sinon faux. */ - public function hasHeader($name) + public function hasHeader($name): bool { return isset($this->name[ strtolower($name) ]); } @@ -115,7 +115,7 @@ public function hasHeader($name) * @return string[] Si l'en-tête est trouvé alors il est renvoyé * toutes ses valeurs, sinon un tableau vide. */ - public function getHeader($name) + public function getHeader($name): array { return $this->hasHeader($name) ? $this->headers[ $this->name[ strtolower($name) ] ] @@ -130,7 +130,7 @@ public function getHeader($name) * @return string Si l'en-tête est trouvé alors il est renvoyé * toutes les valeurs de l'en-tête concaténés par une virgule, sinon une chaine vide. */ - public function getHeaderLine($name) + public function getHeaderLine($name): string { return $this->hasHeader($name) ? implode(',', $this->getHeader($name)) @@ -143,9 +143,9 @@ public function getHeaderLine($name) * @param string $name Nom du champ d'en-tête insensible à la casse. * @param string|string[] $value Valeur(s) de l'en-tête. * - * @return $this + * @return static */ - public function withHeader($name, $value) + public function withHeader($name, $value): MessageInterface { $clone = clone $this; $values = $clone->validateAndTrimHeader($name, $value); @@ -161,9 +161,9 @@ public function withHeader($name, $value) * @param string $name Nom du champ d'en-tête insensible à la casse. * @param string|string[] $value Valeur(s) de l'en-tête. * - * @return $this + * @return static */ - public function withAddedHeader($name, $value) + public function withAddedHeader($name, $value): MessageInterface { $clone = clone $this; $values = $this->validateAndTrimHeader($name, $value); @@ -184,9 +184,9 @@ public function withAddedHeader($name, $value) * * @param string $name Nom de champ d'en-tête insensible à la casse à supprimer. * - * @return $this + * @return static */ - public function withoutHeader($name) + public function withoutHeader($name): MessageInterface { $clone = clone $this; if ($clone->hasHeader($name)) { @@ -201,7 +201,7 @@ public function withoutHeader($name) * * @return StreamInterface Renvoie le corps en tant que flux. */ - public function getBody() + public function getBody(): StreamInterface { return $this->body; } @@ -211,9 +211,9 @@ public function getBody() * * @param StreamInterface $body Le corp. * - * @return $this + * @return static */ - public function withBody(StreamInterface $body) + public function withBody(StreamInterface $body): MessageInterface { $clone = clone $this; $clone->body = $body; @@ -224,7 +224,7 @@ public function withBody(StreamInterface $body) /** * Filtre la version du protocole. * - * @param string $version + * @param mixed $version * * @throws \InvalidArgumentException Le protocole spécifié n'est pas valide. * @@ -274,8 +274,8 @@ protected function withHeaders(array $headers): void * * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 * - * @param string $header - * @param array|string $values + * @param mixed $header + * @param mixed $values * * @throws \InvalidArgumentException; * diff --git a/src/Components/Http/Request.php b/src/Components/Http/Request.php index 5ce7cdb..e954f0d 100644 --- a/src/Components/Http/Request.php +++ b/src/Components/Http/Request.php @@ -40,7 +40,7 @@ class Request extends Message implements RequestInterface /** * L'URI de la requête. * - * @var \Psr\Http\Message\UriInterface + * @var UriInterface */ protected $uri; @@ -97,7 +97,7 @@ public function __construct( * * @return string Renvoie la méthode de requête. */ - public function getMethod() + public function getMethod(): string { return $this->method; } @@ -109,7 +109,7 @@ public function getMethod() * * @return string Cible ce la requête. */ - public function getRequestTarget() + public function getRequestTarget(): string { if ($this->requestTarget !== null) { return $this->requestTarget; @@ -134,7 +134,7 @@ public function getRequestTarget() * @return UriInterface Renvoie une instance d'UriInterface * représentant l'URI de la requête. */ - public function getUri() + public function getUri(): UriInterface { return $this->uri; } @@ -147,7 +147,7 @@ public function getUri() * @throws \InvalidArgumentException pour les méthodes HTTP invalides. * @return static */ - public function withMethod($method) + public function withMethod($method): RequestInterface { $clone = clone $this; $clone->method = $this->filterMethod($method); @@ -165,7 +165,7 @@ public function withMethod($method) * * @return static */ - public function withRequestTarget($requestTarget) + public function withRequestTarget($requestTarget): RequestInterface { if (!is_string($requestTarget)) { throw new \InvalidArgumentException('The target of the request must be a string.'); @@ -186,7 +186,7 @@ public function withRequestTarget($requestTarget) * * @return static */ - public function withUri(UriInterface $uri, $preserveHost = false) + public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface { $clone = clone $this; $clone->uri = $uri; @@ -204,7 +204,7 @@ public function withUri(UriInterface $uri, $preserveHost = false) /** * Filtre la méthde HTTP de la requête. * - * @param string $method Méthode HTTP ('GET'|'POST'|...). + * @param mixed $method Méthode HTTP ('GET'|'POST'|...). * * @throws \InvalidArgumentException La méthode doit être une chaine de caractère. * @throws \InvalidArgumentException La méthode n'est pas prise en charge par la requête. diff --git a/src/Components/Http/Response.php b/src/Components/Http/Response.php index ee7979b..dd61cee 100644 --- a/src/Components/Http/Response.php +++ b/src/Components/Http/Response.php @@ -175,7 +175,7 @@ public function getStatusCode(): int * * @return static */ - public function withStatus($code, $reasonPhrase = '') + public function withStatus($code, $reasonPhrase = ''): ResponseInterface { $clone = clone $this; $clone->code = $this->filtreCode($code); @@ -202,7 +202,7 @@ public function getReasonPhrase(): string /** * Filtre le code d'état. * - * @param int $code Code d'état. + * @param mixed $code Code d'état. * * @throws \InvalidArgumentException Le code de statut n'est pas valide. * diff --git a/src/Components/Http/ServerRequest.php b/src/Components/Http/ServerRequest.php index 93abae4..bc2fdbd 100644 --- a/src/Components/Http/ServerRequest.php +++ b/src/Components/Http/ServerRequest.php @@ -70,14 +70,14 @@ class ServerRequest extends Request implements ServerRequestInterface /** * Construit une requête coté serveur. * - * @param string $method Méthode HTTP ('GET'|'POST'|...). - * @param UriInterface $uri L'URI de la requête. - * @param array $headers Les en-têtes du message. - * @param StreamInterface $body Corp de la requête. - * @param string $version La version du protocole HTTP. - * @param array $serverParams Paramètres de la requête. - * @param array $cookies Les cookies. - * @param array $uploadFiles Fichiers transmis au serveur. + * @param string $method Méthode HTTP ('GET'|'POST'|...). + * @param UriInterface $uri L'URI de la requête. + * @param array $headers Les en-têtes du message. + * @param StreamInterface|null $body Corp de la requête. + * @param string $version La version du protocole HTTP. + * @param array $serverParams Paramètres de la requête. + * @param array $cookies Les cookies. + * @param array $uploadFiles Fichiers transmis au serveur. */ public function __construct( string $method, @@ -154,7 +154,7 @@ public static function create(): ServerRequest * * @return string */ - public function getBasePath($scriptName = '') + public function getBasePath(string $scriptName = ''): string { $filename = $this->getScriptName($scriptName); $baseUrl = $this->uri->getScheme() . '://' . $this->uri->getHost(); @@ -172,7 +172,7 @@ public function getBasePath($scriptName = '') * * @return bool */ - public function isAjax() + public function isAjax(): bool { return !empty($this->serverParams[ 'HTTP_X_REQUESTED_WITH' ]) && strtolower($this->serverParams[ 'HTTP_X_REQUESTED_WITH' ]) === 'xmlhttprequest'; } @@ -183,7 +183,7 @@ public function isAjax() * * @return bool */ - public function isMaxSize() + public function isMaxSize(): bool { return empty($this->parseBody) && empty($this->uploadFiles) && isset($this->serverParams[ 'CONTENT_LENGTH' ]) && $this->serverParams[ 'CONTENT_LENGTH' ] > 0; } @@ -197,7 +197,7 @@ public function isMaxSize() * * @return array */ - public function getServerParams() + public function getServerParams(): array { return $this->serverParams; } @@ -212,7 +212,7 @@ public function getServerParams() * * @return array */ - public function getCookieParams() + public function getCookieParams(): array { return $this->cookieParams; } @@ -228,7 +228,7 @@ public function getCookieParams() * * @return static */ - public function withCookieParams(array $cookies) + public function withCookieParams(array $cookies): ServerRequestInterface { $clone = clone $this; $clone->cookieParams = $cookies; @@ -246,7 +246,7 @@ public function withCookieParams(array $cookies) * * @return array */ - public function getQueryParams() + public function getQueryParams(): array { return $this->queryParams; } @@ -259,7 +259,7 @@ public function getQueryParams() * * @return static */ - public function withQueryParams(array $query) + public function withQueryParams(array $query): ServerRequestInterface { $clone = clone $this; $clone->queryParams = $query; @@ -276,7 +276,7 @@ public function withQueryParams(array $query) * @return array Arbre de tableau des instances de UploadedFileInterface; un vide * Le tableau DOIT être retourné si aucune donnée n'est présente. */ - public function getUploadedFiles() + public function getUploadedFiles(): array { return $this->uploadFiles; } @@ -289,7 +289,7 @@ public function getUploadedFiles() * @throws \InvalidArgumentException Les contenus doivent être tous des instance d'UploadedFileInterface. * @return static */ - public function withUploadedFiles(array $uploadedFiles) + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface { $clone = clone $this; $clone->uploadFiles = self::parseFilesToUploadFiles($uploadedFiles); @@ -321,7 +321,7 @@ public function getParsedBody() * à condition de. * @return static */ - public function withParsedBody($data) + public function withParsedBody($data): ServerRequestInterface { $this->filtreBody($data); $clone = clone $this; @@ -341,7 +341,7 @@ public function withParsedBody($data) * * @return array Attributs dérivés de la requête. */ - public function getAttributes() + public function getAttributes(): array { return $this->attributes; } @@ -362,9 +362,7 @@ public function getAttributes() */ public function getAttribute($name, $default = null) { - return isset($this->attributes[ $name ]) - ? $this->attributes[ $name ] - : $default; + return $this->attributes[ $name ] ?? $default; } /** @@ -384,7 +382,7 @@ public function getAttribute($name, $default = null) * * @return static */ - public function withAttribute($name, $value) + public function withAttribute($name, $value): ServerRequestInterface { $clone = clone $this; $clone->attributes[ $name ] = $value; @@ -404,7 +402,7 @@ public function withAttribute($name, $value) * * @return static */ - public function withoutAttribute($name) + public function withoutAttribute($name): ServerRequestInterface { $clone = clone $this; if (isset($clone->attributes[ $name ])) { @@ -516,17 +514,17 @@ private static function normaliseMultiFile(array $files): array * Parcours récursif à partir d'une clé standard (tmp_name, size, name...) * pour remplir par référence la variable output et regrouper les éléments par fichier. * - * @param array|mixed $output Tableau qui sera rempli par référence. - * @param array $array Informations contenus dans l'une des clés standards. - * @param string $name Clés standards de la variable superglobale $_FILES. + * @param array|null $output Tableau qui sera rempli par référence. + * @param array $array Informations contenus dans l'une des clés standards. + * @param string $name Clés standards de la variable superglobale $_FILES. * * @return void */ - private static function normaliseFile(&$output, array $array, string $name): void + private static function normaliseFile(?array &$output, array $array, string $name): void { /* Troisième parcour. */ foreach ($array as $key => $value) { - if (is_array($value)) { + if (is_array($value) && $output !== null) { self::normaliseFile($output[ $key ], $value, $name); } if (!is_array($value)) { diff --git a/src/Components/Http/Stream.php b/src/Components/Http/Stream.php index 57387bc..ada681e 100644 --- a/src/Components/Http/Stream.php +++ b/src/Components/Http/Stream.php @@ -67,7 +67,7 @@ class Stream implements StreamInterface * * @see http://php.net/manual/fr/wrappers.php.php * - * @param null|object|resource|scalar $mixed + * @param mixed $mixed * * @throws \InvalidArgumentException Le type de données n'est pas pris en charge par flux de données. */ @@ -93,6 +93,7 @@ public function __toString(): string $this->seek(0); + /** @phpstan-ignore-next-line */ return (string) stream_get_contents($this->stream); } @@ -105,19 +106,14 @@ public function __toString(): string * @throws \InvalidArgumentException Le mode de lecture n'est pas valide. * @throws \RuntimeException Le fichier ne peut pas être ouvert. * - * @return \Soosyze\Components\Http\Stream + * @return Stream */ - public static function createStreamFromFile($filename, $mode = 'r') + public static function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface { if (!in_array($mode, self::$modes[ 'read' ])) { throw new \InvalidArgumentException('The mode is invalid.'); } - - try { - $handle = fopen($filename, $mode); - } catch (\Exception $ex) { - throw new \RuntimeException('The file cannot be opened.', $ex->getCode(), $ex); - } + $handle = Utils::tryFopen($filename, $mode); return new Stream($handle); } @@ -125,7 +121,7 @@ public static function createStreamFromFile($filename, $mode = 'r') /** * Ferme le flux de données et toutes les autres ressources. */ - public function close() + public function close(): void { if ($this->stream !== null) { fclose($this->stream); @@ -154,7 +150,7 @@ public function detach() * * @return int|null Renvoie la taille en octets si elle est connue, ou null si elle est inconne. */ - public function getSize() + public function getSize(): ?int { if ($this->stream === null) { return null; @@ -163,7 +159,7 @@ public function getSize() return $stats === false ? null - : $stats[ 'size' ] ?? null; + : $stats[ 'size' ]; } /** @@ -173,7 +169,7 @@ public function getSize() * * @return int Position du pointeur de fichier */ - public function tell() + public function tell(): int { if ($this->stream === null) { throw new \RuntimeException('Stream is detached.'); @@ -190,7 +186,7 @@ public function tell() * * @return bool */ - public function eof() + public function eof(): bool { if ($this->stream === null) { throw new \RuntimeException('Stream is detached.'); @@ -204,7 +200,7 @@ public function eof() * * @return bool */ - public function isSeekable() + public function isSeekable(): bool { $seekable = $this->getMetadata('seekable'); @@ -224,7 +220,7 @@ public function isSeekable() * * @return void */ - public function seek($offset, $whence = SEEK_SET) + public function seek($offset, $whence = SEEK_SET): void { if ($this->stream === null) { throw new \RuntimeException('Stream is detached.'); @@ -242,7 +238,7 @@ public function seek($offset, $whence = SEEK_SET) * * @return void */ - public function rewind() + public function rewind(): void { if ($this->stream === null) { throw new \RuntimeException('Stream is detached.'); @@ -258,7 +254,7 @@ public function rewind() * * @return bool */ - public function isWritable() + public function isWritable(): bool { return in_array($this->getMetadata('mode'), self::$modes[ 'write' ]); } @@ -272,7 +268,7 @@ public function isWritable() * * @return int Renvoie le nombre d'octets écrits dans le flux. */ - public function write($string) + public function write($string): int { if ($this->stream === null) { throw new \RuntimeException('Stream is detached.'); @@ -290,7 +286,7 @@ public function write($string) * * @return bool */ - public function isReadable() + public function isReadable(): bool { return in_array($this->getMetadata('mode'), self::$modes[ 'read' ]); } @@ -306,7 +302,7 @@ public function isReadable() * * @return string Renvoie les données lues dans le flux ou une chaîne vide si aucun octet n'est disponible. */ - public function read($length) + public function read($length): string { if ($this->stream === null) { throw new \RuntimeException('Stream is detached.'); @@ -332,7 +328,7 @@ public function read($length) * * @return string */ - public function getContents() + public function getContents(): string { if ($this->stream === null) { throw new \RuntimeException('Stream is detached.'); @@ -392,19 +388,16 @@ private function createStream($mixed) /** * Charge un flux à partir d'une valeur scalaire. * - * @param mixed $scalar Valeur scalaire. + * @param null|scalar $scalar Valeur scalaire. * * @return resource */ private function createStreamFromScalar($scalar) { - $handle = fopen('php://temp', 'r+'); + $handle = Utils::tryFopen('php://temp', 'r+'); - if ($handle === false) { - throw new \Exception(); - } if ($scalar !== '') { - fwrite($handle, $scalar); + fwrite($handle, (string) $scalar); fseek($handle, 0); } diff --git a/src/Components/Http/UploadedFile.php b/src/Components/Http/UploadedFile.php index 8f84b53..a92c8ca 100644 --- a/src/Components/Http/UploadedFile.php +++ b/src/Components/Http/UploadedFile.php @@ -78,7 +78,7 @@ class UploadedFile implements UploadedFileInterface /** * Représentation du fichier en flux de données. * - * @var StreamInterface + * @var StreamInterface|null */ protected $stream; @@ -122,7 +122,7 @@ public function __construct( * @throws \InvalidArgumentException La clé tmp_name est requise. * @return UploadedFileInterface */ - public static function create(array $file) + public static function create(array $file): UploadedFileInterface { if (!isset($file[ 'tmp_name' ])) { throw new \InvalidArgumentException('The tmp_name key is required.'); @@ -155,7 +155,7 @@ public static function create(array $file) * créé. * @return StreamInterface Stream représentation du fichier téléchargé. */ - public function getStream() + public function getStream(): StreamInterface { if ($this->isError()) { throw new \RuntimeException('A download error prevents recovery of the stream.'); @@ -166,7 +166,11 @@ public function getStream() } if (empty($this->stream)) { - $this->stream = new Stream(fopen($this->file, 'r')); + $this->stream = new Stream( + $this->file === null + ? null + : Utils::tryFopen($this->file, 'r') + ); } return $this->stream; @@ -188,7 +192,7 @@ public function getStream() * @throws \InvalidArgumentException Une erreur est survenue. * @return void */ - public function moveTo($targetPath) + public function moveTo($targetPath): void { if ($this->moved) { throw new \RuntimeException('The file has already been moved.'); @@ -204,9 +208,9 @@ public function moveTo($targetPath) ? $this->moveToSapi($targetPath) : $this->moveToNoSapi($targetPath); } else { - $handle = fopen($targetPath, 'w'); + $handle = Utils::tryFopen($targetPath, 'w'); - fwrite($handle, $this->stream->getContents()); + fwrite($handle, $this->getStream()->getContents()); fclose($handle); $this->moved = true; @@ -218,7 +222,7 @@ public function moveTo($targetPath) * * @return int|null Taille du fichier en octets ou null si inconnu. */ - public function getSize() + public function getSize(): ?int { return $this->size; } @@ -232,7 +236,7 @@ public function getSize() * * @return int Une des constantes UPLOAD_ERR_XXX de PHP. */ - public function getError() + public function getError(): int { return $this->error; } @@ -247,7 +251,7 @@ public function getError() * @return string|null Nom de fichier envoyé par le client ou null si aucun. * a été fourni. */ - public function getClientFilename() + public function getClientFilename(): ?string { return $this->name; } @@ -262,7 +266,7 @@ public function getClientFilename() * @return string|null Le type de média envoyé par le client ou null si aucun * a été fourni. */ - public function getClientMediaType() + public function getClientMediaType(): ?string { return $this->type; } @@ -292,7 +296,7 @@ protected function filterFile($file): void /** * Déclenche une exception si le nom du fichier n'est pas valide. * - * @param string|null $name Nom du fichier + * @param mixed $name Nom du fichier * * @throws \InvalidArgumentException Le nom du fichier doit être une chaine de caractère ou null. * @@ -310,7 +314,7 @@ protected function filterName($name): ?string /** * Déclenche une exception si la taille du fichier n'est pas valide. * - * @param int|null $size Taille du fichier. + * @param mixed $size Taille du fichier. * * @throws \InvalidArgumentException La taille du fichier doit-être un nombre entier ou null * @@ -328,7 +332,7 @@ protected function filterSize($size): ?int /** * Déclenche une exception si le type du fichier n'est pas valide. * - * @param string|null $type Type du fichier + * @param mixed $type Type du fichier * * @throws \InvalidArgumentException Le type du fichier doit être une chaine de caractère ou null. * @@ -346,7 +350,7 @@ protected function filterType($type): ?string /** * Déclence une exception si le type d'error n'est pas valide. * - * @param int $error Type d'erreur. + * @param mixed $error Type d'erreur. * * @throws \InvalidArgumentException Le type d'erreur n'est pas valide. * @@ -370,6 +374,7 @@ protected function filterError($error): int */ private function moveToSapi(string $targetPath): bool { + /** @phpstan-ignore-next-line */ return rename($this->file, $targetPath); } @@ -385,9 +390,11 @@ private function moveToSapi(string $targetPath): bool */ private function moveToNoSapi(string $targetPath): bool { + /** @phpstan-ignore-next-line */ if (!is_uploaded_file($this->file)) { throw new \RuntimeException('The file was not downloaded by HTTP POST.'); } + /** @phpstan-ignore-next-line */ if (!move_uploaded_file($this->file, $targetPath)) { throw new \RuntimeException('An error occurred while moving the file.'); } diff --git a/src/Components/Http/Uri.php b/src/Components/Http/Uri.php index f89a51a..2a55396 100644 --- a/src/Components/Http/Uri.php +++ b/src/Components/Http/Uri.php @@ -87,6 +87,7 @@ class Uri implements UriInterface * Les ports supportés. * * @var array + * @phpstan-var array */ protected $ports = [ 'ftp' => 21, @@ -161,7 +162,7 @@ public function __toString(): string * * @return string Schéma de l'URI ou une chaine vide. */ - public function getScheme() + public function getScheme(): string { return $this->scheme; } @@ -174,7 +175,7 @@ public function getScheme() * * @return string Autorité de l'URI, au format "[user-info@]host[:port]". */ - public function getAuthority() + public function getAuthority(): string { $authority = $this->getUserInfo() ? $this->getUserInfo() . '@' @@ -193,7 +194,7 @@ public function getAuthority() * @return string Informations de l'utilisateur de l'URI, * au format "nom d'utilisateur[:mot de passe]". */ - public function getUserInfo() + public function getUserInfo(): string { if ($this->user !== '') { return $this->user . ($this->pass !== '' @@ -212,7 +213,7 @@ public function getUserInfo() * * @return string Hôte de l'URI. */ - public function getHost() + public function getHost(): string { return $this->host; } @@ -223,7 +224,7 @@ public function getHost() * * @return null|int Port de l'URI. */ - public function getPort() + public function getPort(): ?int { return $this->port; } @@ -236,7 +237,7 @@ public function getPort() * * @return string Chemin de l'URI. */ - public function getPath() + public function getPath(): string { return $this->path; } @@ -249,7 +250,7 @@ public function getPath() * * @return string Chaîne de requête de l'URI. */ - public function getQuery() + public function getQuery(): string { return $this->query; } @@ -263,7 +264,7 @@ public function getQuery() * * @return string Fragment de requête de l'URI. */ - public function getFragment() + public function getFragment(): string { return $this->fragment; } @@ -278,7 +279,7 @@ public function getFragment() * * @return static Nouvelle instance avec le schéma spécifié. */ - public function withScheme($scheme) + public function withScheme($scheme): UriInterface { $clone = clone $this; $clone->scheme = $this->filterScheme($scheme); @@ -294,7 +295,7 @@ public function withScheme($scheme) * * @return static Nouvelle instance avec les informations utilisateur spécifiées. */ - public function withUserInfo($user, $password = null) + public function withUserInfo($user, $password = null): UriInterface { $clone = clone $this; $clone->user = $this->filterString($user); @@ -315,7 +316,7 @@ public function withUserInfo($user, $password = null) * * @return static Nouvelle instance avec l'hôte spécifié. */ - public function withHost($host) + public function withHost($host): UriInterface { $clone = clone $this; $clone->host = $this->filterStringToLower($host); @@ -335,7 +336,7 @@ public function withHost($host) * * @return static Nouvelle instance avec le port spécifié. */ - public function withPort($port) + public function withPort($port): UriInterface { $clone = clone $this; $clone->port = $this->filterPort($port); @@ -352,7 +353,7 @@ public function withPort($port) * * @return static Nouvelle instance avec le chemin spécifié. */ - public function withPath($path) + public function withPath($path): UriInterface { $clone = clone $this; $clone->path = $this->filterPath($path); @@ -369,7 +370,7 @@ public function withPath($path) * * @return static Nouvelle instance avec la chaîne de requête spécifiée. */ - public function withQuery($query) + public function withQuery($query): UriInterface { $clone = clone $this; $clone->query = $this->filterQuery($query); @@ -384,7 +385,7 @@ public function withQuery($query) * * @return static Une nouvelle instance avec le fragment spécifié. */ - public function withFragment($fragment) + public function withFragment($fragment): UriInterface { $clone = clone $this; $clone->fragment = $this->filterFragment($fragment); @@ -401,9 +402,9 @@ public function withFragment($fragment) * * @return bool */ - public static function validePort($port): bool + public static function validePort(int $port): bool { - return is_int($port) && ($port > 0 && $port <= 65535); + return $port > 0 && $port <= 65535; } /** @@ -417,7 +418,7 @@ public static function validePort($port): bool * * @return UriInterface Nouvelle instance d'URI. */ - public static function create($uri): UriInterface + public static function create(string $uri): UriInterface { if (($parse = parse_url($uri)) === false) { throw new \InvalidArgumentException('Unable to parse URI'); @@ -446,7 +447,7 @@ public static function create($uri): UriInterface /** * Filtre un schéma. * - * @param string|null $sch Schéma à filtrer. + * @param mixed $sch Schéma à filtrer. * * @throws \InvalidArgumentException Le schéma n'est pas pris en compte. * @@ -472,7 +473,7 @@ protected function filterScheme($sch = ''): string /** * Filtre un port. * - * @param int|null $port Port à filtrer. + * @param mixed $port Port à filtrer. * * @throws \InvalidArgumentException Le port n'est pas dans la gamme des ports TCP/UDP. * @@ -484,19 +485,24 @@ protected function filterPort($port): ?int return null; } + if (!is_int($port)) { + throw new \InvalidArgumentException( + sprintf('The port of must be of type integer: %s given', gettype($port)) + ); + } if (!self::validePort($port)) { throw new \InvalidArgumentException('The port is not in the TCP/UDP port.'); } return $this->validPortStandard($port) ? null - : (int) $port; + : $port; } /** * Filtre une requête. * - * @param string|null $query Requête à filtrer. + * @param mixed $query Requête à filtrer. * * @return string Requête normalisée. */ @@ -510,7 +516,7 @@ protected function filterQuery($query): string /** * Filtre une ancre. * - * @param string|null $fragment Ancre à filtrer. + * @param mixed $fragment Ancre à filtrer. * * @return string Ancre normalisée. */ @@ -524,7 +530,7 @@ protected function filterFragment($fragment): string /** * Filtre un chemin. * - * @param string|null $path Chemin à filtrer. + * @param mixed $path Chemin à filtrer. * * @return string Chemin normalisé. */ @@ -538,7 +544,7 @@ protected function filterPath($path): string /** * Filtre une chaine de caractère. * - * @param string|null|object $value Chaine de caractère à filtrer. + * @param mixed $value Chaine de caractère à filtrer. * * @return string Chaine de caractère normalisée. */ @@ -547,7 +553,7 @@ protected function filterString($value): string if ($value === null) { return ''; } - if (!is_string($value) && !method_exists($value, '__toString')) { + if (!is_string($value) && (!is_object($value) || !method_exists($value, '__toString'))) { throw new \InvalidArgumentException('The value must be a string.'); } @@ -557,7 +563,7 @@ protected function filterString($value): string /** * Filtre une chaine de caractère et la renvoie en minuscule. * - * @param string $value Chaine de caractère à filtrer. + * @param mixed $value Chaine de caractère à filtrer. * * @return string Chaine de caractère filtré. */ @@ -573,7 +579,7 @@ protected function filterStringToLower($value): string * * @return bool */ - protected function validPortStandard($port): bool + protected function validPortStandard(int $port): bool { return in_array($port, $this->ports) && $this->scheme === array_keys($this->ports, $port)[ 0 ]; @@ -586,7 +592,7 @@ protected function validPortStandard($port): bool * * @return string Chaine de requête en encodage URL. */ - protected function rawurldecodeValue($query): string + protected function rawurldecodeValue(string $query): string { return preg_replace_callback( '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', diff --git a/src/Components/Http/Utils.php b/src/Components/Http/Utils.php new file mode 100644 index 0000000..b5956e1 --- /dev/null +++ b/src/Components/Http/Utils.php @@ -0,0 +1,30 @@ +getMessage() + ), 0, $e); + } + + return $handle; + } +} diff --git a/src/Components/HttpClient/Client.php b/src/Components/HttpClient/Client.php index f8b938d..593cd72 100644 --- a/src/Components/HttpClient/Client.php +++ b/src/Components/HttpClient/Client.php @@ -74,10 +74,15 @@ public function sendRequest(RequestInterface $request): ResponseInterface throw new RequestException($request, curl_error($this->handle)); } - $code = curl_getinfo($this->handle, CURLINFO_RESPONSE_CODE); + /** @var int $code */ + $code = curl_getinfo($this->handle, CURLINFO_RESPONSE_CODE); + + /** @var int $headerSize */ $headerSize = curl_getinfo($this->handle, CURLINFO_HEADER_SIZE); - $headers = substr($exec, 0, $headerSize); - $body = substr($exec, $headerSize); + + /** @var string $exec */ + $headers = substr($exec, 0, $headerSize); + $body = substr($exec, $headerSize); curl_close($this->handle); unset($this->handle); diff --git a/src/Components/Paginate/Paginator.php b/src/Components/Paginate/Paginator.php index 896853d..2aa9df2 100644 --- a/src/Components/Paginate/Paginator.php +++ b/src/Components/Paginate/Paginator.php @@ -102,19 +102,19 @@ public function __toString(): string /** * Change la page courante. * - * @param numeric $current + * @param int $current * * @throws \InvalidArgumentException La page courante doit être * un nombre numérique supérieur à 1. * * @return $this */ - public function setCurrent($current): self + public function setCurrent(int $current): self { - if (!is_numeric($current) || $current < 1) { + if ($current < 1) { throw new \InvalidArgumentException('The current page must be a numeric number greater than 1.'); } - $this->current = (int) $current; + $this->current = $current; return $this; } @@ -122,19 +122,19 @@ public function setCurrent($current): self /** * Change le nombre de page maximum à afficher. * - * @param numeric $max + * @param int $max * * @throws \InvalidArgumentException Le nombre de page à afficher doit être * supérieur ou égale à trois. * * @return $this */ - public function setMaxPage($max = 3): self + public function setMaxPage(int $max = 3): self { - if (!is_numeric($max) || $max < 3) { + if ($max < 3) { throw new \InvalidArgumentException('The number of pages to display must be greater than or equal to three.'); } - $this->nbMaxPage = (int) $max; + $this->nbMaxPage = $max; return $this; } diff --git a/src/Components/Router/Router.php b/src/Components/Router/Router.php index 73be8ea..4775755 100644 --- a/src/Components/Router/Router.php +++ b/src/Components/Router/Router.php @@ -66,6 +66,7 @@ public function parse(RequestInterface $request): ?array $routesByMethod = Route::getRouteByMethod($request->getMethod()); foreach ($routesByMethod as $key) { + /** @var array $route */ $route = Route::getRoute($key); if (!empty($route[ 'with' ])) { @@ -94,7 +95,7 @@ public function parse(RequestInterface $request): ?array public function execute(array $route, ?RequestInterface $request = null) { $class = strstr($route[ 'uses' ], '@', true); - $method = substr(strrchr($route[ 'uses' ], '@'), 1); + $method = ltrim($route[ 'uses' ], $class . '@'); /* Cherche les différents paramètres de l'URL pour l'injecter dans la méthode. */ if (!empty($route[ 'with' ])) { @@ -111,8 +112,6 @@ public function execute(array $route, ?RequestInterface $request = null) $property = $reflection->getProperty('container'); $property->setAccessible(true); $property->setValue($obj, $this->container); - } else { - $obj->container = $this->container; } return $reflection->getMethod($method)->invokeArgs($obj, $params); @@ -159,14 +158,16 @@ public function getPath( $path = $route[ 'path' ]; foreach ($route[ 'with' ] as $key => $value) { - if ($strict && !isset($params[ $key ])) { - throw new \InvalidArgumentException(htmlspecialchars( - "the argument $key is missing" - )); - } - if (!$strict && !isset($params[ $key ])) { + if (!isset($params[ $key ])) { + if ($strict) { + throw new \InvalidArgumentException(htmlspecialchars( + "the argument $key is missing" + )); + } + continue; } + $value = str_replace([ '(', '/' ], [ '(?:', '\/' ], $value); if ($strict && !preg_match('/^' . $value . '$/', $params[ $key ])) { throw new Exception\RouteArgumentException($params[ $key ], $value, $path); diff --git a/src/Components/Util/Util.php b/src/Components/Util/Util.php index 9486cda..f0ddebc 100644 --- a/src/Components/Util/Util.php +++ b/src/Components/Util/Util.php @@ -107,9 +107,15 @@ public static function getJson(string $strFile, bool $assoc = true) ); } - $out = json_decode(file_get_contents($strFile), $assoc, 512, JSON_UNESCAPED_UNICODE); + $data = file_get_contents($strFile); + if ($data === false) { + throw new \RuntimeException( + htmlspecialchars("An error is encountered while reading $strFile file.") + ); + } + $out = json_decode($data, $assoc, 512, JSON_UNESCAPED_UNICODE); - if ((!is_array($out) && $assoc) || (!is_object($out) && !$assoc)) { + if (!is_array($out) && !is_object($out)) { throw new \Exception( htmlspecialchars("The JSON $strFile file is invalid.") ); @@ -139,15 +145,21 @@ public static function createJson( } $pathFile = $cleanPath . self::DS . $strFileName . '.json'; + if (file_exists($pathFile)) { + return null; + } - if (!file_exists($pathFile)) { - $file = fopen($pathFile, 'w+'); - fwrite($file, json_encode($data, JSON_UNESCAPED_UNICODE)); + $file = self::tryFopen($pathFile, 'w+'); - return fclose($file); + $jsonEncode = json_encode($data, JSON_UNESCAPED_UNICODE); + if ($jsonEncode === false) { + throw new \RuntimeException( + "An error is encountered while serializing the $pathFile file." + ); } + fwrite($file, $jsonEncode); - return null; + return fclose($file); } /** @@ -164,11 +176,19 @@ public static function saveJson( string $strFileName, array $data ): bool { - $fp = fopen( - self::cleanPath($strPath) . self::DS . $strFileName . '.json', + $pathFile = self::cleanPath($strPath) . self::DS . $strFileName . '.json'; + $fp = self::tryFopen( + $pathFile, 'w' ); - fwrite($fp, json_encode($data, JSON_UNESCAPED_UNICODE)); + + $jsonEncode = json_encode($data, JSON_UNESCAPED_UNICODE); + if ($jsonEncode === false) { + throw new \RuntimeException( + "An error is encountered while serializing the $pathFile file." + ); + } + fwrite($fp, $jsonEncode); return fclose($fp); } @@ -276,7 +296,7 @@ public static function cleanPath( string $characterMask = "/ \t\n\r\0\x0B" ): string { $str = str_replace('\\', '/', $path); - $str = preg_replace('/\/+/', '/', $str); + $str = preg_replace('/\/+/', '/', $str) ?? ''; return rtrim($str, $characterMask); } @@ -396,7 +416,7 @@ public static function strSlug( string $ignore = '' ): string { $output = mb_strtolower($str, 'UTF-8'); - $output = str_replace(self::$search, self::$replace, $output) ?? ''; + $output = str_replace(self::$search, self::$replace, $output); $output = preg_replace('/([^\w' . $ignore . ']|_)+/i', $separator, $output) ?? ''; return trim($output, $separator); @@ -465,9 +485,10 @@ public static function getOctetShortBytesPhp(string $shortBytes): ?int /** * Retourne la quantité de données maximum à l'upload autorisé par votre configuration. + * Ou null si aucune donnée minimum ne peut-être trouvée. * memory_limit: -1 no limit */ - public static function getOctetUploadLimit(): int + public static function getOctetUploadLimit(): ?int { $limitMin = []; foreach ([ 'upload_max_filesize', 'post_max_size', 'memory_limit' ] as $ini) { @@ -483,7 +504,14 @@ public static function getOctetUploadLimit(): int } } - return min(...$limitMin); + try { + /** @var int $min */ + $min = min(...$limitMin); + } catch (\ArgumentCountError $e) { + return null; + } + + return $min; } /** @@ -499,7 +527,7 @@ public static function strHumansTimeDiff( \DateTimeInterface $from, string $to = 'now' ): array { - $interval = \date_create($to)->diff($from); + $interval = self::tryDateCreate($to)->diff($from); if (($value = $interval->y) >= 1) { $str = $value > 1 @@ -540,4 +568,38 @@ public static function strHumansTimeDiff( ? [ $str . $suffix, $value ] : [ $str . $suffix, 1 ]; } + + /** + * @param string $filename + * @param string $mode + * + * @throws \RuntimeException + * @return resource + */ + public static function tryFopen(string $filename, string $mode) + { + try { + /** @var resource $handle */ + $handle = fopen($filename, $mode); + } catch (\Exception $e) { + throw new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $e->getMessage() + ), 0, $e); + } + + return $handle; + } + + public static function tryDateCreate(string $to = 'now'): \DateTime + { + $handle = \date_create($to); + if ($handle === false) { + throw new \InvalidArgumentException('The date must be in valid format'); + } + + return $handle; + } } diff --git a/src/Components/Validator/Filters/ToBool.php b/src/Components/Validator/Filters/ToBool.php index 5df0e29..244cef5 100644 --- a/src/Components/Validator/Filters/ToBool.php +++ b/src/Components/Validator/Filters/ToBool.php @@ -28,7 +28,7 @@ class ToBool extends \Soosyze\Components\Validator\Filter * * @return bool */ - protected function clean(string $key, $value, $args) + protected function clean(string $key, $value, $args): bool { if (!$this->isBool($value)) { throw new \InvalidArgumentException('The type must be validated before being filtered.'); diff --git a/src/Components/Validator/Filters/ToFloat.php b/src/Components/Validator/Filters/ToFloat.php index 765557e..d5f4874 100644 --- a/src/Components/Validator/Filters/ToFloat.php +++ b/src/Components/Validator/Filters/ToFloat.php @@ -22,13 +22,13 @@ class ToFloat extends \Soosyze\Components\Validator\Filter * * @param string $key Identifiant de la valeur. * @param mixed $value Valeur à filtrer. - * @param string $args Argument de filtre. + * @param mixed $args Argument de filtre. * * @throws \InvalidArgumentException The type must be validated before being filtered. * * @return float */ - protected function clean(string $key, $value, $args) + protected function clean(string $key, $value, $args): float { if (($out = filter_var($value, FILTER_VALIDATE_FLOAT)) === false) { throw new \InvalidArgumentException('The type must be validated before being filtered.'); diff --git a/src/Components/Validator/Filters/ToHtmlsc.php b/src/Components/Validator/Filters/ToHtmlsc.php index e832636..d1ab5c6 100644 --- a/src/Components/Validator/Filters/ToHtmlsc.php +++ b/src/Components/Validator/Filters/ToHtmlsc.php @@ -28,7 +28,7 @@ class ToHtmlsc extends \Soosyze\Components\Validator\Filter * * @return string */ - protected function clean(string $key, $value, $args) + protected function clean(string $key, $value, $args): string { if (!is_string($value)) { throw new \InvalidArgumentException('The type must be validated before being filtered.'); diff --git a/src/Components/Validator/Filters/ToInt.php b/src/Components/Validator/Filters/ToInt.php index b044bf9..da10e77 100644 --- a/src/Components/Validator/Filters/ToInt.php +++ b/src/Components/Validator/Filters/ToInt.php @@ -28,7 +28,7 @@ class ToInt extends \Soosyze\Components\Validator\Filter * * @return int */ - protected function clean(string $key, $value, $args) + protected function clean(string $key, $value, $args): int { if (($out = filter_var($value, FILTER_VALIDATE_INT)) === false) { throw new \InvalidArgumentException('The type must be validated before being filtered.'); diff --git a/src/Components/Validator/Filters/ToLtrim.php b/src/Components/Validator/Filters/ToLtrim.php index 3cde056..ea476b3 100644 --- a/src/Components/Validator/Filters/ToLtrim.php +++ b/src/Components/Validator/Filters/ToLtrim.php @@ -20,21 +20,25 @@ class ToLtrim extends \Soosyze\Components\Validator\Filter /** * Filtre une valeur avec la méthode htmlspecialchars. * - * @param string $key Identifiant de la valeur. - * @param mixed $value Valeur à filtrer. - * @param mixed|null $args Argument de filtre. + * @param string $key Identifiant de la valeur. + * @param mixed $value Valeur à filtrer. + * @param mixed $args Argument de filtre. * * @throws \InvalidArgumentException The type must be validated before being filtered. * * @return string */ - protected function clean(string $key, $value, $args) + protected function clean(string $key, $value, $args): string { if (!is_string($value)) { throw new \InvalidArgumentException('The type must be validated before being filtered.'); } + if (!is_string($args)) { + throw new \InvalidArgumentException( + sprintf('The argument must be of type string: %s given', gettype($args)) + ); + } - return ltrim($value, $args - ?? " \t\n\r\0\x0B"); + return ltrim($value, $args === '' ? " \t\n\r\0\x0B" : $args); } } diff --git a/src/Components/Validator/Filters/ToRtrim.php b/src/Components/Validator/Filters/ToRtrim.php index ea4f62c..43899e6 100644 --- a/src/Components/Validator/Filters/ToRtrim.php +++ b/src/Components/Validator/Filters/ToRtrim.php @@ -22,19 +22,23 @@ class ToRtrim extends \Soosyze\Components\Validator\Filter * * @param string $key Identifiant de la valeur. * @param mixed $value Valeur à filtrer. - * @param string $args Argument de filtre. + * @param mixed $args Argument de filtre. * * @throws \InvalidArgumentException The type must be validated before being filtered. * * @return string */ - protected function clean(string $key, $value, $args) + protected function clean(string $key, $value, $args): string { if (!is_string($value)) { throw new \InvalidArgumentException('The type must be validated before being filtered.'); } + if (!is_string($args)) { + throw new \InvalidArgumentException( + sprintf('The argument must be of type string: %s given', gettype($args)) + ); + } - return rtrim($value, $args - ?? " \t\n\r\0\x0B"); + return rtrim($value, $args === '' ? " \t\n\r\0\x0B" : $args); } } diff --git a/src/Components/Validator/Filters/ToStripTags.php b/src/Components/Validator/Filters/ToStripTags.php index 0b57585..18e2c7f 100644 --- a/src/Components/Validator/Filters/ToStripTags.php +++ b/src/Components/Validator/Filters/ToStripTags.php @@ -24,17 +24,22 @@ class ToStripTags extends \Soosyze\Components\Validator\Filter * * @param string $key Identifiant de la valeur. * @param mixed $value Valeur à filtrer. - * @param string $args Liste des balise HTML autorisés. + * @param mixed $args Liste des balise HTML autorisés. * * @throws \InvalidArgumentException The type must be validated before being filtered. * * @return string */ - protected function clean(string $key, $value, $args = self::ALLOWABLE_TAGS) + protected function clean(string $key, $value, $args = self::ALLOWABLE_TAGS): string { if (!is_string($value)) { throw new \InvalidArgumentException('The type must be validated before being filtered.'); } + if (!is_string($args)) { + throw new \InvalidArgumentException( + sprintf('The argument must be of type string: %s given', gettype($args)) + ); + } return strip_tags($value, $args); } diff --git a/src/Components/Validator/Filters/ToTrim.php b/src/Components/Validator/Filters/ToTrim.php index 61563e2..0758d56 100644 --- a/src/Components/Validator/Filters/ToTrim.php +++ b/src/Components/Validator/Filters/ToTrim.php @@ -10,6 +10,8 @@ namespace Soosyze\Components\Validator\Filters; +use Soosyze\Components\Validator\Filter; + /** * {@inheritdoc} * @@ -22,19 +24,23 @@ class ToTrim extends \Soosyze\Components\Validator\Filter * * @param string $key Identifiant de la valeur. * @param mixed $value Valeur à filtrer. - * @param string $args Argument de filtre. + * @param mixed $args Argument de filtre. * * @throws \InvalidArgumentException The type must be validated before being filtered. * * @return string */ - protected function clean(string $key, $value, $args) + protected function clean(string $key, $value, $args): string { if (!is_string($value)) { throw new \InvalidArgumentException('The type must be validated before being filtered.'); } + if (!is_string($args)) { + throw new \InvalidArgumentException( + sprintf('The argument must be of type string: %s given', gettype($args)) + ); + } - return trim($value, $args - ?? " \t\n\r\0\x0B"); + return trim($value, $args === '' ? " \t\n\r\0\x0B" : $args); } } diff --git a/src/Components/Validator/Rule.php b/src/Components/Validator/Rule.php index 0c051b9..af453ce 100644 --- a/src/Components/Validator/Rule.php +++ b/src/Components/Validator/Rule.php @@ -34,7 +34,7 @@ abstract class Rule /** * Argument de test. * - * @var string + * @var mixed */ protected $args = ''; @@ -97,10 +97,10 @@ abstract class Rule /** * Exécute le test de validation. * - * @param string $keyRule Clé du test. - * @param string $keyValue Identifiant de la valeur. - * @param mixed|null $args Argument de test, peut-être une valeur d'un champ. - * @param bool $not Inverse le test. + * @param string $keyRule Clé du test. + * @param string $keyValue Identifiant de la valeur. + * @param mixed $args Argument de test, peut-être une valeur d'un champ. + * @param bool $not Inverse le test. * * @return $this */ @@ -270,8 +270,8 @@ public function getValue() * Défini le test. * * @param string $keyRule Clé du test. - * @param string $value Valeur à tester. - * @param string $args Argument de test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. * @param bool $not Inverse le test. * * @return void @@ -319,12 +319,10 @@ protected function addReturn( * @throws \InvalidArgumentException The minimum value must not be greater than the maximum value. * * @return numeric[] Tableau des valeurs min et max. + * @phpstan-return array{min: numeric, max: numeric} */ - protected function getParamMinMax(?string $arg): array + protected function getParamMinMax(string $arg): array { - if ($arg === null) { - throw new \InvalidArgumentException('Between values are invalid.'); - } $explode = explode(',', $arg); if (!isset($explode[ 0 ], $explode[ 1 ])) { throw new \InvalidArgumentException('Between values are invalid.'); diff --git a/src/Components/Validator/Rules/Accepted.php b/src/Components/Validator/Rules/Accepted.php index b5490f2..e7e9c0b 100644 --- a/src/Components/Validator/Rules/Accepted.php +++ b/src/Components/Validator/Rules/Accepted.php @@ -20,10 +20,10 @@ class Accepted extends \Soosyze\Components\Validator\Rule /** * Test si la valeur est égale à "1", "true", "on" et "yes". * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/AlphaNum.php b/src/Components/Validator/Rules/AlphaNum.php index f326b14..0fc656d 100644 --- a/src/Components/Validator/Rules/AlphaNum.php +++ b/src/Components/Validator/Rules/AlphaNum.php @@ -20,10 +20,10 @@ class AlphaNum extends \Soosyze\Components\Validator\Rule /** * Test si la valeur est Alpha numérique [a-zA-Z0-9]. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/AlphaNumText.php b/src/Components/Validator/Rules/AlphaNumText.php index f245e4c..ce42a63 100644 --- a/src/Components/Validator/Rules/AlphaNumText.php +++ b/src/Components/Validator/Rules/AlphaNumText.php @@ -20,10 +20,10 @@ class AlphaNumText extends Regex /** * Test si la valeur est alpha numérique et possède des caractères textuelles [a-zA-Z0-9 .!?,;:_-]. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/ArrayType.php b/src/Components/Validator/Rules/ArrayType.php index fa994d0..3d13d33 100644 --- a/src/Components/Validator/Rules/ArrayType.php +++ b/src/Components/Validator/Rules/ArrayType.php @@ -22,7 +22,7 @@ class ArrayType extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param mixed $values Valeur à tester. - * @param string $args Argument de test. + * @param mixed $args Argument de test. * @param bool $not Inverse le test. */ protected function test(string $key, $values, $args, bool $not): void diff --git a/src/Components/Validator/Rules/Base64.php b/src/Components/Validator/Rules/Base64.php index 591d1e1..6d8341a 100644 --- a/src/Components/Validator/Rules/Base64.php +++ b/src/Components/Validator/Rules/Base64.php @@ -20,10 +20,10 @@ class Base64 extends \Soosyze\Components\Validator\Rule /** * Test si la valeur est égale à "1", "true", "on" et "yes". * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Between.php b/src/Components/Validator/Rules/Between.php index 3f98e58..c30a57b 100644 --- a/src/Components/Validator/Rules/Between.php +++ b/src/Components/Validator/Rules/Between.php @@ -20,10 +20,10 @@ class Between extends Size /** * Test si une valeur est entre 2 valeurs de comparaison. * - * @param string $key Clé du test. - * @param array|float|int|object|ressource|string|UploadedFileInterface $value Valeur à tester. - * @param string $args Liste de 2 valeurs de comparaison séparées par une virgule. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param array|float|int|object|resource|string|UploadedFileInterface $value Valeur à tester. + * @param mixed $args Liste de 2 valeurs de comparaison séparées par une virgule. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { @@ -32,6 +32,9 @@ protected function test(string $key, $value, $args, bool $not): void if ($this->hasErrors()) { return; } + if (!is_string($args)) { + throw new \TypeError('The comparisons arguments must be a string.'); + } [ $min, $max ] = $this->getParamMinMax($args); $this->sizeBetween($key, $length, $min, $max, $not); @@ -84,11 +87,8 @@ protected function sizeBetween( * * @return array */ - protected function getParamMinMax(?string $args): array + protected function getParamMinMax(string $args): array { - if ($args === null) { - throw new \InvalidArgumentException('Between values are invalid.'); - } $explode = explode(',', $args); if (!isset($explode[ 0 ], $explode[ 1 ])) { throw new \InvalidArgumentException('Between values are invalid.'); diff --git a/src/Components/Validator/Rules/BetweenNumeric.php b/src/Components/Validator/Rules/BetweenNumeric.php index dbecd35..af8d9ac 100644 --- a/src/Components/Validator/Rules/BetweenNumeric.php +++ b/src/Components/Validator/Rules/BetweenNumeric.php @@ -22,7 +22,7 @@ class BetweenNumeric extends Between * * @param string $key Clé du test. * @param numeric $value Valeur à tester. - * @param string $args Liste de 2 valeurs de comparaison séparées par une virgule. + * @param mixed $args Liste de 2 valeurs de comparaison séparées par une virgule. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void @@ -32,6 +32,9 @@ protected function test(string $key, $value, $args, bool $not): void if ($this->hasErrors()) { return; } + if (!is_string($args)) { + throw new \TypeError('The comparisons arguments must be a string.'); + } [ $min, $max ] = $this->getParamMinMax($args); $this->sizeBetween($key, $length, $min, $max, $not); diff --git a/src/Components/Validator/Rules/BoolType.php b/src/Components/Validator/Rules/BoolType.php index 0849329..d2c116d 100644 --- a/src/Components/Validator/Rules/BoolType.php +++ b/src/Components/Validator/Rules/BoolType.php @@ -20,10 +20,10 @@ class BoolType extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est de type boolean. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/ClassExists.php b/src/Components/Validator/Rules/ClassExists.php index b5896a1..93d9b65 100644 --- a/src/Components/Validator/Rules/ClassExists.php +++ b/src/Components/Validator/Rules/ClassExists.php @@ -20,10 +20,10 @@ class ClassExists extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est une adresse IP. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/ColorHex.php b/src/Components/Validator/Rules/ColorHex.php index 2c478b5..12e464e 100644 --- a/src/Components/Validator/Rules/ColorHex.php +++ b/src/Components/Validator/Rules/ColorHex.php @@ -20,10 +20,10 @@ class ColorHex extends Regex /** * Test si la valeur correspond à une couleur au format hexadécimale à 3 ou 6 caractères. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Date.php b/src/Components/Validator/Rules/Date.php index 7423328..e5f704a 100644 --- a/src/Components/Validator/Rules/Date.php +++ b/src/Components/Validator/Rules/Date.php @@ -20,10 +20,10 @@ class Date extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est une date. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/DateAfter.php b/src/Components/Validator/Rules/DateAfter.php index 5fed1e6..0531c38 100644 --- a/src/Components/Validator/Rules/DateAfter.php +++ b/src/Components/Validator/Rules/DateAfter.php @@ -22,12 +22,16 @@ class DateAfter extends Date * * @param string $key Clé du test. * @param string $value Date à tester. - * @param string $args Date de comparaison. + * @param mixed $args Date de comparaison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { + if (!is_string($args)) { + throw new \TypeError('The comparison argument must be string.'); + } parent::test('date', $args, '', true); + if ($this->hasErrors()) { throw new \InvalidArgumentException('The comparison date is not correct.'); } diff --git a/src/Components/Validator/Rules/DateAfterOrEqual.php b/src/Components/Validator/Rules/DateAfterOrEqual.php index f4913cd..b476caa 100644 --- a/src/Components/Validator/Rules/DateAfterOrEqual.php +++ b/src/Components/Validator/Rules/DateAfterOrEqual.php @@ -22,7 +22,7 @@ class DateAfterOrEqual extends DateAfter * * @param string $key Clé du test. * @param string $value Date à tester. - * @param string $args Date de comparaison. + * @param mixed $args Date de comparaison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void diff --git a/src/Components/Validator/Rules/DateBefore.php b/src/Components/Validator/Rules/DateBefore.php index ccaaee3..0ddd1ff 100644 --- a/src/Components/Validator/Rules/DateBefore.php +++ b/src/Components/Validator/Rules/DateBefore.php @@ -22,12 +22,16 @@ class DateBefore extends Date * * @param string $key Clé du test. * @param string $value Date à tester. - * @param string $args Date de comparaison. + * @param mixed $args Date de comparaison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { + if (!is_string($args)) { + throw new \TypeError('The comparison argument must be string.'); + } parent::test('date', $args, '', true); + if ($this->hasErrors()) { throw new \InvalidArgumentException('The comparison date is not correct.'); } diff --git a/src/Components/Validator/Rules/DateBeforeOrEqual.php b/src/Components/Validator/Rules/DateBeforeOrEqual.php index a4bbb68..85a9889 100644 --- a/src/Components/Validator/Rules/DateBeforeOrEqual.php +++ b/src/Components/Validator/Rules/DateBeforeOrEqual.php @@ -22,7 +22,7 @@ class DateBeforeOrEqual extends DateBefore * * @param string $key Clé du test. * @param string $value Date à tester. - * @param string $args Date de comparaison. + * @param mixed $args Date de comparaison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void diff --git a/src/Components/Validator/Rules/DateFormat.php b/src/Components/Validator/Rules/DateFormat.php index 5d7ad2e..523a574 100644 --- a/src/Components/Validator/Rules/DateFormat.php +++ b/src/Components/Validator/Rules/DateFormat.php @@ -24,11 +24,14 @@ class DateFormat extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param string $value Valeur à tester. - * @param string $args Format de la date (ex: Y-m-d). + * @param mixed $args Format de la date (ex: Y-m-d). * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { + if (!is_string($args)) { + throw new \TypeError('The date format must be a string.'); + } $dateFormat = date_parse_from_format($args, $value); $errorFormat = $dateFormat[ 'error_count' ] === 0 && $dateFormat[ 'warning_count' ] === 0; diff --git a/src/Components/Validator/Rules/Dir.php b/src/Components/Validator/Rules/Dir.php index c7a66d9..2b96fb3 100644 --- a/src/Components/Validator/Rules/Dir.php +++ b/src/Components/Validator/Rules/Dir.php @@ -20,10 +20,10 @@ class Dir extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est un répértoire existant sur le serveur. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Email.php b/src/Components/Validator/Rules/Email.php index aeb8a4e..90daef2 100644 --- a/src/Components/Validator/Rules/Email.php +++ b/src/Components/Validator/Rules/Email.php @@ -20,10 +20,10 @@ class Email extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est un email. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Equal.php b/src/Components/Validator/Rules/Equal.php index 34da160..02aedc1 100644 --- a/src/Components/Validator/Rules/Equal.php +++ b/src/Components/Validator/Rules/Equal.php @@ -22,7 +22,7 @@ class Equal extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param scalar $value Valeur à tester. - * @param string $args Valeur de comparaison. + * @param mixed $args Valeur de comparaison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void diff --git a/src/Components/Validator/Rules/EqualStrict.php b/src/Components/Validator/Rules/EqualStrict.php index 2455708..6d1cbc2 100644 --- a/src/Components/Validator/Rules/EqualStrict.php +++ b/src/Components/Validator/Rules/EqualStrict.php @@ -22,7 +22,7 @@ class EqualStrict extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param scalar $value Valeur à tester. - * @param string $args Valeur de comparaison. + * @param mixed $args Valeur de comparaison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void diff --git a/src/Components/Validator/Rules/File.php b/src/Components/Validator/Rules/File.php index 365bd44..64ff92a 100644 --- a/src/Components/Validator/Rules/File.php +++ b/src/Components/Validator/Rules/File.php @@ -22,10 +22,10 @@ class File extends \Soosyze\Components\Validator\Rule /** * Test si la valeur est un fichier. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { @@ -115,12 +115,13 @@ protected function checkErrorFile(string $key, UploadedFileInterface $value): vo */ protected function getMime(UploadedFileInterface $upload): string { + /** @var string $file */ $file = $upload->getStream()->getMetadata('uri'); $mime = (new \finfo(FILEINFO_MIME_TYPE))->file($file); if ($mime === false) { - throw new \Exception(); + throw new \RuntimeException('An error occurred while returning information about a file.'); } return $mime; diff --git a/src/Components/Validator/Rules/FileExtensions.php b/src/Components/Validator/Rules/FileExtensions.php index b32cae8..15b9d6d 100644 --- a/src/Components/Validator/Rules/FileExtensions.php +++ b/src/Components/Validator/Rules/FileExtensions.php @@ -24,7 +24,7 @@ class FileExtensions extends File * * @param string $key Clé du test. * @param UploadedFileInterface $value Valeur à tester. - * @param string $args Liste d'extensions séparé par une virgule. + * @param mixed $args Liste d'extensions séparé par une virgule. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void @@ -35,6 +35,9 @@ protected function test(string $key, $value, $args, bool $not): void return; } + if (!is_string($args)) { + throw new \TypeError('The list of allowed extensions must be a string.'); + } $extensions = explode(',', $args); $extension = $this->getExtension($value); diff --git a/src/Components/Validator/Rules/FileMimes.php b/src/Components/Validator/Rules/FileMimes.php index a53a9d1..bb5c5e1 100644 --- a/src/Components/Validator/Rules/FileMimes.php +++ b/src/Components/Validator/Rules/FileMimes.php @@ -10,6 +10,8 @@ namespace Soosyze\Components\Validator\Rules; +use Psr\Http\Message\UploadedFileInterface; + /** * {@inheritdoc} * @@ -27,13 +29,17 @@ class FileMimes extends FileExtensions /** * Test si l'extension du fichier est autorisée. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param string $args Liste des extensions autorisées. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param UploadedFileInterface $value Valeur à tester. + * @param mixed $args Liste des extensions autorisées. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { + if (!is_string($args)) { + throw new \TypeError('The list of allowed extensions must be a string.'); + } + parent::test('file_extensions', $value, $args, $not); if ($this->hasErrors()) { diff --git a/src/Components/Validator/Rules/FileMimetypes.php b/src/Components/Validator/Rules/FileMimetypes.php index feaec30..6c9b058 100644 --- a/src/Components/Validator/Rules/FileMimetypes.php +++ b/src/Components/Validator/Rules/FileMimetypes.php @@ -24,7 +24,7 @@ class FileMimetypes extends File * * @param string $key Clé du test. * @param UploadedFileInterface $value Valeur à tester. - * @param string $args Mime exacte ou le type du mime du fichier. + * @param mixed $args Mime exacte ou le type du mime du fichier. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void @@ -37,6 +37,10 @@ protected function test(string $key, $value, $args, bool $not): void $mtype = $this->getMime($value); + if (!is_string($args)) { + throw new \TypeError('The argument must be a string.'); + } + if (strpos($mtype, $args) !== 0 && $not) { $this->addReturn($key, 'mime_types', [ ':list' => $args ]); } elseif (strpos($mtype, $args) === 0 && !$not) { diff --git a/src/Components/Validator/Rules/FloatType.php b/src/Components/Validator/Rules/FloatType.php index d89b833..54cb867 100644 --- a/src/Components/Validator/Rules/FloatType.php +++ b/src/Components/Validator/Rules/FloatType.php @@ -20,10 +20,10 @@ class FloatType extends \Soosyze\Components\Validator\Rule /** * Test si une variable est de type ou de valeur numérique flottant. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/FontAwesome.php b/src/Components/Validator/Rules/FontAwesome.php index 525f662..477c837 100644 --- a/src/Components/Validator/Rules/FontAwesome.php +++ b/src/Components/Validator/Rules/FontAwesome.php @@ -37,11 +37,14 @@ class FontAwesome extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param string $value Valeur à tester. - * @param string $args Styles de fontawesome acceptés. + * @param mixed $args Styles de fontawesome acceptés. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { + if (!is_string($args)) { + throw new \TypeError('The argument must be a string.'); + } [ $pattern, $stylesPattern ] = $this->getPattern($args); if (!preg_match($pattern, $value) && $not) { diff --git a/src/Components/Validator/Rules/Image.php b/src/Components/Validator/Rules/Image.php index 9393ed4..1d11741 100644 --- a/src/Components/Validator/Rules/Image.php +++ b/src/Components/Validator/Rules/Image.php @@ -24,13 +24,15 @@ class Image extends FileMimes * * @param string $key Clé du test. * @param UploadedFileInterface $value Valeur à tester. - * @param string $args Liste d'extensions d'images autorisées. + * @param mixed $args Liste d'extensions d'images autorisées. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { - $extensions = $args - ?? 'jpe,jpg,jpeg,png,gif,svg'; + if (!is_string($args)) { + throw new \TypeError('The argument must be a string.'); + } + $extensions = $args === '' ? 'jpe,jpg,jpeg,png,gif,svg' : $args; parent::test('file_mimes', $value, $extensions, $not); if ($this->hasErrors()) { diff --git a/src/Components/Validator/Rules/ImageDimensions.php b/src/Components/Validator/Rules/ImageDimensions.php index e251e8b..e296bf0 100644 --- a/src/Components/Validator/Rules/ImageDimensions.php +++ b/src/Components/Validator/Rules/ImageDimensions.php @@ -24,11 +24,15 @@ abstract class ImageDimensions extends FileMimetypes * * @param string $key Clé du test. * @param UploadedFileInterface $value Valeur à tester. - * @param string $args Argument de test. + * @param mixed $args Argument de test. * @param bool $not Inverse le test. */ public function test(string $key, $value, $args, bool $not): void { + if (!is_string($args)) { + throw new \TypeError('The argument must be a string.'); + } + parent::test('file_mimetypes', $value, 'image', true); if ($this->hasErrors()) { @@ -53,7 +57,11 @@ public function test(string $key, $value, $args, bool $not): void */ protected function getDimensions(UploadedFileInterface $upload): array { - [ $width, $height ] = getimagesize($upload->getStream()->getMetadata('uri')); + /** @var string $uri */ + $uri = $upload->getStream()->getMetadata('uri'); + /** @var array $imageSize */ + $imageSize = getimagesize($uri); + [ $width, $height ] = $imageSize; return ['width' => $width, 'height' => $height]; } diff --git a/src/Components/Validator/Rules/InArray.php b/src/Components/Validator/Rules/InArray.php index 384ed5f..9168416 100644 --- a/src/Components/Validator/Rules/InArray.php +++ b/src/Components/Validator/Rules/InArray.php @@ -22,12 +22,18 @@ class InArray extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param scalar $value Valeur à tester. - * @param string $args Tableau de comparaison. + * @param mixed $args Tableau de comparaison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { - $array = explode(',', $args); + if (is_string($args)) { + $array = explode(',', $args); + } elseif (is_array($args)) { + $array = $args; + } else { + throw new \TypeError('The arguments must be a string or array.'); + } if (!in_array($value, $array) && $not) { $this->addReturn($key, 'must', [ ':list' => implode(', ', $array) ]); diff --git a/src/Components/Validator/Rules/Instance.php b/src/Components/Validator/Rules/Instance.php index 060bd52..4848f9f 100644 --- a/src/Components/Validator/Rules/Instance.php +++ b/src/Components/Validator/Rules/Instance.php @@ -22,7 +22,7 @@ class Instance extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param string $values Valeur à tester. - * @param string $args Argument de test. + * @param mixed $args Argument de test. * @param bool $not Inverse le test. */ protected function test(string $key, $values, $args, bool $not): void diff --git a/src/Components/Validator/Rules/IntType.php b/src/Components/Validator/Rules/IntType.php index 50b56f1..68ad7a1 100644 --- a/src/Components/Validator/Rules/IntType.php +++ b/src/Components/Validator/Rules/IntType.php @@ -20,10 +20,10 @@ class IntType extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est de type entier. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Ip.php b/src/Components/Validator/Rules/Ip.php index 04142fe..7795b30 100644 --- a/src/Components/Validator/Rules/Ip.php +++ b/src/Components/Validator/Rules/Ip.php @@ -20,10 +20,10 @@ class Ip extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est une adresse IP. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/IsFile.php b/src/Components/Validator/Rules/IsFile.php index 36d7517..b3c3167 100644 --- a/src/Components/Validator/Rules/IsFile.php +++ b/src/Components/Validator/Rules/IsFile.php @@ -20,10 +20,10 @@ class IsFile extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est un fichier existant sur le serveur. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/IterableType.php b/src/Components/Validator/Rules/IterableType.php index 347f997..1913cdb 100644 --- a/src/Components/Validator/Rules/IterableType.php +++ b/src/Components/Validator/Rules/IterableType.php @@ -22,7 +22,7 @@ class IterableType extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param mixed $values Valeur à tester. - * @param string $arg Argument de test. + * @param mixed $arg Argument de test. * @param bool $not Inverse le test. */ protected function test(string $key, $values, $arg, bool $not): void diff --git a/src/Components/Validator/Rules/Json.php b/src/Components/Validator/Rules/Json.php index d2bb4bc..1ed421e 100644 --- a/src/Components/Validator/Rules/Json.php +++ b/src/Components/Validator/Rules/Json.php @@ -20,10 +20,10 @@ class Json extends \Soosyze\Components\Validator\Rule /** * Test si la valeur et de type JSON. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Max.php b/src/Components/Validator/Rules/Max.php index bfb61a6..e914e29 100644 --- a/src/Components/Validator/Rules/Max.php +++ b/src/Components/Validator/Rules/Max.php @@ -24,7 +24,7 @@ class Max extends Size * * @param string $key Clé du test. * @param int|float|string|array|UploadedFileInterface $value Valeur à tester. - * @param string $args Valeur de comparraison. + * @param mixed $args Valeur de comparraison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void @@ -33,6 +33,9 @@ protected function test(string $key, $value, $args, bool $not): void if ($this->hasErrors()) { return; } + if (!is_numeric($args) && !is_string($args)) { + throw new \TypeError('The arguments must be a string or numeric.'); + } $this->sizeMax($key, $length, $args, $not); } @@ -51,10 +54,10 @@ protected function messages(): array /** * Test si une valeur est plus grande que la valeur de comparaison. * - * @param string $key Clé du test. - * @param float|int $length Taille de la valeur. - * @param string $max Valeur de comparraison. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param float|int $length Taille de la valeur. + * @param numeric|string $max Valeur de comparraison. + * @param bool $not Inverse le test. * * @return void */ diff --git a/src/Components/Validator/Rules/MaxNumeric.php b/src/Components/Validator/Rules/MaxNumeric.php index f63b03e..92233c8 100644 --- a/src/Components/Validator/Rules/MaxNumeric.php +++ b/src/Components/Validator/Rules/MaxNumeric.php @@ -22,7 +22,7 @@ class MaxNumeric extends Max * * @param string $key Clé du test. * @param numeric $value Valeur à tester. - * @param string $args Valeur de comparraison. + * @param mixed $args Valeur de comparraison. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void @@ -31,6 +31,9 @@ protected function test(string $key, $value, $args, bool $not): void if ($this->hasErrors()) { return; } + if (!is_numeric($args)) { + throw new \TypeError('The comparison argument must be numeric.'); + } $this->sizeMax($key, $length, $args, $not); } } diff --git a/src/Components/Validator/Rules/Min.php b/src/Components/Validator/Rules/Min.php index cfce480..484cc3d 100644 --- a/src/Components/Validator/Rules/Min.php +++ b/src/Components/Validator/Rules/Min.php @@ -24,7 +24,7 @@ class Min extends Size * * @param string $key Clé du test. * @param int|float|string|array|UploadedFileInterface $value Valeur à tester. - * @param string $args Valeur de comparraison. + * @param mixed $args Valeur de comparraison. * @param bool $not Inverse le test. * * @throws \InvalidArgumentException La valeur min n'est pas numérique. @@ -35,6 +35,9 @@ protected function test(string $key, $value, $args, bool $not): void if ($this->hasErrors()) { return; } + if (!is_numeric($args) && !is_string($args)) { + throw new \TypeError('The arguments must be a string or numeric.'); + } $this->sizeMin($key, $length, $args, $not); } @@ -53,10 +56,10 @@ protected function messages(): array /** * Test si une valeur est plus petite que la valeur de comparaison. * - * @param string $key Clé du test. - * @param float|int $length Taille de la valeur. - * @param string $min Valeur de comparraison. - * @param bool $not Inverse le test + * @param string $key Clé du test. + * @param float|int $length Taille de la valeur. + * @param numeric|string $min Valeur de comparraison. + * @param bool $not Inverse le test * * @return void. */ diff --git a/src/Components/Validator/Rules/MinNumeric.php b/src/Components/Validator/Rules/MinNumeric.php index 18a2c87..0f49140 100644 --- a/src/Components/Validator/Rules/MinNumeric.php +++ b/src/Components/Validator/Rules/MinNumeric.php @@ -22,7 +22,7 @@ class MinNumeric extends Min * * @param string $key Clé du test. * @param numeric $value Valeur à tester. - * @param string $args Valeur de comparraison. + * @param mixed $args Valeur de comparraison. * @param bool $not Inverse le test. * * @throws \InvalidArgumentException La valeur min n'est pas numérique. @@ -33,6 +33,9 @@ protected function test(string $key, $value, $args, bool $not): void if ($this->hasErrors()) { return; } + if (!is_numeric($args)) { + throw new \TypeError('The arguments must be a numeric.'); + } $this->sizeMin($key, $length, $args, $not); } } diff --git a/src/Components/Validator/Rules/NullValue.php b/src/Components/Validator/Rules/NullValue.php index 574d1a3..68ecd4c 100644 --- a/src/Components/Validator/Rules/NullValue.php +++ b/src/Components/Validator/Rules/NullValue.php @@ -20,10 +20,10 @@ class NullValue extends \Soosyze\Components\Validator\Rule /** * Test si la valeur est égale à "1", "true", "on" et "yes". * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/NumericType.php b/src/Components/Validator/Rules/NumericType.php index 07ed867..fbb5f46 100644 --- a/src/Components/Validator/Rules/NumericType.php +++ b/src/Components/Validator/Rules/NumericType.php @@ -20,10 +20,10 @@ class NumericType extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est de type numeric. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Regex.php b/src/Components/Validator/Rules/Regex.php index ef3d3bf..889be27 100644 --- a/src/Components/Validator/Rules/Regex.php +++ b/src/Components/Validator/Rules/Regex.php @@ -22,11 +22,14 @@ class Regex extends \Soosyze\Components\Validator\Rule * * @param string $key Clé du test. * @param string $value Valeur à tester. - * @param string $args Expression régulière. + * @param mixed $args Expression régulière. * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { + if (!is_string($args)) { + throw new \TypeError('The argument must be a string.'); + } if (!preg_match($args, $value) && $not) { $this->addReturn($key, 'must', [ ':regex' => $args ]); } elseif (preg_match($args, $value) && !$not) { diff --git a/src/Components/Validator/Rules/Required.php b/src/Components/Validator/Rules/Required.php index 03c6e57..0a42ebb 100644 --- a/src/Components/Validator/Rules/Required.php +++ b/src/Components/Validator/Rules/Required.php @@ -41,10 +41,10 @@ public function setInputs(array $inputs): void /** * Test si une valeur est requise. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/RequiredWith.php b/src/Components/Validator/Rules/RequiredWith.php index 7de47b6..c3745e5 100644 --- a/src/Components/Validator/Rules/RequiredWith.php +++ b/src/Components/Validator/Rules/RequiredWith.php @@ -20,10 +20,10 @@ class RequiredWith extends Required /** * Test si une valeur est requise si un ensemble de champs est présent. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { @@ -44,6 +44,9 @@ protected function isOneValue(): bool if (empty($this->args)) { throw new \InvalidArgumentException('A field must be provided for the required with rule.'); } + if (!is_string($this->args)) { + throw new \TypeError('The argument must be a string.'); + } $fields = explode(',', $this->args); foreach ($fields as $field) { if (!isset($this->inputs[ $field ])) { diff --git a/src/Components/Validator/Rules/RequiredWithAll.php b/src/Components/Validator/Rules/RequiredWithAll.php index 13c5c77..00adaf2 100644 --- a/src/Components/Validator/Rules/RequiredWithAll.php +++ b/src/Components/Validator/Rules/RequiredWithAll.php @@ -20,10 +20,10 @@ class RequiredWithAll extends Required /** * Test si une valeur est requise si un ensemble de champs est présent. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { @@ -44,6 +44,9 @@ protected function isOneVoidValue(): bool if (empty($this->args)) { throw new \InvalidArgumentException('A field must be provided for the required with rule.'); } + if (!is_string($this->args)) { + throw new \TypeError('The argument must be a string.'); + } $fields = explode(',', $this->args); foreach ($fields as $field) { if (!isset($this->inputs[ $field ])) { diff --git a/src/Components/Validator/Rules/RequiredWithout.php b/src/Components/Validator/Rules/RequiredWithout.php index bdcc8f9..2f10bb0 100644 --- a/src/Components/Validator/Rules/RequiredWithout.php +++ b/src/Components/Validator/Rules/RequiredWithout.php @@ -20,10 +20,10 @@ class RequiredWithout extends Required /** * Test si une valeur est requise si un ensemble de champs n'est pas présent. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { @@ -44,6 +44,9 @@ protected function isOneVoidValue() if (empty($this->args)) { throw new \InvalidArgumentException('A field must be provided for the required with rule.'); } + if (!is_string($this->args)) { + throw new \TypeError('The argument must be a string.'); + } $fields = explode(',', $this->args); foreach ($fields as $field) { if (!isset($this->inputs[ $field ])) { diff --git a/src/Components/Validator/Rules/RequiredWithoutAll.php b/src/Components/Validator/Rules/RequiredWithoutAll.php index c9d9491..b494e32 100644 --- a/src/Components/Validator/Rules/RequiredWithoutAll.php +++ b/src/Components/Validator/Rules/RequiredWithoutAll.php @@ -20,10 +20,10 @@ class RequiredWithoutAll extends Required /** * Test si une valeur est requise si un ensemble de champs n'est pas présent. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { @@ -44,6 +44,9 @@ protected function isAllVoidValue(): bool if (empty($this->args)) { throw new \InvalidArgumentException('A field must be provided for the required with rule.'); } + if (!is_string($this->args)) { + throw new \TypeError('The argument must be a string.'); + } $fields = explode(',', $this->args); $errors = 0; foreach ($fields as $field) { diff --git a/src/Components/Validator/Rules/RessourceType.php b/src/Components/Validator/Rules/RessourceType.php index 47e1081..b210c6a 100644 --- a/src/Components/Validator/Rules/RessourceType.php +++ b/src/Components/Validator/Rules/RessourceType.php @@ -20,10 +20,10 @@ class RessourceType extends \Soosyze\Components\Validator\Rule /** * Test si la valeur est égale à "1", "true", "on" et "yes". * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Size.php b/src/Components/Validator/Rules/Size.php index 00d1a2c..2ef89c1 100644 --- a/src/Components/Validator/Rules/Size.php +++ b/src/Components/Validator/Rules/Size.php @@ -62,7 +62,7 @@ protected function getSize($value) $size = 0; if (is_int($value) || is_float($value)) { $size = $value; - } elseif (is_string($value) || method_exists($value, '__toString')) { + } elseif (is_string($value) || (is_object($value) && method_exists($value, '__toString'))) { $size = strlen((string) $value); } elseif (is_array($value)) { $size = count($value); diff --git a/src/Components/Validator/Rules/Slug.php b/src/Components/Validator/Rules/Slug.php index c337486..b4a84c7 100644 --- a/src/Components/Validator/Rules/Slug.php +++ b/src/Components/Validator/Rules/Slug.php @@ -20,10 +20,10 @@ class Slug extends Regex /** * Test si la valeur correspond à une chaine de caractères alpha numérique (underscore et tiret autorisé). * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/StringType.php b/src/Components/Validator/Rules/StringType.php index a24d6f1..f5a8a1f 100644 --- a/src/Components/Validator/Rules/StringType.php +++ b/src/Components/Validator/Rules/StringType.php @@ -20,10 +20,10 @@ class StringType extends \Soosyze\Components\Validator\Rule /** * Test si la valeur est une chaine de caractères. * - * @param string $key Clé du test. - * @param mixed $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param mixed $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Timezone.php b/src/Components/Validator/Rules/Timezone.php index 4cbd17a..78c39b9 100644 --- a/src/Components/Validator/Rules/Timezone.php +++ b/src/Components/Validator/Rules/Timezone.php @@ -20,10 +20,10 @@ class Timezone extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est une URL. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Token.php b/src/Components/Validator/Rules/Token.php index 9cebd0c..c375a1c 100644 --- a/src/Components/Validator/Rules/Token.php +++ b/src/Components/Validator/Rules/Token.php @@ -23,7 +23,7 @@ class Token extends Size * * @param string $key Clé du test. * @param string $value Valeur à tester. - * @param string $args Nombre de seconde ou le token est valide (défaut 15 minutes), + * @param mixed $args Nombre de seconde ou le token est valide (défaut 15 minutes), * si la valeur du time = 0 alors le test du temps de validation n'est pas effectif. * @param bool $not Inverse le test. * @@ -38,11 +38,11 @@ protected function test(string $key, $value, $args, bool $not): void ]); } - if (empty($args)) { - $args = 900; - } - $intervale = $this->getComparator($args); - $name = $this->getKey(); + $intervale = is_numeric($args) + ? $this->getComparator($args) + : 900; + + $name = $this->getKey(); if (!isset($_SESSION[ 'token' ][ $name ]) && !isset($_SESSION[ 'token_time' ][ $name ])) { $this->addReturn($key, 'error'); diff --git a/src/Components/Validator/Rules/Url.php b/src/Components/Validator/Rules/Url.php index c96a0a0..e72a0fd 100644 --- a/src/Components/Validator/Rules/Url.php +++ b/src/Components/Validator/Rules/Url.php @@ -20,10 +20,10 @@ class Url extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est une URL. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Uuid.php b/src/Components/Validator/Rules/Uuid.php index 480e2a2..e1a3fcd 100644 --- a/src/Components/Validator/Rules/Uuid.php +++ b/src/Components/Validator/Rules/Uuid.php @@ -22,10 +22,10 @@ class Uuid extends \Soosyze\Components\Validator\Rule /** * Test si la valeur est égale à "1", "true", "on" et "yes". * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Rules/Version.php b/src/Components/Validator/Rules/Version.php index 6b0be9f..4bf73fa 100644 --- a/src/Components/Validator/Rules/Version.php +++ b/src/Components/Validator/Rules/Version.php @@ -35,10 +35,10 @@ class Version extends \Soosyze\Components\Validator\Rule /** * Test si une valeur est une URL. * - * @param string $key Clé du test. - * @param string $value Valeur à tester. - * @param mixed|null $args Argument de test. - * @param bool $not Inverse le test. + * @param string $key Clé du test. + * @param string $value Valeur à tester. + * @param mixed $args Argument de test. + * @param bool $not Inverse le test. */ protected function test(string $key, $value, $args, bool $not): void { diff --git a/src/Components/Validator/Validator.php b/src/Components/Validator/Validator.php index a415f2d..c19e714 100644 --- a/src/Components/Validator/Validator.php +++ b/src/Components/Validator/Validator.php @@ -14,13 +14,17 @@ * Valide des valeurs à partir de tests chaînés. * * @author Mathieu NOËL + * + * @phpstan-type Error array> + * @phpstan-type Errors array */ class Validator { /** * Règles de validations. * - * @var array + * @var array + * @phpstan-var array */ protected $rules = []; @@ -99,7 +103,7 @@ class Validator /** * Champs à tester. * - * @var array[] + * @var array */ protected $inputs = []; @@ -270,7 +274,7 @@ public function setLabels(array $labels): self * * @return $this */ - public function addInput($key, $value): self + public function addInput(string $key, $value): self { $this->inputs[ $key ] = $value; @@ -335,6 +339,7 @@ public function addLabels(array $labels): self * @param string $key Nom du champ. * * @return array + * @phpstan-return Error */ public function getError(string $key): array { @@ -346,7 +351,8 @@ public function getError(string $key): array * * @codeCoverageIgnore getter * - * @return array>> + * @return array + * @phpstan-return Errors */ public function getErrors(): array { @@ -621,6 +627,7 @@ protected function getCorrectInput(string $key, array $inputs) * @param string $rule Règle compléte. * * @return array + * @phpstan-return array{string, string, bool} */ protected function getInfosRule(string $rule): array { @@ -629,7 +636,7 @@ protected function getInfosRule(string $rule): array $name = $exp[ 0 ][ 0 ] === '!' ? substr($exp[ 0 ], 1) : $exp[ 0 ]; - $arg = $exp[ 1 ] ?? null; + $arg = $exp[ 1 ] ?? ''; /* Si l'argument fait référence à un autre champ. */ if ($arg && $arg[ 0 ] === '@') { @@ -664,6 +671,7 @@ protected function parseRules(string $key, string $strRule): Rule )); } + /** @var Rule $class */ return (new $class)->hydrate($name, $key, $arg, $not); } diff --git a/src/Config.php b/src/Config.php index 1e7ce1a..6631804 100644 --- a/src/Config.php +++ b/src/Config.php @@ -30,7 +30,7 @@ class Config implements \ArrayAccess /** * Les données de la configurations. * - * @var mixed[] + * @var array> */ private $data = []; @@ -81,12 +81,10 @@ public function get(string $strKey, $default = null) $this->loadConfig($file); if ($key) { - return $this->data[ $file ][ $key ] - ?? $default; + return $this->data[ $file ][ $key ] ?? $default; } - return $this->data[ $file ] - ?? $default; + return $this->data[ $file ] ?? $default; } /** @@ -96,7 +94,6 @@ public function get(string $strKey, $default = null) * @param mixed $value Valeur à stocker. * * @throws \InvalidArgumentException La clé est invalide, elle doit être composée de 2 parties séparées par un point. - * * @return $this */ public function set(string $strKey, $value): self @@ -126,7 +123,6 @@ public function set(string $strKey, $value): self * @param string $strKey "nom_fichier.nom_clé". * * @throws \InvalidArgumentException - * * @return $this */ public function del(string $strKey): self @@ -172,6 +168,12 @@ public function getPath(): string */ public function offsetExists($offset): bool { + if (!is_string($offset)) { + throw new \InvalidArgumentException( + sprintf('The key of must be of type string: %s given', gettype($offset)) + ); + } + return $this->has($offset); } @@ -186,6 +188,12 @@ public function offsetExists($offset): bool */ public function offsetGet($offset) { + if (!is_string($offset)) { + throw new \InvalidArgumentException( + sprintf('The key of must be of type string: %s given', gettype($offset)) + ); + } + return $this->get($offset); } @@ -201,6 +209,11 @@ public function offsetGet($offset) */ public function offsetSet($offset, $value): void { + if (!is_string($offset)) { + throw new \InvalidArgumentException( + sprintf('The key of must be of type string: %s given', gettype($offset)) + ); + } $this->set($offset, $value); } @@ -215,6 +228,11 @@ public function offsetSet($offset, $value): void */ public function offsetUnset($offset): void { + if (!is_string($offset)) { + throw new \InvalidArgumentException( + sprintf('The key of must be of type string: %s given', gettype($offset)) + ); + } $this->del($offset); } @@ -224,12 +242,13 @@ public function offsetUnset($offset): void * @param string $strKey Nom de la clé. * * @return array + * @phpstan-return array{string, string|null} */ protected function prepareKey(string $strKey): array { $file = strstr($strKey, '.'); if ($file !== false) { - return [ strstr($strKey, '.', true), trim($file, '.') ]; + return [ trim($strKey, $file . '.'), trim($file, '.') ]; } return [ $strKey, null ]; @@ -251,6 +270,7 @@ protected function loadConfig(string $nameConfig): void $file = $this->path . $nameConfig . '.json'; if (file_exists($file)) { + /** @phpstan-ignore-next-line */ $this->data[ $nameConfig ] = Util::getJson($file); } } diff --git a/src/Container.php b/src/Container.php index dd234db..090985b 100644 --- a/src/Container.php +++ b/src/Container.php @@ -240,9 +240,11 @@ public function callHook(string $name, array $args = []) return $out; } foreach ($this->hooks[ $key ] as $services => $func) { - $out = \is_string($func) - ? call_user_func_array([ $this->get($services), $func ], $args) - : call_user_func_array($func, $args); + if (\is_string($func)) { + $out = $this->get($services)->$func(...$args); + } else { + $out = call_user_func_array($func, $args); + } } return $out; diff --git a/src/Controller.php b/src/Controller.php index 45a949e..7b4b9ac 100644 --- a/src/Controller.php +++ b/src/Controller.php @@ -73,7 +73,7 @@ class Controller * @param string $key Nom du service. * @param array $args Paramètres passés à la fonction. * - * @return object + * @return mixed */ public function __call(string $key, array $args) { @@ -87,9 +87,9 @@ public function __call(string $key, array $args) * * @param string $key Nom du service. * - * @return object Service dans le container. + * @return mixed Service dans le container. */ - public function get(string $key): object + public function get(string $key) { return $this->container->get($key); } diff --git a/tests/AppTest.php b/tests/AppTest.php index 20612b0..2e6a6ae 100644 --- a/tests/AppTest.php +++ b/tests/AppTest.php @@ -3,6 +3,7 @@ namespace Soosyze\Tests; use Psr\Http\Message\RequestInterface; +use Soosyze\App; use Soosyze\Components\Http\ServerRequest; use Soosyze\Components\Http\Uri; use Soosyze\Tests\Resources\App\AppCore; @@ -10,7 +11,7 @@ class AppTest extends \PHPUnit\Framework\TestCase { /** - * @var AppCore + * @var App */ protected static $object; diff --git a/tests/Components/Form/FormTest.php b/tests/Components/Form/FormTest.php index 3f3b9d2..3a89dc8 100644 --- a/tests/Components/Form/FormTest.php +++ b/tests/Components/Form/FormTest.php @@ -77,7 +77,7 @@ public function providerInput(): \Generator ]; } - public function testInputNumber() + public function testInputNumber(): void { $this->object->number('inputNumber', [ ':actions' => 1 ]); @@ -164,6 +164,7 @@ public function testInputException(): void { $this->expectException(\BadMethodCallException::class); $this->expectExceptionMessage('The error type field does not exist'); + /** @phpstan-ignore-next-line */ $this->object->error('inputTextarea', 'lorem ipsum'); } @@ -433,21 +434,25 @@ public function testBeforeGroup(): void public function testAfter(): void { $this->object + ->text('key_field_1') + ->text('key_field_2') ->text('1') - ->text('2') + ->text('key_field_4') ->after('1', function ($form) { $form->text('3'); }) - ->after('1', function ($form) { + ->after('key_field_4', function ($form) { $form->text('4'); }); $this->assertEquals( '
' . PHP_EOL . + '' . PHP_EOL . + '' . PHP_EOL . '' . PHP_EOL . - '' . PHP_EOL . '' . PHP_EOL . - '' . PHP_EOL . + '' . PHP_EOL . + '' . PHP_EOL . '
' . PHP_EOL, (string) $this->object ); diff --git a/tests/Components/Http/MessageTest.php b/tests/Components/Http/MessageTest.php index 5707240..4c16b17 100644 --- a/tests/Components/Http/MessageTest.php +++ b/tests/Components/Http/MessageTest.php @@ -26,6 +26,7 @@ public function testWithProtocolVersionValueException($version): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The specified protocol is invalid.'); + /** @phpstan-ignore-next-line */ $this->object->withProtocolVersion($version); } @@ -138,6 +139,7 @@ public function testWithHeaderInvalidArguments( ): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage($exceptionMessage); + /** @phpstan-ignore-next-line */ $this->object->withHeader($name, $value); } diff --git a/tests/Components/Http/RequestTest.php b/tests/Components/Http/RequestTest.php index 07ed66e..3d44bd5 100644 --- a/tests/Components/Http/RequestTest.php +++ b/tests/Components/Http/RequestTest.php @@ -44,6 +44,7 @@ public function testWithMethodException($method): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The method must be a string'); + /** @phpstan-ignore-next-line */ $this->object->withMethod($method); } diff --git a/tests/Components/Http/ResponseTest.php b/tests/Components/Http/ResponseTest.php index 932c19a..5cbef00 100644 --- a/tests/Components/Http/ResponseTest.php +++ b/tests/Components/Http/ResponseTest.php @@ -59,6 +59,7 @@ public function testWithStatus(): void public function testWithStatusInvalidArgumentException($code, $reasonPhrase): void { $this->expectException(\InvalidArgumentException::class); + /** @phpstan-ignore-next-line */ $this->object->withStatus($code, $reasonPhrase); } diff --git a/tests/Components/Http/ServerRequestTest.php b/tests/Components/Http/ServerRequestTest.php index 26c2fae..4c1df43 100644 --- a/tests/Components/Http/ServerRequestTest.php +++ b/tests/Components/Http/ServerRequestTest.php @@ -338,6 +338,7 @@ public function testParsedBodyException($data): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('First parameter to withParsedBody MUST be object, array or null.'); + /** @phpstan-ignore-next-line */ $this->object->withParsedBody($data); } diff --git a/tests/Components/Http/StreamTest.php b/tests/Components/Http/StreamTest.php index a762d05..161cec6 100644 --- a/tests/Components/Http/StreamTest.php +++ b/tests/Components/Http/StreamTest.php @@ -133,9 +133,11 @@ public function testEof(): void $this->assertFalse($body->eof()); /* Va lire caractère par caractère jusqu'a arriver à la fin de la chaine. */ + /** @phpstan-ignore-next-line */ while (!$body->eof()) { $body->read(1); } + /** @phpstan-ignore-next-line */ $this->assertTrue($body->eof()); } @@ -255,6 +257,7 @@ public function testReadStringLengthException(): void $body = new Stream('test'); $this->expectException(RuntimeException::class); + /** @phpstan-ignore-next-line */ $body->read('error'); } diff --git a/tests/Components/Http/UploadedFileRessourceTest.php b/tests/Components/Http/UploadedFileRessourceTest.php index eb68551..4bafedc 100644 --- a/tests/Components/Http/UploadedFileRessourceTest.php +++ b/tests/Components/Http/UploadedFileRessourceTest.php @@ -53,6 +53,7 @@ public function testMoveExceptionTarget(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Target is incorrect.'); + /** @phpstan-ignore-next-line */ $this->object->moveTo(1); } diff --git a/tests/Components/Http/UploadedFileTest.php b/tests/Components/Http/UploadedFileTest.php index e5b5129..9138387 100644 --- a/tests/Components/Http/UploadedFileTest.php +++ b/tests/Components/Http/UploadedFileTest.php @@ -96,6 +96,7 @@ public function testMoveExceptionMoved(): void public function testMoveExceptionTarget(): void { $this->expectException(\Exception::class); + /** @phpstan-ignore-next-line */ $this->object->moveTo(1); } diff --git a/tests/Components/Http/UriTest.php b/tests/Components/Http/UriTest.php index 3f2e6f7..f653d1f 100644 --- a/tests/Components/Http/UriTest.php +++ b/tests/Components/Http/UriTest.php @@ -61,6 +61,7 @@ public function testScheme(): void public function testWithSchemeInvalidArgumentException($schema): void { $this->expectException(\InvalidArgumentException::class); + /** @phpstan-ignore-next-line */ $this->object->withScheme($schema); } @@ -112,6 +113,7 @@ public function testUserInfo(): void $this->assertEquals('foo', Uri::create('http://foo@bar.com/')->getUserInfo()); $this->assertEquals('', $this->object->withUserInfo('')->getUserInfo()); + /** @phpstan-ignore-next-line */ $this->assertEquals('', $this->object->withUserInfo(null)->getUserInfo()); $this->assertEquals('user:foo', $this->object->withUserInfo('user', 'foo')->getUserInfo()); $this->assertEquals('foo', $this->object->withUserInfo('foo')->getUserInfo()); @@ -143,6 +145,7 @@ public function testWithPortException(): void $uri = new Uri(); $this->expectException(\Exception::class); + /** @phpstan-ignore-next-line */ $uri->withPort('error'); } @@ -170,6 +173,7 @@ public function testWithUserInfoException(): void $uri = new Uri(); $this->expectException(\Exception::class); + /** @phpstan-ignore-next-line */ $uri->withUserInfo(1); } @@ -185,6 +189,7 @@ public function testWithHostException(): void $uri = new Uri(); $this->expectException(\Exception::class); + /** @phpstan-ignore-next-line */ $uri->withHost(1); } @@ -200,6 +205,7 @@ public function testWithPathException(): void $uri = new Uri(); $this->expectException(\Exception::class); + /** @phpstan-ignore-next-line */ $uri->withPath(1); } @@ -215,6 +221,7 @@ public function testWithQueryException(): void $uri = new Uri(); $this->expectException(\Exception::class); + /** @phpstan-ignore-next-line */ $uri->withQuery(1); } diff --git a/tests/Components/Paginate/PaginatorTest.php b/tests/Components/Paginate/PaginatorTest.php index 2dfffe5..64c30ea 100644 --- a/tests/Components/Paginate/PaginatorTest.php +++ b/tests/Components/Paginate/PaginatorTest.php @@ -88,11 +88,10 @@ public function testSetMaxPage(): void /** * @dataProvider providerSetMaxPageException * - * @param mixed $max * @param class-string<\Throwable> $exceptionClass */ public function testSetMaxPageException( - $max, + int $max, string $exceptionClass, string $exceptionMessage ): void { @@ -105,11 +104,6 @@ public function testSetMaxPageException( public function providerSetMaxPageException(): \Generator { - yield [ - 'error', - \InvalidArgumentException::class, - 'The number of pages to display must be greater than or equal to three.' - ]; yield [ 2, \InvalidArgumentException::class, diff --git a/tests/Components/Util/UtilTest.php b/tests/Components/Util/UtilTest.php index dc794d1..2bb86a7 100644 --- a/tests/Components/Util/UtilTest.php +++ b/tests/Components/Util/UtilTest.php @@ -3,6 +3,7 @@ namespace Soosyze\Tests\Components\Util; use Soosyze\Components\Util\Util; +use Soosyze\Tests\Traits\DateTime; require_once __DIR__ . '/../../Resources/Functions.php'; @@ -11,6 +12,8 @@ */ class UtilTest extends \PHPUnit\Framework\TestCase { + use DateTime; + private const PATH = 'tests/Components/Util/build'; private const FILE = 'file'; @@ -225,7 +228,7 @@ public function testGetOctetUploadLimit(): void */ public function testStrTimeDiffHumans(string $expectedHumansTime, string $date): void { - $data = Util::strHumansTimeDiff(date_create($date)); + $data = Util::strHumansTimeDiff(self::dateCreate($date)); $this->assertEquals($expectedHumansTime, sprintf($data[ 0 ], $data[ 1 ])); } diff --git a/tests/Components/Validator/Rules/FileSizeTest.php b/tests/Components/Validator/Rules/FileSizeTest.php index 572d074..23654a3 100644 --- a/tests/Components/Validator/Rules/FileSizeTest.php +++ b/tests/Components/Validator/Rules/FileSizeTest.php @@ -70,8 +70,8 @@ public function testMin(): void 'not_file_min' => $this->uplaod_img ])->setRules([ /* Text */ - 'file_min' => 'min:15', - 'not_file_min' => '!min:15' + 'file_min' => 'min:15B', + 'not_file_min' => '!min:15B' ]); $this->assertFalse($this->object->isValid()); diff --git a/tests/Components/Validator/Rules/TokenTest.php b/tests/Components/Validator/Rules/TokenTest.php index 43cdb3e..1b464ad 100644 --- a/tests/Components/Validator/Rules/TokenTest.php +++ b/tests/Components/Validator/Rules/TokenTest.php @@ -28,18 +28,6 @@ public function testToken(): void $this->assertTrue($this->object->isValid()); } - public function testTokenException(): void - { - $_SESSION[ 'token' ] = 'Lorem ipsum dolor sit amet'; - $_SESSION[ 'token_time' ] = time(); - - $this->expectException(\Exception::class); - $this->object - ->addInput('field', 'error') - ->addRule('field', 'token:error') - ->isValid(); - } - public function testTokenErrorSession(): void { @session_destroy(); diff --git a/tests/ContainerTest.php b/tests/ContainerTest.php index 73a6c84..b183f1c 100644 --- a/tests/ContainerTest.php +++ b/tests/ContainerTest.php @@ -108,6 +108,7 @@ public function testGet(): void $this->assertInstanceOf(Service1::class, $service1); $this->assertTrue($service1->isOk()); + /** @phpstan-ignore-next-line */ $service1snd = $this->object->service1(); $this->assertInstanceOf(Service1::class, $service1snd); $this->assertTrue($service1snd->isOk()); @@ -116,11 +117,10 @@ public function testGet(): void /** * @dataProvider providerGetException * - * @param mixed $key * @param class-string $exceptionClass */ public function testGetInvalidArgumentException( - $key, + string $key, string $exceptionClass, string $exceptionMessage ): void { diff --git a/tests/Resources/Container/Service2.php b/tests/Resources/Container/Service2.php index 41e2984..a90f46a 100644 --- a/tests/Resources/Container/Service2.php +++ b/tests/Resources/Container/Service2.php @@ -9,7 +9,7 @@ class Service2 */ protected $service1; - public function __construct(Service1 $service1, int $count = null) + public function __construct(Service1 $service1) { $this->service1 = $service1; } diff --git a/tests/Traits/DateTime.php b/tests/Traits/DateTime.php new file mode 100644 index 0000000..e5cc457 --- /dev/null +++ b/tests/Traits/DateTime.php @@ -0,0 +1,16 @@ +