-
-
Save xenogenesi/9f91776c99019bfb7e48f4bed44c816f to your computer and use it in GitHub Desktop.
Phing AdhocTask to find the relative path between two paths
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
<!-- | |
Usage: | |
<relative-path from="${from}" to="${to}" | |
output="project_property" /> | |
--> | |
<adhoc-task name="relative-path"><![CDATA[ | |
class RelativePath extends Task { | |
private $from; | |
private $to; | |
private $output; | |
function setFrom($from) { | |
$this->from = $from; | |
} | |
function setTo($to) { | |
$this->to = $to; | |
} | |
function setOutput($output=null) { | |
$this->output = $output; | |
} | |
function main() { | |
$relpath = $this->find_relative_path($this->from, $this->to); | |
$this->log("relpath = " . $relpath); | |
if ($this->output != null) { | |
$this->project->setProperty($this->output, $relpath); | |
} | |
} | |
/** | |
* credits: https://gist.github.com/ohaal/2936041 | |
* Find the relative file system path between two file system paths | |
* | |
* @param string $frompath Path to start from | |
* @param string $topath Path we want to end up in | |
* | |
* @return string Path leading from $frompath to $topath | |
*/ | |
function find_relative_path ( $frompath, $topath ) { | |
$from = explode( DIRECTORY_SEPARATOR, $frompath ); // Folders/File | |
$to = explode( DIRECTORY_SEPARATOR, $topath ); // Folders/File | |
$relpath = ''; | |
$i = 0; | |
// Find how far the path is the same | |
while ( isset($from[$i]) && isset($to[$i]) ) { | |
if ( $from[$i] != $to[$i] ) break; | |
$i++; | |
} | |
$j = count( $from ) - 1; | |
// Add '..' until the path is the same | |
while ( $i <= $j ) { | |
if ( !empty($from[$j]) ) $relpath .= '..'.DIRECTORY_SEPARATOR; | |
$j--; | |
} | |
// Go to folder from where it starts differing | |
while ( isset($to[$i]) ) { | |
if ( !empty($to[$i]) ) $relpath .= $to[$i].DIRECTORY_SEPARATOR; | |
$i++; | |
} | |
// Strip last separator | |
return substr($relpath, 0, -1); | |
} | |
} | |
]]></adhoc-task> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment