How could I reduce PHP code with lots of isset checks and repetitive, but variable generation arguments?
Greetings. I am struggling to reduce a code segment that looks rather lengthy, leaving me unconvinced about its essentiality. It's a function to generate a multitude of session arrays used to fill out forms, and it has me verifying the existence of certain values in the argument array, with cases for every single one to generate the requested arrays. Here goes:
function prepOptional($formData) {
$baseInfo=getBaseInfo();
$_SESSION['fooData'] = (isset($formData['cbFoo']) ? prepBaseForm($baseInfo, 'foo',
'Option foo') : '');
$_SESSION['opt1Data'] = (isset($formData['cbOpt1']) ? prepBaseForm($baseInfo, 'opt1',
'Opti开发者_StackOverflowon 1') : '');
$_SESSION['barData'] = (isset($formData['cbBar']) ? prepBaseForm(prepOtherArray($formData), 'bar',
'Option bar', 'Optional argument') : '');
}
The function accepts a formdata array as argument, and depending on the contained values it generates the corresponding arrays in session; this happens only after checking the existence of the matching flag, hence the issets and the ternary operator.
The called function, prepBaseForm, separates the appending of the second and third arguments, corresponding to a filename and a friendly name, to the first argument, which is an array; it also accepts an optional fourth parameter, indicating a file to concatenate to the filled form.
If the value is not present in the array, the code intentionally clears the corresponding session variable to '' in order to keep the generation order intact (to this end: is there a better way of doing this, considering that there are scenarios in which the given generation order will be broken?).
The actual code has about twenty generation blocks with this format, and it's getting quite lengthy; one optimization I thought of was to loop through the given fields and generalize the generation process, but as you can see, many times the arguments differ, or the input array for the prepBaseForm function has to be generated another way. Any ideas on how I could tackle this refactoring? Thanks in advance for your response.
One option would be to provide defaults, and just run it if the values are changed using normal conditionals. Then you can clean up further by putting everything into a simple loop.:
function prepOptional($formData) {
$baseInfo=getBaseInfo();
$options = array(
'foo' => 'Option foo',
'opt1' => 'Option Opt1',
'bar' => 'Option Bar',
);
foreach ($options as $name => $text) {
//Add defaults for formData and Session arrays)
$formData += array('cb' . ucfirst($name) => '');
$_SESSION += array($name . 'Data' => '');
if ($formData['cb' . ucfirst($name)]) {
$_SESSION[$name . 'Data'] = prepBaseForm(
$baseInfo,
$name,
$text
);
}
}
}
精彩评论