Skip to content

Commit

Permalink
bug #22133 [Filesystem] normalize paths before making them relative (…
Browse files Browse the repository at this point in the history
…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
  • Loading branch information
fabpot committed Mar 24, 2017
2 parents be3d2d2 + d50ffa1 commit da0b520
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Symfony/Component/Filesystem/Filesystem.php
Expand Up @@ -362,6 +362,31 @@ public function makePathRelative($endPath, $startPath)
$startPathArr = explode('/', trim($startPath, '/'));
$endPathArr = explode('/', trim($endPath, '/'));

if ('/' !== $startPath[0]) {
array_shift($startPathArr);
}

if ('/' !== $endPath[0]) {
array_shift($endPathArr);
}

$normalizePathArray = function ($pathSegments) {
$result = array();

foreach ($pathSegments as $segment) {
if ('..' === $segment) {
array_pop($result);
} else {
$result[] = $segment;
}
}

return $result;
};

$startPathArr = $normalizePathArray($startPathArr);
$endPathArr = $normalizePathArray($endPathArr);

// Find for which directory the common path stops
$index = 0;
while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Component/Filesystem/Tests/FilesystemTest.php
Expand Up @@ -868,6 +868,16 @@ public function providePathsForMakePathRelative()
array('/a/aab/bb/', '/b/aab', '../../a/aab/bb/'),
array('/aab/bb', '/aa', '../aab/bb/'),
array('/aab', '/aa', '../aab/'),
array('/aa/bb/cc', '/aa/dd/..', 'bb/cc/'),
array('/aa/../bb/cc', '/aa/dd/..', '../bb/cc/'),
array('/aa/bb/../../cc', '/aa/../dd/..', 'cc/'),
array('/../aa/bb/cc', '/aa/dd/..', 'bb/cc/'),
array('/../../aa/../bb/cc', '/aa/dd/..', '../bb/cc/'),
array('C:/aa/bb/cc', 'C:/aa/dd/..', 'bb/cc/'),
array('c:/aa/../bb/cc', 'c:/aa/dd/..', '../bb/cc/'),
array('C:/aa/bb/../../cc', 'C:/aa/../dd/..', 'cc/'),
array('C:/../aa/bb/cc', 'C:/aa/dd/..', 'bb/cc/'),
array('C:/../../aa/../bb/cc', 'C:/aa/dd/..', '../bb/cc/'),
);

if ('\\' === DIRECTORY_SEPARATOR) {
Expand Down

0 comments on commit da0b520

Please sign in to comment.