Last active
November 8, 2025 17:21
-
-
Save aklump/13e240478d1c3ecc33c320b5477b3acf to your computer and use it in GitHub Desktop.
Search for a path moving up the file tree, e.g. "locate .git from child path"
This file contains hidden or 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 | |
| /** | |
| * The Upfind class provides functionality to locate a file or directory | |
| * by walking up the directory tree from a starting directory. | |
| */ | |
| class Upfind { | |
| public function __invoke(string $basename): string { | |
| $result = $this->upfind($basename); | |
| if (!$result) { | |
| return ''; | |
| } | |
| return $result . DIRECTORY_SEPARATOR . $basename; | |
| } | |
| private function upfind($basename, $start_dir = NULL) { | |
| $path = $start_dir; | |
| if (!isset($path)) { | |
| $path = getcwd(); | |
| } | |
| while ($path | |
| && $path !== DIRECTORY_SEPARATOR | |
| && ($expected = $path . DIRECTORY_SEPARATOR . $basename) | |
| && !file_exists($expected)) { | |
| $path = dirname($path); | |
| unset($expected); | |
| } | |
| if (empty($expected)) { | |
| return ''; | |
| } | |
| return $path; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment