Created
November 1, 2012 20:12
-
-
Save hakre/3996171 to your computer and use it in GitHub Desktop.
Some knowledge about a phar path condensed into a class
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
<?php | |
/** | |
* Some knowledge about a phar path condensed | |
* into a class | |
*/ | |
class PharPath | |
{ | |
private $path; | |
public function __construct($path) { | |
$this->setPath($path); | |
} | |
/** | |
* @param string $url | |
* @throws \UnexpectedValueException | |
*/ | |
public function setPath($url) { | |
$this->path = strtr($url, '\\', '/'); # UNIX Paths Normalization; | |
$this->getPathToPharFile(); // trigger Exception to validate input. | |
} | |
public function hasScheme() { | |
return substr($this->path, 0, 7) === 'phar://'; | |
} | |
/** | |
* @return string path to the .phar file on disk | |
* @throws \UnexpectedValueException | |
*/ | |
public function getPathToPharFile() { | |
if (!$this->hasScheme()) { | |
// by php convention, phar files included via phar:// are announced | |
// without that scheme prefix. | |
return $this->path; | |
} | |
$path = $this->getSchemeFreePath(); | |
$offset = strrpos($path, '.phar'); // phar:// wrapper looks from the end | |
if ($offset === false) { | |
throw new \UnexpectedValueException('Phar does not have the .phar extension but it is needed.'); | |
} | |
$path = substr($path, 0, $offset + 5); | |
return $path; | |
} | |
/** | |
* @return string path without the (optional) phar:// stream wrapper scheme prefix | |
*/ | |
public function getSchemeFreePath() { | |
$buffer = $this->path; | |
$this->hasScheme() && $buffer = substr($buffer, 7); | |
return $buffer; | |
} | |
/** | |
* @return string path inside the phar, normally a file or directory | |
*/ | |
public function getPharPath() { | |
if (!$this->hasScheme()) { | |
return ''; | |
} | |
$path = $this->getSchemeFreePath(); | |
$base = $this->getPathToPharFile(); | |
if ($base === $path) { | |
return ''; | |
} | |
return substr($path, strlen($base)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment