Skip to content

Commit d35cf94

Browse files
authored
Merge pull request lkwdwrd#4 from johnpbloch/normalize-paths
Normalize paths
2 parents e17c0b9 + 2bdaefb commit d35cf94

2 files changed

Lines changed: 44 additions & 7 deletions

File tree

src/lkwdwrd/util/util.php

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@
2323
*/
2424
function rel_path( $from, $to, $ps = PS ) {
2525
// Turn paths into array.
26-
$arFrom = explode($ps, rtrim( $from, $ps ) );
27-
$arTo = explode( $ps, rtrim( $to, $ps ) );
26+
$arFrom = explode($ps, rtrim( normalize( $from, $ps ), $ps ) );
27+
$arTo = explode( $ps, rtrim( normalize( $to, $ps ), $ps ) );
2828
// Strip the common roots from both arrays.
2929
while( count( $arFrom ) && count( $arTo ) && ( $arFrom[0] == $arTo[0] ) ) {
3030
array_shift( $arFrom );
@@ -34,3 +34,14 @@ function rel_path( $from, $to, $ps = PS ) {
3434
// to items.
3535
return str_pad( '', count( $arFrom ) * 3, '..' . $ps ) . implode( $ps, $arTo );
3636
}
37+
38+
/**
39+
* Convert all different directory separators into one unified style
40+
*
41+
* @param string $path The path to normalize
42+
* @param string $ds The directory separator to standardize on
43+
* @return string The normalized path
44+
*/
45+
function normalize( $path, $ds ) {
46+
return str_replace( array( '/', "\\" ), $ds, $path );
47+
}

tests/phpunit/util_Tests.php

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,38 @@ public function setUp() {
2828

2929
/**
3030
* Make sure the rel_path function makes relative paths.
31+
* @dataProvider data_rel_path
3132
*/
32-
public function test_rel_path() {
33-
$abspath1 = '/a/random/path/to/a/place';
34-
$abspath2 = '/a/random/path/to/another/place';
33+
public function test_rel_path( $path1, $path2, $sep, $expected) {
34+
$this->assertEquals( Util\rel_path( $path1, $path2, $sep ), $expected );
35+
}
3536

36-
$calculatedRel = Util\rel_path( $abspath1, $abspath2, '/' );
37-
$this->assertEquals( $calculatedRel, '../../another/place' );
37+
public function data_rel_path(){
38+
return array(
39+
array(
40+
'/a/random/path/to/a/place',
41+
'/a/random/path/to/another/place',
42+
'/',
43+
'../../another/place',
44+
),
45+
array(
46+
'/somewhere/over/the/rainbow',
47+
'/somewhere/over/the/rainbow/bluebirds/sing',
48+
'/',
49+
'bluebirds/sing',
50+
),
51+
array(
52+
'/just/some/test',
53+
'/just\some\mixed\slash\example',
54+
'/',
55+
'../mixed/slash/example',
56+
),
57+
array(
58+
'/testing/inverse/directory/separators',
59+
'/unix/to/windows',
60+
'\\',
61+
'..\..\..\..\unix\to\windows',
62+
),
63+
);
3864
}
3965
}

0 commit comments

Comments
 (0)