refactoring - How could I reduce PHP code with lots of isset checks and repetitive, but variable generation arguments? -


greetings. struggling reduce code segment looks rather lengthy, leaving me unconvinced essentiality. it's function generate multitude of session arrays used fill out forms, , has me verifying existence of values in argument array, cases every single 1 generate 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',             'option 1') : '');      $_session['bardata'] = (isset($formdata['cbbar']) ? prepbaseform(prepotherarray($formdata), 'bar',             'option bar', 'optional argument') : '');  } 

the function accepts formdata array argument, , depending on contained values generates corresponding arrays in session; happens after checking existence of matching flag, hence issets , ternary operator.

the called function, prepbaseform, separates appending of second , third arguments, corresponding filename , friendly name, first argument, array; accepts optional fourth parameter, indicating file concatenate filled form.

if value not present in array, code intentionally clears corresponding session variable '' in order keep generation order intact (to end: there better way of doing this, considering there scenarios in given generation order broken?).

the actual code has twenty generation blocks format, , it's getting quite lengthy; 1 optimization thought of loop through given fields , generalize generation process, can see, many times arguments differ, or input array prepbaseform function has generated way. ideas on how tackle refactoring? in advance response.

one option provide defaults, , run if values changed using normal conditionals. can clean further putting simple loop.:

function prepoptional($formdata) {     $baseinfo=getbaseinfo();      $options = array(         'foo' => 'option foo',          'opt1' => 'option opt1',         'bar' => 'option bar',     );     foreach ($options $name => $text) {         //add defaults formdata , session arrays)         $formdata += array('cb' . ucfirst($name) => '');         $_session += array($name . 'data' => '');          if ($formdata['cb' . ucfirst($name)]) {             $_session[$name . 'data'] = prepbaseform(                 $baseinfo,                  $name,                  $text             );         }     } } 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -