From aed91d0ede62e0c60d910683827c47bcfc598f29 Mon Sep 17 00:00:00 2001 From: Rias Date: Thu, 19 May 2022 10:49:54 +0200 Subject: [PATCH] Add custom startsWith again --- src/Helpers/ActiveUrlChecker.php | 4 ++-- src/Helpers/Str.php | 11 ++++++++++- tests/NavigationTest.php | 2 +- tests/StrTest.php | 9 +++++++++ 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/Helpers/ActiveUrlChecker.php b/src/Helpers/ActiveUrlChecker.php index 92bea4a..5b69842 100644 --- a/src/Helpers/ActiveUrlChecker.php +++ b/src/Helpers/ActiveUrlChecker.php @@ -36,7 +36,7 @@ public function check(string $url): bool $itemPath = Str::ensureRight('/', $url->getPath()); // If this url doesn't start with the rootPath, it's inactive. - if (! str_starts_with($itemPath, $rootPath)) { + if (! Str::startsWith($itemPath, $rootPath)) { return false; } @@ -48,7 +48,7 @@ public function check(string $url): bool $matchPath = Str::removeFromStart($rootPath, $matchPath); // If this url starts with the url we're matching with, it's active. - if ($matchPath === $itemPath || str_starts_with($matchPath, $itemPath)) { + if ($matchPath === $itemPath || Str::startsWith($matchPath, $itemPath)) { return true; } diff --git a/src/Helpers/Str.php b/src/Helpers/Str.php index 656e75d..cd9f302 100644 --- a/src/Helpers/Str.php +++ b/src/Helpers/Str.php @@ -4,9 +4,18 @@ class Str { + public static function startsWith(string $haystack, string $needle): bool + { + if ($needle != '' && substr($haystack, 0, strlen($needle)) === $needle) { + return true; + } + + return false; + } + public static function removeFromStart(string $remove, string $subject): string { - if (! str_starts_with($subject, $remove)) { + if (! self::startsWith($subject, $remove)) { return $subject; } diff --git a/tests/NavigationTest.php b/tests/NavigationTest.php index d3d64c7..375303f 100644 --- a/tests/NavigationTest.php +++ b/tests/NavigationTest.php @@ -39,7 +39,7 @@ public function test_it_can_get_the_active_section() public function test_it_returns_null_when_there_is_no_active_section() { - $activeSection = (new Navigation($this->activeUrlChecker))->add('Home', 'home')->activeSection(); + $activeSection = (new Navigation($this->activeUrlChecker))->add('Home', '/')->activeSection(); $this->assertNull($activeSection); } diff --git a/tests/StrTest.php b/tests/StrTest.php index dd87e14..3fcab98 100644 --- a/tests/StrTest.php +++ b/tests/StrTest.php @@ -7,6 +7,15 @@ class StrTest extends TestCase { + /** @test * */ + public function it_can_check_if_string_starts_with() + { + $this->assertTrue(Str::startsWith('startEnd', 'start')); + $this->assertFalse(Str::startsWith('startEnd', 'end')); + $this->assertFalse(Str::startsWith('/', '/foo')); + $this->assertTrue(Str::startsWith('/foo', '/')); + } + /** @test * */ public function it_can_remove_from_start() {