Skip to content

Commit cdb41ce

Browse files
committed
Merge pull request #123 from phpcr/relative-path
Relativize path
2 parents a7acd0b + cdde76d commit cdb41ce

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/PHPCR/Util/PathHelper.php

+22
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,28 @@ public static function absolutizePath($path, $context, $destination = false, $th
196196
return self::normalizePath($path, $destination, $throw);
197197
}
198198

199+
/**
200+
* Make an absolute path relative to $context.
201+
*
202+
* ie. $context . '/' . PathHelper::relativePath($path, $context) === $path
203+
*
204+
* Input paths are assumed to be normalized.
205+
*
206+
* @param string $path The absolute path to a node
207+
* @param string $context The absolute path to an ancestor of $path
208+
* @param bool $throw Whether to throw exceptions on invalid data.
209+
*
210+
* @return string The relative path from $context to $path
211+
*/
212+
public static function relativizePath($path, $context, $throw = true)
213+
{
214+
if ($context !== substr($path, 0, strlen($context))) {
215+
return self::error("$path is not within $context", $throw);
216+
}
217+
218+
return ltrim(substr($path, strlen($context)), '/');
219+
}
220+
199221
/**
200222
* Get the parent path of a valid absolute path.
201223
*

tests/PHPCR/Tests/Util/PathHelperTest.php

+43
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,49 @@ public static function dataproviderAbsolutizePathInvalid()
186186
);
187187
}
188188

189+
// relativizePath tests
190+
191+
/**
192+
* @dataProvider dataproviderRelativizePath
193+
*/
194+
public function testRelativizePath($inputPath, $context, $outputPath)
195+
{
196+
$this->assertSame($outputPath, PathHelper::relativizePath($inputPath, $context));
197+
}
198+
199+
public static function dataproviderRelativizePath()
200+
{
201+
return array(
202+
array('/parent/path/child', '/parent', 'path/child'),
203+
array('/child', '/', 'child'),
204+
);
205+
}
206+
207+
/**
208+
* @expectedException \PHPCR\RepositoryException
209+
* @dataProvider dataproviderRelativizePathInvalid
210+
*/
211+
public function testRelativizePathInvalidThrow($inputPath, $context)
212+
{
213+
PathHelper::relativizePath($inputPath, $context);
214+
}
215+
216+
/**
217+
* @dataProvider dataproviderRelativizePathInvalid
218+
*/
219+
public function testRelativizePathInvalidNoThrow($inputPath, $context)
220+
{
221+
$this->assertFalse(PathHelper::relativizePath($inputPath, $context, false));
222+
}
223+
224+
public static function dataproviderRelativizePathInvalid()
225+
{
226+
return array(
227+
array('/path', '/context'),
228+
array('/parent', '/parent/child'),
229+
);
230+
}
231+
189232
// getParentPath tests
190233

191234
/**

0 commit comments

Comments
 (0)