Skip to content

Instantly share code, notes, and snippets.

@karakhanyans
Created January 26, 2021 22:08
Show Gist options
  • Save karakhanyans/e40322dc7ce48e13d8ea74b4c591b4a2 to your computer and use it in GitHub Desktop.
Save karakhanyans/e40322dc7ce48e13d8ea74b4c591b4a2 to your computer and use it in GitHub Desktop.
Questionarie
<?php
namespace App\Contracts;
interface QuestionnaireInterface
{
public function setQuestion(string $question);
public function setAnswer(string $answer, bool $isValid);
public function save();
public function checkAnswer($id);
}
<?php
namespace App\Services;
use App\Contracts\QuestionnaireInterface;
class SingleAnswerService implements QuestionnaireInterface
{
protected $question;
protected $answers = [];
protected $id;
protected $other;
public function __construct()
{
$this->id = uniqid();
}
public function setQuestion(string $question)
{
$this->question = $question;
}
public function setAnswer(string $answer, bool $isValid = true)
{
$this->answers[] = [
'id' => uniqid(),
'answer' => $answer,
'is_valid' => $isValid
];
}
public function setOther(string $other)
{
$this->other = $other;
}
protected function validate()
{
$filtered = array_filter($this->answers, function ($answer) {
return $answer['is_valid'];
});
if (empty($filtered)) {
throw new \Exception('Questionnaire should have at least one correct answer');
}
}
public function save(): array
{
$this->validate();
return [
'question' => $this->question,
'answers' => $this->answers
];
}
public function checkAnswer($id): bool
{
$answer = array_filter($this->answers, function ($answer) use ($id){
return $answer['id'] === $id;
});
$answer = array_values($answer);
return $answer[0]['is_valid'];
}
}
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
$singleAnswer = new \App\Services\SingleAnswerService();
$singleAnswer->setQuestion('What is your age?');
$singleAnswer->setAnswer('14-16', true);
$singleAnswer->setAnswer('17-24', false);
$singleAnswer->setAnswer('25-30', false);
$question = $singleAnswer->save();
$checkAnswer = $singleAnswer->checkAnswer($question['answers'][1]['id']);
dd($checkAnswer);
return view('welcome');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment