impregnable fiend impregnable fiend - 5 months ago 10
PHP Question

How correctly improve this piece of PHP code to follow DRY?

I know that my question is plain, but I'm stucked and have no one to ask, but wanna do it right. Now my code works properly, but it's obviously not follow DRY so I'm asking for help. Current code:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$answer_1 = $request->answer_1;
$answer_2 = $request->answer_2;
$answerUser = $request->answerUser;

$answer_1 = pathinfo($answer_1, PATHINFO_FILENAME);
$answer_2 = pathinfo($answer_2, PATHINFO_FILENAME);

$filename = 'answers/' . $answer_1 . '.txt';
$f = fopen($filename, 'r+');
if ($f) {
$size = filesize($filename);
$content_1 = fread($f, $size);
$content_1 = trim($content_1);
fclose($f);
}
$filename = 'answers/' . $answer_2 . '.txt';
$f = fopen($filename, 'r+');
if ($f) {
$size = filesize($filename);
$content_2 = fread($f, $size);
$content_2 = trim($content_2);
fclose($f);
}

if (strcmp($content_1, $answerUser) == 0 || strcmp($content_2, $answerUser) == 0) {
http_response_code(200);
} else {
http_response_code(400);
}


My code works fine, there is no errors, but I dunno how to do correctly refactoring here.
So, now if ( just for example ) I got 20 'answers' from client I have to write almost identical 20 expressions, but apparently it has to be a function. Any advises will be greatly ... you know :)

Answer

Something like this should work fine. The important thing is that you check at the start of the foreach loop whether the element is actually an answer or something else. I'll leave that part to you since you know the details of the data input better.

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$answerUser = $request->answerUser;

$any_correct = false;

foreach ($request as $answer) {
    //Implement some logic right here to check whether it is an answer or not!
    if($answer){
        $path = pathinfo($answer, PATHINFO_FILENAME);
        $filename = 'answers/' . $path . '.txt';
        $f = fopen($filename, 'r+');
        if ($f) {
            $size = filesize($filename);
            $content_1 = fread($f, $size);
            $content_1 = trim($content_1);
            fclose($f);

            if(strcmp($content_1, $answerUser) == 0){
                $any_correct = true;
            }
        }
    }
}
if($any_correct){
    http_response_code(200);
}else{
    http_response_code(400);
}
Comments