1
\$\begingroup\$

Good day! I would like to know if this is possible to be refactored into a cleaner code. The reason I'm doing it like this is to catch the column that the error appeared on and then potentially output the column name and value for the client to view later on.

// Make the name act as the key and the value equates to ID
// $towers['tower1'] = 1;
$towers = Tower::pluck('id', 'name')->toArray();
$departments = Department::pluck('id', 'name')->toArray();

foreach($data as $key => $row) {
    try {
        // $row['tower'] = 'Hello World Tower'
        // Try to see if $row['tower'] is present in the $towers data source
        $data[$key]['tower'] = $towers[$row['tower']];
    } catch (\Exception $e) {
        // Exception occurs because index is not available
        $error_holder[$key]['tower_error'] = $e->getMessage();
    }

    // Same logic as above
    try {
        $data[$key]['department'] = $departments[$row['department']];
    } catch (\Exception $e) {
        $error_holder[$key]['department_error'] = $e->getMessage();
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ The catch blocks will never be executed. Voting to close as not working as intended. \$\endgroup\$
    – slepic
    Commented Jun 17, 2020 at 12:49

1 Answer 1

2
\$\begingroup\$

You need anything here but a try catch.

foreach($data as $key => $row) {
    // $row['tower'] = 'Hello World Tower'
    // Try to see if $row['tower'] is present in the $towers data source
    if (isset($towers[$row['tower']])) {
        $data[$key]['tower'] = $towers[$row['tower']];
    } else {
        $error_holder[$key]['tower_error'] = "Tower not found for $key";
    }

    if (isset($departments[$row['department']])) {
        $data[$key]['department'] = $departments[$row['department']];
    } else {
        $error_holder[$key]['tower_error'] = "Department not found for $key";
    }
}

Although you can reduce the duplication by storing sources into array and looping over it but honestly it makes the code so muddled that I don't see the benefit.

foreach (compact('tower','department') as $name => $column)
    foreach($data as $key => $row) {
        if (isset($column[$row[$name]])) {
            $data[$key][$name] = $column[$row[$name]];
        } else {
            $error_holder[$key][$name.'_error'] = "$name not found for $key";
        }
    }
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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