diff --git a/.gitignore b/.gitignore index f629cd8..2cb622c 100755 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ ._* .DS_Store .sass-cache -vendor \ No newline at end of file +composer.lock +vendor +.idea/ \ No newline at end of file diff --git a/Client.php b/Client.php index b5267af..f767283 100755 --- a/Client.php +++ b/Client.php @@ -126,7 +126,7 @@ protected function prepareRequest(RequestInterface $request): void $this->setOption(CURLOPT_RETURNTRANSFER, true); // Default auth option if get user name - if (!$this->hasOption(CURLOPT_HTTPAUTH) && !is_null($request->getUri()->getPart("user"))) { + if (!$this->hasOption(CURLOPT_HTTPAUTH) && $request->getUri()->getPart("user") !== null) { $this->setOption(CURLOPT_HTTPAUTH, static::DEFAULT_AUTH); } diff --git a/Dir.php b/Dir.php index 9fd5d69..21c51c4 100755 --- a/Dir.php +++ b/Dir.php @@ -57,7 +57,7 @@ public function getRoot(string $path = ""): string */ public function getLogs(string $path = ""): string { - if(!is_null($this->handler)) { + if ($this->handler !== null) { return $this->handler->getLogs($path); } return $this->getRoot("storage/logs/" . $path); @@ -72,7 +72,7 @@ public function getLogs(string $path = ""): string */ public function __call($method, $args): mixed { - if (!is_null($this->handler) && method_exists($this->handler, $method)) { + if ($this->handler !== null && method_exists($this->handler, $method)) { return call_user_func_array([$this->handler, $method], $args); } else { throw new \BadMethodCallException("The method ({$method}) does not exist in \"".__CLASS__."\" (DirInterface or DirHandlerInterface).", 1); diff --git a/Env.php b/Env.php index 9e4ac0a..133c13e 100755 --- a/Env.php +++ b/Env.php @@ -16,7 +16,7 @@ class Env public function __construct(?string $file = null) { - if (!is_null($file) && is_file($file)) { + if ($file !== null && is_file($file)) { $this->loadEnvFile($file); } } diff --git a/Environment.php b/Environment.php index 31e8337..14dab37 100755 --- a/Environment.php +++ b/Environment.php @@ -75,7 +75,7 @@ public function getUriParts(array $add = []): array */ public function getPath(): string { - if (is_null($this->path)) { + if ($this->path === null) { $basePath = ''; $requestName = Format\Str::value($this->get("SCRIPT_NAME"))->getUrlPath()->get(); $requestDir = dirname($requestName); diff --git a/Headers.php b/Headers.php index ed95553..fdf09af 100755 --- a/Headers.php +++ b/Headers.php @@ -106,7 +106,7 @@ public function normalizeKey(string $key, bool $preserveCase = false): string */ final public static function getGlobalHeaders($skip = false): array { - //if(is_null(static::$getGlobalHeaders)) { + //if(static::$getGlobalHeaders === null) { if (!$skip && function_exists("getallheaders")) { static::$getGlobalHeaders = getallheaders(); } else { diff --git a/Interfaces/DirHandlerInterface.php b/Interfaces/DirHandlerInterface.php index 09a43af..148eaaa 100755 --- a/Interfaces/DirHandlerInterface.php +++ b/Interfaces/DirHandlerInterface.php @@ -1,4 +1,5 @@ version)) { + if ($this->version === null) { $prot = explode("/", ($this->env['SERVER_PROTOCOL'] ?? "HTTP/1.1")); $this->version = end($prot); } @@ -72,7 +72,7 @@ public function getHeader($name): array */ public function hasHeader($name): bool { - if (is_null($this->headers)) { + if ($this->headers === null) { throw new RequestException("Missing The HTTP Headers instance", 1); } return $this->headers->hasHeader($name); diff --git a/Request.php b/Request.php index 6e9e374..f002230 100755 --- a/Request.php +++ b/Request.php @@ -27,6 +27,9 @@ public function __construct( $this->uri = is_string($uri) ? new Uri($uri) : $uri; $this->headers = is_array($headers) ? new Headers($headers) : $headers; $this->body = $this->resolveRequestStream($body); + if ($this->env === null) { + $this->env = new Environment(); + } $this->setHostHeader(); } @@ -118,11 +121,11 @@ public function isSSL(): bool public function getPort(): int { $serverPort = $this->env->get("SERVER_PORT"); - return (int)(($serverPort) ? $serverPort : $this->uri->getPort()); + return (int)(((int)$serverPort > 0) ? $serverPort : $this->uri->getPort()); } /** - * Set host header if missing or overwrite if custom is set. + * Set the host header if missing or overwrite if custom is set. * @return void */ final protected function setHostHeader(): void @@ -146,7 +149,7 @@ private function resolveRequestStream(StreamInterface|array|string|null $body): $body = http_build_query($body); } $stream = new Stream(Stream::TEMP); - if (!is_null($body)) { + if ($body !== null) { $stream->write($body); $stream->rewind(); } @@ -160,7 +163,7 @@ private function resolveRequestStream(StreamInterface|array|string|null $body): */ public function getCliKeyword(): ?string { - if (is_null($this->cliKeywords)) { + if ($this->cliKeywords === null) { $new = []; $arg = $this->getUri()->getArgv(); foreach ($arg as $val) { @@ -185,7 +188,7 @@ public function getCliKeyword(): ?string */ public function getCliArgs(): array { - if (is_null($this->cliArgs)) { + if ($this->cliArgs === null) { $args = $this->getUri()->getArgv(); $this->cliArgs = []; foreach ($args as $arg) { diff --git a/Response.php b/Response.php index 976f510..d079dc5 100755 --- a/Response.php +++ b/Response.php @@ -88,12 +88,12 @@ public function __construct( ) { $this->body = $body; $this->statusCode = $status; - $this->headers = is_null($headers) ? new Headers() : $headers; - $this->body = $body; - if (!is_null($version)) { + $this->headers = $headers === null ? new Headers() : $headers; + //$this->body = $body; + if ($version !== null) { $this->version = $version; } - if (!is_null($phrase)) { + if ($phrase !== null) { $this->phrase = $phrase; } } @@ -116,7 +116,7 @@ public function withStatus(int $code, string $reasonPhrase = ''): ResponseInterf * Get current response status code * @return int */ - public function getStatusCode() + public function getStatusCode(): int { return $this->statusCode; } @@ -125,9 +125,9 @@ public function getStatusCode() * Get current response status phrase * @return string */ - public function getReasonPhrase() + public function getReasonPhrase(): string { - if (is_null($this->phrase)) { + if ($this->phrase === null) { $this->phrase = ($this::PHRASE[$this->statusCode] ?? ""); } return $this->phrase; @@ -230,7 +230,7 @@ public function location(string $url, int $statusCode = 302): void */ public function createHeaders(): void { - if (is_null($this->hasHeadersInit)) { + if ($this->hasHeadersInit === null) { $this->hasHeadersInit = true; foreach ($this->getHeaders() as $key => $_unusedVal) { $value = $this->getHeaderLine($key); diff --git a/ServerRequest.php b/ServerRequest.php index ef68bc4..6959536 100755 --- a/ServerRequest.php +++ b/ServerRequest.php @@ -101,7 +101,7 @@ public function withCookieParams(array $cookies): self */ public function getQueryParams(): array { - if (is_null($this->queryParams)) { + if ($this->queryParams === null) { parse_str($this->getUri()->getQuery(), $this->queryParams); } return $this->queryParams; @@ -188,7 +188,7 @@ public function withUploadedFiles(array $uploadedFiles): self */ public function getParsedBody(): null|array|object { - if (is_null($this->parsedBody) && $this->getMethod() === "POST") { + if ($this->parsedBody === null && $this->getMethod() === "POST") { $header = $this->getHeader('Content-Type'); $contents = (string)$this->getBody(); switch (($header[0] ?? null)) { diff --git a/Stream.php b/Stream.php index f6e0454..fc02ec1 100755 --- a/Stream.php +++ b/Stream.php @@ -35,12 +35,13 @@ class Stream implements StreamInterface /** * PSR-7 Stream - * @param mixed $stream - * @param string $permission Default stream permission is r+ + * + * @param mixed $stream + * @param string $permission The default stream permission is r+ */ public function __construct(mixed $stream = null, string $permission = "r+") { - if (is_null($stream)) { + if ($stream === null) { $stream = $this::DEFAULT_WRAPPER; } @@ -48,7 +49,7 @@ public function __construct(mixed $stream = null, string $permission = "r+") $this->resource = $stream; $this->meta = $this->getMetadata(); /* - if (is_null($this->meta)) { + if ($this->meta === null) { throw new RuntimeException("Could not access the stream metadata.", 1); } */ @@ -147,7 +148,7 @@ public function stats(?string $key = null): mixed { $stats = fstat($this->resource); if (is_array($stats)) { - return is_null($key) ? $stats : ($stats[$key] ?? false); + return $key === null ? $stats : ($stats[$key] ?? false); } return false; } @@ -241,7 +242,7 @@ public function rewind(): void */ public function write(string $string): int { - if (is_null($this->size)) { + if ($this->size === null) { $this->size = 0; } return fwrite($this->resource, $string); @@ -284,7 +285,7 @@ public function getMetadata(?string $key = null): mixed $this->readable = (bool)preg_match(self::READABLE_MATCH, $this->meta['mode']); $this->writable = (bool)preg_match(self::WRITABLE_MATCH, $this->meta['mode']); $this->seekable = $this->meta['seekable']; - return (!is_null($key) ? ($this->meta[$key] ?? null) : $this->meta); + return ($key !== null ? ($this->meta[$key] ?? null) : $this->meta); } /** diff --git a/UploadedFile.php b/UploadedFile.php index b1e813a..694e1e6 100755 --- a/UploadedFile.php +++ b/UploadedFile.php @@ -42,7 +42,7 @@ class UploadedFile implements UploadedFileInterface public function __construct(StreamInterface|array|string $stream, mixed ...$vars) { - if(count($vars) > 0 && is_string($stream)) { + if (count($vars) > 0 && is_string($stream)) { array_unshift($vars, $stream); $stream = array_combine(['name', 'type', 'tmp_name', 'error', 'size'], $vars); } @@ -68,7 +68,7 @@ public function __construct(StreamInterface|array|string $stream, mixed ...$vars */ public function getStream(): StreamInterface { - if (is_null($this->stream)) { + if ($this->stream === null) { throw new RuntimeException("The no stream exists. You need to construct a new stream", 1); } if (is_string($this->stream)) { @@ -91,9 +91,9 @@ public function moveTo($targetPath): void throw new RuntimeException('Target directory is not writable'); } - if (!is_null($this->stream)) { + if ($this->stream !== null) { $this->streamFile($targetPath); - } elseif (!is_null($this->tmp)) { + } elseif ($this->tmp !== null) { $this->moveUploadedFile($targetPath); } @@ -148,7 +148,7 @@ public function moveUploadedFile(string $targetPath) */ public function getSize(): ?int { - return (is_null($this->size)) ? (($this->stream instanceof StreamInterface) ? $this->stream->getSize() : null) : $this->size; + return ($this->size === null) ? (($this->stream instanceof StreamInterface) ? $this->stream->getSize() : null) : $this->size; } /** diff --git a/Uri.php b/Uri.php index b5f3306..e976d0c 100755 --- a/Uri.php +++ b/Uri.php @@ -25,14 +25,13 @@ class Uri implements UriInterface private $parts = []; private $scheme; - //private $uri; private $host; private $port; private $user; private $pass; private $path; private $query; - private $fragment; // Anchor/after hash + private $fragment; private $dir; private $rootDir; private $userInfo; @@ -41,7 +40,6 @@ class Uri implements UriInterface private $encoded; private $build; - /** * URI in parts * @param array|string $uri @@ -122,7 +120,7 @@ public function getRootDir(): string */ public function getAuthority(): string { - if (is_null($this->authority)) { + if ($this->authority === null) { $this->authority = ""; if (($host = $this->getHost()) && ($userInfo = $this->getUserInfo())) { @@ -143,7 +141,7 @@ public function getAuthority(): string */ public function getUserInfo(): string { - if (is_null($this->userInfo)) { + if ($this->userInfo === null) { $this->userInfo = ""; if ($user = $this->getUniquePart("user")) { $this->encoded['user'] = $user; @@ -154,7 +152,7 @@ public function getUserInfo(): string if (is_string($user) && !empty($user)) { $this->userInfo .= "{$user}"; - if (!is_null($pass)) { + if ($pass !== null) { $this->userInfo .= ":{$pass}"; } } @@ -169,7 +167,7 @@ public function getUserInfo(): string public function getHost(): string { if ($val = $this->getUniquePart("host")) { - if(($pos = strpos($val, ":")) !== false) { + if (($pos = strpos($val, ":")) !== false) { $val = substr($val, 0, $pos); } $this->encoded['host'] = Format\Str::value($val)->tolower()->get(); @@ -197,7 +195,7 @@ public function getPort(): ?int */ public function getDefaultPort(): ?int { - if (is_null($this->port) && !is_null($this->scheme)) { + if ($this->port === null && $this->scheme !== null) { $this->port = ($this::DEFAULT_PORTS[$this->getScheme()] ?? null); } if ($val = $this->getUniquePart("port")) { @@ -217,7 +215,7 @@ public function getPath(): string ->normalizeUrlEncoding() ->replace(['%2F'], ['/']) ->get(); - if($this->encoded['path']) { + if ($this->encoded['path']) { $this->encoded['path'] = "/".ltrim($this->encoded['path'], "/"); } } @@ -257,7 +255,7 @@ public function getFragment(): string */ public function getUri(): string { - if (is_null($this->build)) { + if ($this->build === null) { $this->build = ""; if ($scheme = $this->getScheme()) { $this->build .= "{$scheme}:"; @@ -393,7 +391,7 @@ public function withUriParts(array $parts): self */ private function getUniquePart(string $key): string|int|float|null { - return (!is_null($this->{$key}) && is_null($this->encoded[$key])) ? $this->{$key} : null; + return ($this->{$key} !== null && $this->encoded[$key] === null) ? $this->{$key} : null; } /** @@ -416,7 +414,7 @@ private function fillParts(): void foreach ($vars as $key => $_valueNotUsed) { $this->encoded[$key] = null; $part = ($this->parts[$key] ?? null); - if (!is_null($part)) { + if ($part !== null) { $this->{$key} = $part; } } diff --git a/Url.php b/Url.php index 9ccdedc..40f49ef 100755 --- a/Url.php +++ b/Url.php @@ -55,7 +55,7 @@ public function withType(null|string|array $type = null): self if (is_string($type)) { $type = [$type]; } - if (is_null($type)) { + if ($type === null) { $type = []; } @@ -111,7 +111,7 @@ public function add(array|string $arr): self if (is_string($arr)) { $arr = [$arr]; } - if (is_null($inst->vars)) { + if ($inst->vars === null) { $inst->vars = $inst->getVars(); } $inst->vars = array_merge($inst->vars, $arr); @@ -125,7 +125,7 @@ public function add(array|string $arr): self */ public function getVars(): array { - if (is_null($this->vars)) { + if ($this->vars === null) { $this->vars = explode("/", $this->realPath); } return $this->vars; @@ -146,7 +146,7 @@ public function getParts(): array */ public function getRealPath(): string { - if (is_null($this->realPath)) { + if ($this->realPath === null) { $this->realPath = str_replace(rtrim($this->getDirPath(), "/"), "", $this->uri->getPath()); } if (!is_string($this->realPath)) { @@ -161,7 +161,7 @@ public function getRealPath(): string */ public function getDirPath(): string { - if (is_null($this->dirPath)) { + if ($this->dirPath === null) { // Absolute path to the "httpdocs" directory (document root) $documentRoot = (isset($_SERVER['DOCUMENT_ROOT'])) ? $_SERVER['DOCUMENT_ROOT'] : ""; $documentRoot = htmlspecialchars($documentRoot, ENT_QUOTES, 'UTF-8'); @@ -183,7 +183,7 @@ public function getDirPath(): string public function getDirPathOLD(): string { - if (is_null($this->dirPath)) { + if ($this->dirPath === null) { $root = (isset($_SERVER['DOCUMENT_ROOT'])) ? $_SERVER['DOCUMENT_ROOT'] : ""; $root = htmlspecialchars($root, ENT_QUOTES, 'UTF-8'); $this->dirPath = str_replace($root, "", $this->request->getUri()->getDir()); @@ -225,7 +225,7 @@ public function current(): string */ public function last(): string { - if (is_null($this->vars)) { + if ($this->vars === null) { $this->vars = $this->getVars(); } return end($this->vars); @@ -237,7 +237,7 @@ public function last(): string */ public function first(): string { - if (is_null($this->vars)) { + if ($this->vars === null) { $this->vars = $this->getVars(); } return reset($this->vars); @@ -249,7 +249,7 @@ public function first(): string */ public function prev(): string { - if (is_null($this->vars)) { + if ($this->vars === null) { $this->end(); } return prev($this->vars); @@ -261,7 +261,7 @@ public function prev(): string */ public function next(): string { - if (is_null($this->vars)) { + if ($this->vars === null) { $this->reset(); } return next($this->vars); @@ -303,7 +303,7 @@ public function getRootDir(string $path = "", bool $endSlash = false): string public function getRoot(string $path = "", bool $endSlash = false): string { $url = $this->getRootDir("/"); - if (!is_null($this->handler)) { + if ($this->handler !== null) { $url .= $this->handler->getPublicDirPath(); } $url = rtrim($url, '/'); @@ -346,7 +346,7 @@ public function setHandler(UrlHandlerInterface $handler): void */ public function __call($method, $args): mixed { - if (!is_null($this->handler) && method_exists($this->handler, $method)) { + if ($this->handler !== null && method_exists($this->handler, $method)) { return call_user_func_array([$this->handler, $method], $args); } elseif (method_exists($this->uri, $method)) { return call_user_func_array([$this->uri, $method], $args); diff --git a/composer.json b/composer.json index 22f390c..998de67 100644 --- a/composer.json +++ b/composer.json @@ -39,5 +39,8 @@ "MaplePHP\\Http\\": "" } }, - "minimum-stability": "dev" + "minimum-stability": "dev", + "scripts": { + "unitary": "php vendor/bin/unitary" + } } diff --git a/tests/unitary-request.php b/tests/unitary-request.php index 1319ae2..4cdd841 100644 --- a/tests/unitary-request.php +++ b/tests/unitary-request.php @@ -1,31 +1,37 @@ case("MaplePHP Request URI path test", function() { - $request = new MaplePHP\Http\Request( +$unit->case("MaplePHP Request URI path test", function(TestCase $case) { + + $request = new Request( "POST", // The HTTP Method (GET, POST, PUT, DELETE, PATCH) "https://admin:mypass@example.com:65535/test.php?id=5221&place=stockholm", // The Request URI ["Content-Type" => "application/x-www-form-urlencoded"], // Add Headers, empty array is allowed ["email" => "john.doe@example.com"] // Post data ); - $this->add($request->getMethod(), function() { - return $this->equal("POST"); - - }, "HTTP Request method Type is not POST"); - // Adding an error message is not required, but it is highly recommended + $case + ->error("HTTP Request method is not POST") + ->validate($request->getMethod(), function(Expect $inst) { + $inst->isEqualTo("POST"); + //assert($inst->isEqualTo("GET")->isValid(), "wdqwwdqw dwq wqdwq"); + }); - $this->add($request->getUri()->getPort(), [ - "isInt" => [], // Has no arguments = empty array - "min" => [1], // Strict way is to pass each argument to array - "max" => 65535, // But if its only one argument then this it is acceptable - "length" => [1, 5] - - ], "Is not a valid port number"); + $case->validate($request->getUri()->getPort(), function(Expect $inst) { + $inst->isInt(); + $inst->min(1); + $inst->max(65535); + $inst->length(1, 5); + }); $this->add($request->getUri()->getUserInfo(), [ "isString" => [], @@ -36,7 +42,7 @@ ], "Is not a valid port number"); - $this->add((string)$request->withUri(new \MaplePHP\Http\Uri("https://example.se"))->getUri(), [ + $this->add((string)$request->withUri(new Uri("https://example.se"))->getUri(), [ "equal" => ["https://example.se"], ], "GetUri expects https://example.se as result"); }); \ No newline at end of file diff --git a/tests/unitaryRequest.php b/tests/unitaryRequest.php new file mode 100644 index 0000000..24b708c --- /dev/null +++ b/tests/unitaryRequest.php @@ -0,0 +1,52 @@ +case("MaplePHP Request URI path test", function(TestCase $inst) { + + $request = new Request( + "POST", // The HTTP Method (GET, POST, PUT, DELETE, PATCH) + "https://admin:mypass@example.com:65535/test.php?id=5221&place=stockholm", // The Request URI + ["Content-Type" => "application/x-www-form-urlencoded"], // Add Headers, empty array is allowed + ["email" => "john.doe@example.com"] // Post data + ); + + $inst->add($request->getMethod(), function() { + return $this->equal("GET"); + + }, "HTTP Request method Type is not POST"); + // Adding an error message is not required, but it is highly recommended + + $this->add($request->getUri()->getPort(), [ + "isInt" => [], // Has no arguments = empty array + "min" => [1], // Strict way is to pass each argument to array + "max" => 65535, // But if its only one argument then this it is acceptable + "length" => [1, 5] + + ], "Is not a valid port number"); + + $this->add($request->getUri()->getUserInfo(), [ + "isString" => [], + "User validation" => function($value) { + $arr = explode(":", $value); + return ($this->withValue($arr[0])->equal("admin") && $this->withValue($arr[1])->equal("mypass")); + } + + ], "Is not a valid port number"); + + $this->add((string)$request->withUri(new \MaplePHP\Http\Uri("https://example.se"))->getUri(), [ + "equal" => ["https://example.se"], + ], "GetUri expects https://example.se as result"); +}); \ No newline at end of file