如何正确改进这段PHP代码以遵循DRY?

时间:2016-06-24 15:20:36

标签: php angularjs

我知道我的问题很简单,但是我被困了,没有人问,但是想做得对。现在我的代码工作正常,但显然不是关注DRY所以我正在寻求帮助。 当前代码:

$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);
}

我的代码工作正常,没有错误,但我不知道如何正确地重构这里。 所以,现在如果(仅举例)我从客户端得到20'答案'我必须编写几乎相同的20个表达式,但显然它必须是一个函数。任何建议都会很大......你知道:)。

1 个答案:

答案 0 :(得分:1)

这样的事应该可以正常工作。重要的是你在foreach循环的开头检查元素是否实际上是一个答案或其他东西。因为您更了解数据输入的详细信息,所以我会将该部分留给您。

$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);
}