From a377ab4b6160c1ed0cd35b91538c8ad2a7b6c394 Mon Sep 17 00:00:00 2001 From: Clemens Schwaighofer Date: Wed, 14 Feb 2024 12:26:17 +0900 Subject: [PATCH] Strip multiple slashes in CoreLibs Convert Strings --- .../Convert/CoreLibsConvertStringsTest.php | 74 +++++++++++++++++++ www/lib/CoreLibs/Convert/Strings.php | 16 ++++ 2 files changed, 90 insertions(+) diff --git a/4dev/tests/Convert/CoreLibsConvertStringsTest.php b/4dev/tests/Convert/CoreLibsConvertStringsTest.php index 90415d20..0b2f79a5 100644 --- a/4dev/tests/Convert/CoreLibsConvertStringsTest.php +++ b/4dev/tests/Convert/CoreLibsConvertStringsTest.php @@ -256,6 +256,80 @@ final class CoreLibsConvertStringsTest extends TestCase $output ); } + + /** + * provider for testStripMultiplePathSlashes + * + * @return array + */ + public function stripMultiplePathSlashesProvider(): array + { + return [ + 'no slahses' => [ + 'input' => 'string_abc', + 'expected' => 'string_abc', + ], + 'one slash' => [ + 'input' => 'some/foo', + 'expected' => 'some/foo', + ], + 'two slashes' => [ + 'input' => 'some//foo', + 'expected' => 'some/foo', + ], + 'three slashes' => [ + 'input' => 'some///foo', + 'expected' => 'some/foo', + ], + 'slashes in front' => [ + 'input' => '/foo', + 'expected' => '/foo', + ], + 'two slashes in front' => [ + 'input' => '//foo', + 'expected' => '/foo', + ], + 'thee slashes in front' => [ + 'input' => '///foo', + 'expected' => '/foo', + ], + 'slashes in back' => [ + 'input' => 'foo/', + 'expected' => 'foo/', + ], + 'two slashes in back' => [ + 'input' => 'foo//', + 'expected' => 'foo/', + ], + 'thee slashes in back' => [ + 'input' => 'foo///', + 'expected' => 'foo/', + ], + 'multiple slashes' => [ + 'input' => '/foo//bar///string/end_times', + 'expected' => '/foo/bar/string/end_times', + ] + ]; + } + + /** + * test multiple slashes clean up + * + * @covers ::stripMultiplePathSlashes + * @dataProvider stripMultiplePathSlashesProvider + * @testdox stripMultiplePathSlashes $input will be $expected [$_dataName] + * + * @param string $input + * @param string $expected + * @return void + */ + public function testStripMultiplePathSlashes(string $input, string $expected): void + { + $this->assertEquals( + $expected, + \CoreLibs\Convert\Strings::stripMultiplePathSlashes($input) + ); + } } // __END__ diff --git a/www/lib/CoreLibs/Convert/Strings.php b/www/lib/CoreLibs/Convert/Strings.php index bcbaf058..53d6bba7 100644 --- a/www/lib/CoreLibs/Convert/Strings.php +++ b/www/lib/CoreLibs/Convert/Strings.php @@ -118,6 +118,22 @@ class Strings return $value; } } + + /** + * Strip any duplicated slahes from a path + * eg: //foo///bar/foo.inc -> /foo/bar/foo.inc + * + * @param string $path Path to strip slashes from + * @return string Clean path + */ + public static function stripMultiplePathSlashes(string $path): string + { + return preg_replace( + '#/+#', + '/', + $path + ); + } } // __END__