Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have written this method to normalize some part of an array into a consistent way.

Input for example can be:

array(
    0         => "field_1"
    1         => "field_2"
    "field_3" => array("type" => "some_type");
);

This should be transformed to:

array(
    "field_1" => array("type" => "default");
    "field_2" => array("type" => "default");
    "field_3" => array("type" => "some_type");
);

I'm trying to lower the cyclomatic complexity (if it all possible).

public function parse_fields(array $fields)
{
    $default_value = array('type' => 'default');
    $result = array();
    foreach($fields as $key => $value)
    {
        if(is_numeric($key))
        {
            $result[$value] = $default_value;
        }
        else
        {
            if(!empty($value))
            {
                $result[$key] = $value;
            }
            else
            {
                $result[$key] = $default_value;
            }
        }
    }
    return $result;
}

Note that in the future, the default values can be expanded, and would need to be merged if some elements were missing from the input array. Can you give tips how I can refactor this code to make it cleaner?

share|improve this question

1 Answer

I'm very curious why you want a function like this. It seems like the array itself is not generated in a very good way? Maybe you could explain more why you want this function so it's easier to create function that might suite you.

share|improve this answer
The array is obtained form yaml, which is created by users. This question has become irrelevant as I have rewritten the code. – Ikke Jul 26 '11 at 18:20
8  
You might want to delete the question then. – John Kraft Jul 26 '11 at 19:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.