- Install Laravel Prompts
composer require laravel/prompts
-
Put
selectFile.php
insrc
directory. -
Put
Dir.php
insrc
directory.
Run the src/selectFile.php
.
php -f src/selectFile.php
composer require laravel/prompts
Put selectFile.php
in src
directory.
Put Dir.php
in src
directory.
Run the src/selectFile.php
.
php -f src/selectFile.php
<?php | |
namespace MyLib; | |
class Dir | |
{ | |
/** | |
* Returns all entries in the directory as RecursiveDirectoryIterator | |
* ディレクトリ内の全エントリーをRecursiveDirectoryIteratorで返す | |
* | |
* @param string $value | |
* @return \RecursiveDirectoryIterator|\RegexIterator|array{} | |
*/ | |
public static function glob(string $value) | |
{ | |
if (strlen($value) === 0) { | |
return new \RecursiveDirectoryIterator('.'); | |
} | |
if (str_ends_with($value, '/')) { | |
if (is_dir($value) && is_readable($value)) { | |
return new \RecursiveDirectoryIterator($value); | |
} | |
return []; | |
} | |
$dir = './'; | |
$file = $value; | |
if (str_contains($value, '/')) { | |
$dir = dirname($value); | |
$file = pathinfo($value)['basename']; | |
} | |
$pattern = sprintf("/%s/", preg_quote($file)); | |
return new \RegexIterator( | |
new \RecursiveDirectoryIterator($dir), | |
$pattern | |
); | |
} | |
/** | |
* Returns all entries in the directory as an array | |
* ディレクトリ内の全エントリーを配列で返す | |
* | |
* @param string $value | |
* @return string[] | |
*/ | |
public static function entries(string $value) | |
{ | |
$entries = array_map( | |
fn (string $e) => is_dir($e) | |
? str_replace('//', '/', $e . '/') | |
: str_replace('//', '/', $e), | |
iterator_to_array(self::glob($value)) | |
); | |
sort($entries); | |
return $entries; | |
} | |
} |
<?php | |
require_once __DIR__ . '/../vendor/autoload.php'; | |
require_once __DIR__ . '/Dir.php'; | |
use function Laravel\Prompts\suggest; | |
$selected = suggest( | |
label: 'Select a file.', | |
placeholder: './vendor/autoload.php', | |
default: '', | |
options: fn (string $value) => MyLib\Dir::entries($value), | |
required: 'Selecting a file is required.', | |
validate: fn (string $value) => match (true) { | |
is_dir($value) => "It's a directory.", | |
!is_readable($value) => 'Cannot read the file.', | |
default => null, | |
}, | |
); | |
var_dump($selected); |