1. <?php
  2. /**
  3. * Binds CLI arguments for dry-run scenarios with error logging.
  4. *
  5. * @param array $argv The command-line arguments array.
  6. * @param array $dryRunOptions Optional array of dry-run options.
  7. * @param string $logFile Optional path to the error log file.
  8. * @return array An associative array containing the arguments, dry-run options, and errors.
  9. */
  10. function bindCliArguments(array $argv, array $dryRunOptions = [], string $logFile = 'cli_errors.log'): array
  11. {
  12. $arguments = [];
  13. $errors = [];
  14. // Parse arguments
  15. for ($i = 1; $i < count($argv); $i++) {
  16. $arg = $argv[$i];
  17. if ($arg === '--dry-run') {
  18. $dryRunOptions = $dryRunOptions ? $dryRunOptions : []; // Initialize if not already set
  19. } elseif (strpos($arg, '=') === 0) {
  20. list($key, $value) = explode('=', $arg, 2);
  21. $arguments[$key] = $value;
  22. } else {
  23. $arguments[] = $arg;
  24. }
  25. }
  26. // Validate dry-run options
  27. if (isset($dryRunOptions['enabled']) && $dryRunOptions['enabled'] === false) {
  28. $errors[] = "Dry-run mode is disabled.";
  29. }
  30. // Log errors if any
  31. if (!empty($errors)) {
  32. error_log(implode("\n", $errors), 3, $logFile); // Log to file
  33. }
  34. return [
  35. 'arguments' => $arguments,
  36. 'dryRunOptions' => $dryRunOptions,
  37. 'errors' => $errors,
  38. ];
  39. }

Add your comment