1. <?php
  2. /**
  3. * Decodes input strings for dry-run scenarios with optional flags.
  4. *
  5. * @param string $input The input string to decode.
  6. * @param array $flags An array of optional flags. Defaults to an empty array.
  7. * @return array|string The decoded data or an error message.
  8. */
  9. function decodeInput(string $input, array $flags = []): array|string
  10. {
  11. $decoded = [];
  12. // Handle flags
  13. foreach ($flags as $flag => $value) {
  14. if ($flag === 'debug') {
  15. $decoded['debug'] = $value;
  16. } elseif ($flag === 'verbose') {
  17. $decoded['verbose'] = $value;
  18. } else {
  19. return "Error: Unknown flag '$flag'"; // Invalid flag
  20. }
  21. }
  22. // Decode the input string
  23. if (empty($input)) {
  24. return "Error: Input string is empty.";
  25. }
  26. // Simple example: split by comma and then split each element by a pipe
  27. $parts = explode(',', $input);
  28. foreach ($parts as $part) {
  29. $pipe_parts = explode('|', trim($part)); // Trim whitespace
  30. if (count($pipe_parts) === 2) {
  31. $decoded[$pipe_parts[0]] = $pipe_parts[1];
  32. } elseif (count($pipe_parts) === 1) {
  33. $decoded[$pipe_parts[0]] = ''; //Handle single element
  34. } else {
  35. return "Error: Invalid input format. Expected format: key|value or key";
  36. }
  37. }
  38. return $decoded;
  39. }
  40. //Example Usage
  41. //echo decodeInput("key1|value1,key2|value2", ['debug' => true]);
  42. //echo decodeInput("key1|value1,key2|value2", []);
  43. //echo decodeInput("", []);
  44. //echo decodeInput("key1,key2", ['verbose' => true]);
  45. //echo decodeInput("key1|value1|extra", []);
  46. ?>

Add your comment