<?php
/**
* Decodes input strings for dry-run scenarios with optional flags.
*
* @param string $input The input string to decode.
* @param array $flags An array of optional flags. Defaults to an empty array.
* @return array|string The decoded data or an error message.
*/
function decodeInput(string $input, array $flags = []): array|string
{
$decoded = [];
// Handle flags
foreach ($flags as $flag => $value) {
if ($flag === 'debug') {
$decoded['debug'] = $value;
} elseif ($flag === 'verbose') {
$decoded['verbose'] = $value;
} else {
return "Error: Unknown flag '$flag'"; // Invalid flag
}
}
// Decode the input string
if (empty($input)) {
return "Error: Input string is empty.";
}
// Simple example: split by comma and then split each element by a pipe
$parts = explode(',', $input);
foreach ($parts as $part) {
$pipe_parts = explode('|', trim($part)); // Trim whitespace
if (count($pipe_parts) === 2) {
$decoded[$pipe_parts[0]] = $pipe_parts[1];
} elseif (count($pipe_parts) === 1) {
$decoded[$pipe_parts[0]] = ''; //Handle single element
} else {
return "Error: Invalid input format. Expected format: key|value or key";
}
}
return $decoded;
}
//Example Usage
//echo decodeInput("key1|value1,key2|value2", ['debug' => true]);
//echo decodeInput("key1|value1,key2|value2", []);
//echo decodeInput("", []);
//echo decodeInput("key1,key2", ['verbose' => true]);
//echo decodeInput("key1|value1|extra", []);
?>
Add your comment