From 8d77b6be3a01b3962ba65892c6ff34ac19a47c20 Mon Sep 17 00:00:00 2001 From: Samuel Nitsche Date: Tue, 16 Nov 2021 22:30:18 +0100 Subject: [PATCH 1/2] Fix creating urls from invalid strings --- src/Url.php | 4 +++- tests/UrlParseTest.php | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Url.php b/src/Url.php index 3cb3f9c..bd9ed0c 100644 --- a/src/Url.php +++ b/src/Url.php @@ -40,7 +40,9 @@ public static function create(): static public static function fromString(string $url): static { - $parts = array_merge(parse_url($url)); + if (! $parts = parse_url($url)) { + throw new InvalidArgument("Unable to parse string [{$url}]"); + } $url = new static(); $url->scheme = isset($parts['scheme']) ? $url->sanitizeScheme($parts['scheme']) : ''; diff --git a/tests/UrlParseTest.php b/tests/UrlParseTest.php index 384b652..5c60f85 100644 --- a/tests/UrlParseTest.php +++ b/tests/UrlParseTest.php @@ -49,6 +49,14 @@ public function it_throws_an_exception_if_an_invalid_scheme_is_provided() Url::fromString('htps://spatie.be'); } + /** @test */ + public function it_throws_an_exception_if_a_totally_invalid_url_is_provided() + { + $this->expectException(InvalidArgument::class); + + Url::fromString('///remote/fgt_lang?lang=/../../../..//////////dev/'); + } + /** @test */ public function it_can_parse_a_host() { From 03c35bdb047fa3a9467910fc98de84c054b38307 Mon Sep 17 00:00:00 2001 From: Samuel Nitsche Date: Tue, 16 Nov 2021 22:46:28 +0100 Subject: [PATCH 2/2] Extract method --- src/Exceptions/InvalidArgument.php | 5 +++++ src/Url.php | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Exceptions/InvalidArgument.php b/src/Exceptions/InvalidArgument.php index 80ed2c6..40929b1 100644 --- a/src/Exceptions/InvalidArgument.php +++ b/src/Exceptions/InvalidArgument.php @@ -11,6 +11,11 @@ public static function invalidScheme(string $url): static return new static("The scheme `{$url}` isn't valid. It should be either `http` or `https`."); } + public static function invalidUrl(string $url): static + { + return new static("The string `{$url}` is no valid url."); + } + public static function segmentZeroDoesNotExist(): static { return new static("Segment 0 doesn't exist. Segments can be retrieved by using 1-based index or a negative index."); diff --git a/src/Url.php b/src/Url.php index bd9ed0c..a332e55 100644 --- a/src/Url.php +++ b/src/Url.php @@ -41,7 +41,7 @@ public static function create(): static public static function fromString(string $url): static { if (! $parts = parse_url($url)) { - throw new InvalidArgument("Unable to parse string [{$url}]"); + throw InvalidArgument::invalidUrl($url); } $url = new static();