Created
June 18, 2012 14:59
-
-
Save henriquemoody/2948782 to your computer and use it in GitHub Desktop.
PHP CLI script in procedural style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function writeln($message = '', $stream = STDOUT) | |
{ | |
fwrite($stream, $message . PHP_EOL); | |
} | |
$arg_options = array( | |
'help' => array( | |
'required' => false, | |
'description' => 'Displays the help message', | |
), | |
'zipcode' => array( | |
'required' => true, | |
'description' => 'Zip code', | |
'validator' => function ($zip_code) | |
{ | |
return (1 == preg_match('/\d{5}-?\d{3}/', $zip_code)); | |
}, | |
'filter' => function ($zip_code) | |
{ | |
return preg_replace('/[^\d]/', '', $zip_code); | |
} | |
), | |
'filename' => array( | |
'required' => false, | |
'description' => 'File to read', | |
'default' => __DIR__ . '/address.xml', | |
'validator' => 'is_file', | |
) | |
); | |
$help_msg = 'Usage: php '. array_shift($_SERVER['argv']) . ' OPTIONS' . PHP_EOL . PHP_EOL; | |
foreach ($arg_options as $key => $value) { | |
$help_msg .= ' --' . str_pad($key, 10) . $value['description'] . PHP_EOL; | |
} | |
$arg_values = array(); | |
foreach ($_SERVER['argv'] as $key => $value) { | |
if (0 != $key % 2 ) { | |
continue; | |
} | |
$arg_key = substr($value, 2); | |
if (!isset($arg_options[$arg_key])) { | |
writeln('Unrecognized option ' . $value, STDERR); | |
exit (2); | |
} | |
$arg_option = $arg_options[$arg_key]; | |
if (isset($_SERVER['argv'][$key + 1])) { | |
$arg_value = $_SERVER['argv'][$key + 1]; | |
} elseif (isset($arg_option['default'])) { | |
$arg_value = $arg_option['default']; | |
} else { | |
$arg_value = true; | |
} | |
$arg_values[$arg_key] = $arg_value; | |
} | |
if (empty($arg_values)) { | |
writeln($help_msg, STDERR); | |
exit (1); | |
} | |
if (isset($arg_values['help'])) { | |
writeln($help_msg); | |
exit; | |
} | |
foreach ($arg_options as $arg_key => $arg_option) { | |
if (isset($arg_option['default']) | |
&& !isset($arg_values[$arg_key])) { | |
$arg_values[$arg_key] = $arg_option['default']; | |
} | |
$arg_value = isset($arg_values[$arg_key]) ? $arg_values[$arg_key] : null; | |
if (null === $arg_value && true === $arg_option['required']) { | |
writeln('Value for "--' . $arg_key . '" is required', STDERR); | |
exit (3); | |
} | |
if (null !== $arg_value && isset($arg_option['validator'])) { | |
if (!call_user_func($arg_option['validator'], $arg_value)) { | |
writeln('Value for "--' . $arg_key . '" is not valid', STDERR); | |
exit (4); | |
} | |
} | |
if (isset($arg_option['filter'])) { | |
$arg_value = call_user_func($arg_option['filter'], $arg_value); | |
} | |
$arg_values[$arg_key] = $arg_value; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment