/** * Public entry point to service * @return boolean */ public function service() { if (!$this->shouldService()) { $this->response("Sorry, could not find a survey by that name."); return false; } $qindex = $this->surveyState->getQuestionIndex(); //No qindex exists, or we are at the first question. if (is_null($qindex)) { $qindex = 0; $this->surveyState->setQuestionIndex($qindex); //return first question $question = $this->surveyState->getQuestion(); $this->response($question); return true; } $question = $this->surveyState->getQuestionObj(); $validator = $this->answerValidatorProvider->getValidator($question->getType()); $answer = $this->getRequestBody(); if ($validator->isValid($answer)) { //move to next question $qindex++; //persist our question index state $this->surveyState->setQuestionIndex($qindex); if (!$this->surveyState->hasId()) { $from = session_id(); if (array_key_exists('From', $this->request)) { $from = $this->request['From']; } $this->surveyState->setId($from); } $answer = $validator->normalize($answer); $this->persistAnswer($this->surveyState->getId(), $question, $answer); } else { $helperText = $validator->getHelperText(); $response = "Sorry, we couldn't understand your response. {$helperText}"; $this->response($response); return true; } $next_question = $this->surveyState->getQuestion($qindex); if (is_null($next_question)) { //no more questions. Send thank you message. $this->surveyState->setSurveyExecutionState(SurveyExecutionState::Completed()); $next_question = $this->surveyState->getSurvey()->getThankYouMessage(); } $this->response($next_question); return true; }
function testSurveyState() { $questionStub = $this->getMock('sarhan\\survey\\SurveyQuestion'); $surveyStub = $this->getMock("sarhan\\survey\\Survey"); $surveyStub->expects($this->any())->method('getQuestions')->will($this->returnValue(array($questionStub, $questionStub, $questionStub))); $questionStub->expects($this->any())->method("getType")->will($this->returnValue(QuestionType::YesNo())); $this->assertEquals(array($questionStub, $questionStub, $questionStub), $surveyStub->getQuestions()); $s = new SurveyState(); $s->setSurvey($surveyStub); $this->assertFalse($s->hasId()); $s->setId("foobar"); $this->assertTrue($s->hasId()); $s->setQuestionIndex(0); $q = $s->getQuestion(); $this->assertNotNull($q); $s->setQuestionIndex(3); $q = $s->getQuestion(); $this->assertNull($q); }