Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active November 8, 2025 18:16
Show Gist options
  • Save aklump/03b743c3b53315ad25869f7775d75a8a to your computer and use it in GitHub Desktop.
Save aklump/03b743c3b53315ad25869f7775d75a8a to your computer and use it in GitHub Desktop.
Create a pretty/short path, removing CWD or basepath.
<?php
/**
* @code
* // Print a shortened, nice-to-read path when possible:
* echo (new GetShortPath('/some/base/path')($long_path)
*
* // Or relative to the CWD:
* echo (new GetShortPath()($long_path)
* @endcode
*/
class GetShortPath {
private string $basepath;
public function __construct(string $basepath = NULL) {
$this->basepath = $basepath ?? getcwd();
}
public function __invoke(string $path): string {
if (!str_starts_with($path, $this->basepath)) {
return $path;
}
$short_path = substr($path, strlen($this->basepath) + 1);
if ($this->basepath === getcwd()) {
$short_path = "./$short_path";
}
return $short_path;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment