Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit da0b520

Browse files
committed
bug #22133 [Filesystem] normalize paths before making them relative (xabbuh)
This PR was merged into the 2.7 branch. Discussion ---------- [Filesystem] normalize paths before making them relative | Q | A | ------------- | --- | Branch? | 2.7 | Bug fix? | yes | New feature? | no | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | #22083 | License | MIT | Doc PR | Commits ------- d50ffa1 normalize paths before making them relative
2 parents be3d2d2 + d50ffa1 commit da0b520

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/Symfony/Component/Filesystem/Filesystem.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,31 @@ public function makePathRelative($endPath, $startPath)
362362
$startPathArr = explode('/', trim($startPath, '/'));
363363
$endPathArr = explode('/', trim($endPath, '/'));
364364

365+
if ('/' !== $startPath[0]) {
366+
array_shift($startPathArr);
367+
}
368+
369+
if ('/' !== $endPath[0]) {
370+
array_shift($endPathArr);
371+
}
372+
373+
$normalizePathArray = function ($pathSegments) {
374+
$result = array();
375+
376+
foreach ($pathSegments as $segment) {
377+
if ('..' === $segment) {
378+
array_pop($result);
379+
} else {
380+
$result[] = $segment;
381+
}
382+
}
383+
384+
return $result;
385+
};
386+
387+
$startPathArr = $normalizePathArray($startPathArr);
388+
$endPathArr = $normalizePathArray($endPathArr);
389+
365390
// Find for which directory the common path stops
366391
$index = 0;
367392
while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {

src/Symfony/Component/Filesystem/Tests/FilesystemTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,16 @@ public function providePathsForMakePathRelative()
868868
array('/a/aab/bb/', '/b/aab', '../../a/aab/bb/'),
869869
array('/aab/bb', '/aa', '../aab/bb/'),
870870
array('/aab', '/aa', '../aab/'),
871+
array('/aa/bb/cc', '/aa/dd/..', 'bb/cc/'),
872+
array('/aa/../bb/cc', '/aa/dd/..', '../bb/cc/'),
873+
array('/aa/bb/../../cc', '/aa/../dd/..', 'cc/'),
874+
array('/../aa/bb/cc', '/aa/dd/..', 'bb/cc/'),
875+
array('/../../aa/../bb/cc', '/aa/dd/..', '../bb/cc/'),
876+
array('C:/aa/bb/cc', 'C:/aa/dd/..', 'bb/cc/'),
877+
array('c:/aa/../bb/cc', 'c:/aa/dd/..', '../bb/cc/'),
878+
array('C:/aa/bb/../../cc', 'C:/aa/../dd/..', 'cc/'),
879+
array('C:/../aa/bb/cc', 'C:/aa/dd/..', 'bb/cc/'),
880+
array('C:/../../aa/../bb/cc', 'C:/aa/dd/..', '../bb/cc/'),
871881
);
872882

873883
if ('\\' === DIRECTORY_SEPARATOR) {

0 commit comments

Comments
 (0)