-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
60 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
<?php | ||
|
||
namespace Aternos\IO\System\Util; | ||
|
||
use Aternos\IO\Exception\IOException; | ||
use Aternos\IO\Exception\PathOutsideElementException; | ||
use Aternos\IO\Interfaces\Features\GetPathInterface; | ||
|
||
/** | ||
* Trait GetRelativePathToTrait | ||
* | ||
* Implements getRelativePathTo method | ||
* | ||
* @package Aternos\IO\System\Util | ||
*/ | ||
trait GetRelativePathToTrait | ||
{ | ||
/** | ||
* Get the relative path to another element | ||
* | ||
* @param GetPathInterface $element | ||
* @param bool $allowOutsideElement Allow paths outside the element, throws an exception otherwise | ||
* @return string | ||
* @throws PathOutsideElementException | ||
* @throws IOException | ||
*/ | ||
public function getRelativePathTo(GetPathInterface $element, bool $allowOutsideElement = false): string | ||
{ | ||
$sourcePath = $element->getPath(); | ||
$targetPath = $this->getPath(); | ||
|
||
$sourcePathParts = explode(DIRECTORY_SEPARATOR, $sourcePath); | ||
$targetPathParts = explode(DIRECTORY_SEPARATOR, $targetPath); | ||
|
||
foreach ($sourcePathParts as $key => $sourcePathPart) { | ||
if (isset($targetPathParts[$key]) && $targetPathParts[$key] === $sourcePathPart) { | ||
unset($sourcePathParts[$key]); | ||
unset($targetPathParts[$key]); | ||
continue; | ||
} | ||
|
||
if (!$allowOutsideElement) { | ||
throw new PathOutsideElementException("Path is outside of element (" . $sourcePath . " -> " . $targetPath . ")", $this); | ||
} | ||
break; | ||
} | ||
|
||
$relativePath = ""; | ||
foreach ($sourcePathParts as $ignored) { | ||
$relativePath .= ".." . DIRECTORY_SEPARATOR; | ||
} | ||
foreach ($targetPathParts as $targetPathPart) { | ||
$relativePath .= $targetPathPart . DIRECTORY_SEPARATOR; | ||
} | ||
return rtrim($relativePath, DIRECTORY_SEPARATOR); | ||
} | ||
} |