Skip to content

Instantly share code, notes, and snippets.

@macocci7
Created May 26, 2024 09:15
Show Gist options
  • Save macocci7/e78a3670faa4a8d7d023866db531cb40 to your computer and use it in GitHub Desktop.
Save macocci7/e78a3670faa4a8d7d023866db531cb40 to your computer and use it in GitHub Desktop.
[Laravel Prompts] File Selector (ファイル選択)

Laravel Prompts : File Selector

Installation

composer require laravel/prompts
  • Put selectFile.php in src directory.

  • Put Dir.php in src directory.

Usage

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);
@macocci7
Copy link
Author

laravel11_prompts_select_file_11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment