]> BookStack Code Mirror - system-cli/blob - src/Services/AppLocator.php
b6710a89845bf7b4a26cf98236c20519f79306d4
[system-cli] / src / Services / AppLocator.php
1 <?php declare(strict_types=1);
2
3 namespace Cli\Services;
4
5 use Phar;
6
7 class AppLocator
8 {
9     public static function search(string $directory = ''): string
10     {
11         $directoriesToSearch = $directory ? [$directory] : [
12             getcwd(),
13             static::getCliDirectory(),
14         ];
15
16         foreach ($directoriesToSearch as $directory) {
17             if ($directory && static::isProbablyAppDirectory($directory)) {
18                 return $directory;
19             }
20         }
21
22         return '';
23     }
24
25     public static function require(string $directory = ''): string
26     {
27         $dir = static::search($directory);
28
29         if (!$dir) {
30             throw new \Exception('Could not find a valid BookStack installation');
31         }
32
33         return $dir;
34     }
35
36     protected static function getCliDirectory(): string
37     {
38         $scriptDir = dirname(__DIR__);
39         if (str_starts_with($scriptDir, 'phar://')) {
40             $scriptDir = dirname(Phar::running(false));
41         }
42
43         return dirname($scriptDir);
44     }
45
46     protected static function isProbablyAppDirectory(string $directory): bool
47     {
48         return file_exists($directory . DIRECTORY_SEPARATOR . 'version')
49             && file_exists($directory . DIRECTORY_SEPARATOR . 'package.json');
50     }
51 }