src/CLI/functions.php source

1 <?php
2
3 namespace mini;
4
5 use mini\CLI\ArgManager;
6
7 /**
8 * CLI Feature - Global Helper Functions
9 *
10 * These functions provide the public API for the mini\CLI feature.
11 */
12
13 /**
14 * Get or set the current ArgManager instance for CLI argument parsing
15 *
16 * Returns an unconfigured ArgManager on first call. Use the pattern:
17 * args(args()->withFlag(...)->withSubcommand(...));
18 *
19 * This same pattern works at every command level - root command and subcommands
20 * all configure themselves identically.
21 *
22 * @param ArgManager|null $args ArgManager instance to set, or null to retrieve
23 * @return ArgManager The current ArgManager
24 *
25 * @example Simple command
26 * ```php
27 * // bin/myapp
28 * args(args()->withFlag('v', 'verbose')->withRequiredValue('o', 'output'));
29 *
30 * if (args()->getUnparsedArgs()) {
31 * die("Unexpected: " . implode(', ', args()->getUnparsedArgs()));
32 * }
33 *
34 * if (args()->getFlag('verbose')) {
35 * echo "Verbose mode\n";
36 * }
37 * ```
38 *
39 * @example Command with subcommands
40 * ```php
41 * // bin/myapp
42 * args(args()->withFlag('v', 'verbose')->withSubcommand('run', 'build'));
43 *
44 * if (args()->getUnparsedArgs()) {
45 * die("Unexpected: " . implode(', ', args()->getUnparsedArgs()));
46 * }
47 *
48 * if ($sub = args()->nextCommand()) {
49 * args($sub); // Hand off to subcommand
50 * require __DIR__ . '/commands/' . $sub->getCommand() . '.php';
51 * }
52 * ```
53 *
54 * @example Subcommand file (commands/run.php)
55 * ```php
56 * // Subcommand configures itself - same pattern as root
57 * args(args()->withFlag(null, 'fast')->withRequiredValue('t', 'target'));
58 *
59 * if (args()->getUnparsedArgs()) {
60 * die("Unexpected: " . implode(', ', args()->getUnparsedArgs()));
61 * }
62 *
63 * $fast = args()->getFlag('fast');
64 * $target = args()->getOption('target');
65 * ```
66 */
67 function args(?ArgManager $args = null): ArgManager
68 {
69 static $instance = null;
70
71 if ($args !== null) {
72 $instance = $args;
73 }
74
75 // Return unconfigured ArgManager by default
76 $instance ??= new ArgManager();
77
78 return $instance;
79 }
80