Php

Is there something I can do even more specificly of the code that is Passage specific?

 Thoughts on what I should do with the following code. Any suggestions?
 
 
public function show(Request $request, Quiz $quiz)
{
$type = $quiz->quizzable;

switch($type->getMorphClass()) {
case 'App\Models\Passage':
$wrappedContent = wordwrap($type->text, 50, "\r\n");
$explodedLines = explode("\r\n", $wrappedContent);

$lineNumbers = count($explodedLines);
}

$questions = $quiz->questions->load('choices');
$question = $quiz->questions->first();
$total = $questions->count();
$data = ['passage' => $passage, 'total' => $total, 'questions' => $questions];

if ($request->ajax()) {
return response()->json($data);
}

return view('quizzes.show', compact('questions', 'quiz', 'type', 'lineNumbers'));
}

 
Forr example shoudl I crate a view composer for a passage for this code since its view specific for a passage.
 
$wrappedContent = wordwrap($type->text, 50, "\r\n");
$explodedLines = explode("\r\n", $wrappedContent);

$lineNumbers = count($explodedLines);
You already invited:

tuan

Upvotes from:

First I would remove the `$question` as it seems to not be used anywhere. second I would move some of the logic outside the show method into it's own function so I can do unit test and performance test on it just to make sure that works fine. the show function can call that function that prepares the data and then return the view or ajax response. Fourth not sure if the code is incomplete, but I don't see where the passable variable is being set.

Cyrus

Upvotes from:

1. I also can't see where $passage is being set.
2. I would create and add an interface for all of your quizzable models. That way you can require say a getLineCount() function on all your quizzable models and then just call that from within your code (knowing that it will be there). That would get rid of the entire switch statement and change it to just $lineNumbers = $quiz->quizzable->getLineCount();
3) Maybe this controller method is incomplete but it feels like it's doing 2 similar but still somewhat different things - separate the ajax into one controller and keep the other one here. The only piece of data that overlaps between the ajax response and the normal response is $questions. Having just one variable overlapping shows it shouldn't be together in the same controller.

If you wanna answer this question please Login or Register