Skip to content

Instantly share code, notes, and snippets.

@mageekguy
Last active December 13, 2015 17:58
Show Gist options
  • Save mageekguy/4951925 to your computer and use it in GitHub Desktop.
Save mageekguy/4951925 to your computer and use it in GitHub Desktop.
public function getRelativePathFrom(self $reference)
{
$referencePath = static::cleanPath($reference);
switch (true)
{
case $this->path == $referencePath:
return '.';
case $referencePath == '':
return '.' . $this->path;
case $this->isSubPathOf($referencePath):
return './' . substr($this->path, strlen($referencePath) + 1);
default:
$relativePath = '';
while ($this->isNotSubPathOf($referencePath))
{
$relativePath .= '../';
$referencePath = dirname($referencePath);
}
return static::cleanPath($relativePath) . '/' . ltrim(substr($this->path, strlen($referencePath)), '/');
}
}
protected function isSubPathOf($path)
{
return ($path == '/' || strpos($this->path, $path . '/') === 0);
}
protected function isNotSubPathOf($path)
{
return ($this->isSubPathOf($path) === false);
}
protected static function cleanPath($path)
{
return rtrim($path, '/');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment