1. <?php
  2. /**
  3. * Binds runtime environment arguments for sandbox usage with optional flags.
  4. *
  5. * @param array $argv Array of command-line arguments.
  6. * @return array Associative array of environment variables.
  7. */
  8. function bindRuntimeEnvironment(array $argv): array
  9. {
  10. $env = [];
  11. // Default values
  12. $env['DEBUG'] = false;
  13. $env['LOG_LEVEL'] = 'info';
  14. $env['MAX_FILE_SIZE'] = 1024 * 1024; // 1MB
  15. // Parse command-line arguments
  16. $i = 1;
  17. while ($i < count($argv)) {
  18. $arg = $argv[$i];
  19. if ($arg === '--debug') {
  20. $env['DEBUG'] = true;
  21. } elseif ($arg === '--log-level') {
  22. if ($i + 1 < count($argv)) {
  23. $env['LOG_LEVEL'] = $argv[$i + 1];
  24. $i += 2; // Skip the flag and its value
  25. } else {
  26. error_log("Missing value for --log-level");
  27. $i++;
  28. }
  29. } elseif ($arg === '--max-file-size') {
  30. if ($i + 1 < count($argv)) {
  31. $env['MAX_FILE_SIZE'] = (int)$argv[$i + 1] * 1024 * 1024; // Convert to bytes
  32. $i += 2;
  33. } else {
  34. error_log("Missing value for --max-file-size");
  35. $i++;
  36. }
  37. } else {
  38. error_log("Unknown argument: " . $arg);
  39. $i++;
  40. }
  41. }
  42. // Set environment variables
  43. putenv('DEBUG=' . (int)$env['DEBUG']); // Convert boolean to integer
  44. putenv('LOG_LEVEL=' . $env['LOG_LEVEL']);
  45. putenv('MAX_FILE_SIZE=' . $env['MAX_FILE_SIZE']);
  46. return $env;
  47. }
  48. // Example usage (for testing/demonstration)
  49. // $argv = ['--debug', '--log-level=debug', '--max-file-size=2048'];
  50. // $env = bindRuntimeEnvironment($argv);
  51. // print_r($env);
  52. ?>

Add your comment