Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like Quiz often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Quiz, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 10 | class Quiz extends Game |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * @var QuizMapperInterface |
||
| 14 | */ |
||
| 15 | protected $quizMapper; |
||
| 16 | |||
| 17 | /** |
||
| 18 | * @var QuizAnswerMapperInterface |
||
| 19 | */ |
||
| 20 | protected $quizAnswerMapper; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @var QuizQuestionMapperInterface |
||
| 24 | */ |
||
| 25 | protected $quizQuestionMapper; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @var QuizReplyMapperInterface |
||
| 29 | */ |
||
| 30 | protected $quizReplyMapper; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @var quizReplyAnswerMapper |
||
| 34 | */ |
||
| 35 | protected $quizReplyAnswerMapper; |
||
| 36 | |||
| 37 | /** |
||
| 38 | * |
||
| 39 | * |
||
| 40 | * @param array $data |
||
| 41 | * @return \PlaygroundGame\Entity\Game |
||
| 42 | */ |
||
| 43 | public function createQuestion(array $data) |
||
| 44 | { |
||
| 45 | $path = $this->getOptions()->getMediaPath().DIRECTORY_SEPARATOR; |
||
| 46 | $media_url = $this->getOptions()->getMediaUrl().'/'; |
||
| 47 | |||
| 48 | $question = new \PlaygroundGame\Entity\QuizQuestion(); |
||
| 49 | $form = $this->serviceLocator->get('playgroundgame_quizquestion_form'); |
||
| 50 | $form->bind($question); |
||
| 51 | $form->setData($data); |
||
| 52 | |||
| 53 | $quiz = $this->getGameMapper()->findById($data['quiz_id']); |
||
| 54 | if (!$form->isValid()) { |
||
| 55 | return false; |
||
|
|
|||
| 56 | } |
||
| 57 | |||
| 58 | $question->setQuiz($quiz); |
||
| 59 | |||
| 60 | // If question is a prediction, no need to calculate max good answers |
||
| 61 | if (!$question->getPrediction()) { |
||
| 62 | // Max points and correct answers calculation for the question |
||
| 63 | if (!$question = $this->calculateMaxAnswersQuestion($question)) { |
||
| 64 | return false; |
||
| 65 | } |
||
| 66 | } |
||
| 67 | |||
| 68 | // Max points and correct answers recalculation for the quiz |
||
| 69 | $quiz = $this->calculateMaxAnswersQuiz($question->getQuiz()); |
||
| 70 | |||
| 71 | $this->getEventManager()->trigger(__FUNCTION__, $this, array('game' => $question, 'data' => $data)); |
||
| 72 | $this->getQuizQuestionMapper()->insert($question); |
||
| 73 | $this->getEventManager()->trigger(__FUNCTION__ .'.post', $this, array('game' => $question, 'data' => $data)); |
||
| 74 | |||
| 75 | View Code Duplication | if (!empty($data['upload_image']['tmp_name'])) { |
|
| 76 | ErrorHandler::start(); |
||
| 77 | $data['upload_image']['name'] = $this->fileNewname( |
||
| 78 | $path, |
||
| 79 | $question->getId()."-".$data['upload_image']['name'] |
||
| 80 | ); |
||
| 81 | move_uploaded_file($data['upload_image']['tmp_name'], $path.$data['upload_image']['name']); |
||
| 82 | $question->setImage($media_url.$data['upload_image']['name']); |
||
| 83 | ErrorHandler::stop(true); |
||
| 84 | } |
||
| 85 | |||
| 86 | $this->getQuizQuestionMapper()->update($question); |
||
| 87 | $this->getQuizMapper()->update($quiz); |
||
| 88 | |||
| 89 | return $question; |
||
| 90 | } |
||
| 91 | |||
| 92 | /** |
||
| 93 | * @param array $data |
||
| 94 | * @return \PlaygroundGame\Entity\Game |
||
| 95 | */ |
||
| 96 | public function updateQuestion(array $data, $question) |
||
| 181 | |||
| 182 | public function findRepliesByGame($game) |
||
| 197 | |||
| 198 | public function updatePrediction($question) |
||
| 279 | /** |
||
| 280 | * This function update the sort order of the questions in a Quiz |
||
| 281 | * BEWARE : This function is time consuming (1s for 11 updates) |
||
| 282 | * If you have many replies, switch to a batch |
||
| 283 | * |
||
| 284 | * To improve performance, usage of DQL update |
||
| 285 | * http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html |
||
| 286 | * |
||
| 287 | * @param string $data |
||
| 288 | * @return boolean |
||
| 289 | */ |
||
| 290 | public function updatePredictionOLD($question) |
||
| 291 | { |
||
| 292 | set_time_limit(0); |
||
| 293 | $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default'); |
||
| 294 | |||
| 295 | $replies = $this->findRepliesByGame($question->getQuiz()); |
||
| 296 | |||
| 297 | $answers = $question->getAnswers($question->getQuiz()); |
||
| 298 | |||
| 299 | $answersarray = array(); |
||
| 300 | foreach ($answers as $answer) { |
||
| 301 | $answersarray[$answer->getId()] = $answer; |
||
| 302 | } |
||
| 303 | |||
| 304 | foreach ($replies as $reply) { |
||
| 305 | $quizPoints = 0; |
||
| 306 | $quizCorrectAnswers = 0; |
||
| 307 | |||
| 308 | foreach ($reply->getAnswers() as $quizReplyAnswer) { |
||
| 309 | if (2 != $question->getType() && $quizReplyAnswer->getQuestionId() === $question->getId()) { |
||
| 310 | if ($answersarray[$quizReplyAnswer->getAnswerId()]) { |
||
| 311 | $updatedAnswer = $answersarray[$quizReplyAnswer->getAnswerId()]; |
||
| 312 | $quizReplyAnswer->setPoints($updatedAnswer->getPoints()); |
||
| 313 | $quizReplyAnswer->setCorrect($updatedAnswer->getCorrect()); |
||
| 314 | $q = $em->createQuery(' |
||
| 315 | UPDATE PlaygroundGame\Entity\QuizReplyAnswer a |
||
| 316 | SET a.points = :points, a.correct=:isCorrect |
||
| 317 | WHERE a.id=:answerId |
||
| 318 | '); |
||
| 319 | $q->setParameter('points', $updatedAnswer->getPoints()); |
||
| 320 | $q->setParameter('isCorrect', $updatedAnswer->getCorrect()); |
||
| 321 | $q->setParameter('answerId', $quizReplyAnswer->getId()); |
||
| 322 | $q->execute(); |
||
| 323 | } |
||
| 324 | } elseif ($quizReplyAnswer->getQuestionId() === $question->getId()) { |
||
| 325 | // question is a textarea |
||
| 326 | // search for a matching answer |
||
| 327 | foreach ($answers as $answer) { |
||
| 328 | if (trim(strip_tags($answer->getAnswer())) == trim( |
||
| 329 | strip_tags($quizReplyAnswer->getAnswer()) |
||
| 330 | ) |
||
| 331 | ) { |
||
| 332 | $quizReplyAnswer->setPoints($answer->getPoints()); |
||
| 333 | $quizReplyAnswer->setCorrect($answer->getCorrect()); |
||
| 334 | $q = $em->createQuery(' |
||
| 335 | UPDATE PlaygroundGame\Entity\QuizReplyAnswer a |
||
| 336 | SET a.points = :points, a.correct=:isCorrect |
||
| 337 | WHERE a.id=:answerId |
||
| 338 | '); |
||
| 339 | $q->setParameter('points', $updatedAnswer->getPoints()); |
||
| 340 | $q->setParameter('isCorrect', $updatedAnswer->getCorrect()); |
||
| 341 | $q->setParameter('answerId', $quizReplyAnswer->getId()); |
||
| 342 | $q->execute(); |
||
| 343 | } else { |
||
| 344 | $quizReplyAnswer->setPoints(0); |
||
| 345 | $quizReplyAnswer->setCorrect(false); |
||
| 346 | $q = $em->createQuery(' |
||
| 347 | UPDATE PlaygroundGame\Entity\QuizReplyAnswer a |
||
| 348 | SET a.points = 0, a.correct = false |
||
| 349 | WHERE a.id=:answerId |
||
| 350 | '); |
||
| 351 | $q->setParameter('answerId', $quizReplyAnswer->getId()); |
||
| 352 | $q->execute(); |
||
| 353 | } |
||
| 354 | } |
||
| 355 | } |
||
| 356 | |||
| 357 | // The reply has been updated with correct answers and points for this question. |
||
| 358 | // I count the whole set of points for this reply and update the entry |
||
| 359 | if ($quizReplyAnswer->getCorrect()) { |
||
| 360 | $quizPoints += $quizReplyAnswer->getPoints(); |
||
| 361 | $quizCorrectAnswers += $quizReplyAnswer->getCorrect(); |
||
| 362 | } |
||
| 363 | } |
||
| 364 | |||
| 365 | $winner = $this->isWinner($question->getQuiz(), $quizCorrectAnswers); |
||
| 366 | $reply->getEntry()->setWinner($winner); |
||
| 367 | $reply->getEntry()->setPoints($quizPoints); |
||
| 368 | // The entry should be inactive : entry->setActive(false); |
||
| 369 | $this->getEntryMapper()->update($reply->getEntry()); |
||
| 370 | } |
||
| 371 | |||
| 372 | $this->getEventManager()->trigger( |
||
| 373 | __FUNCTION__ .'.post', |
||
| 374 | $this, |
||
| 375 | array('question' => $question) |
||
| 376 | ); |
||
| 377 | } |
||
| 378 | |||
| 379 | /** |
||
| 380 | * This function update the sort order of the questions in a Quiz |
||
| 381 | * |
||
| 382 | * @param string $data |
||
| 383 | * @return boolean |
||
| 384 | */ |
||
| 385 | public function sortQuestion($data) |
||
| 397 | |||
| 398 | /** |
||
| 399 | * @return string |
||
| 400 | */ |
||
| 401 | public function calculateMaxAnswersQuestion($question) |
||
| 440 | |||
| 441 | public function calculateMaxAnswersQuiz($quiz) |
||
| 454 | |||
| 455 | View Code Duplication | public function getNumberCorrectAnswersQuiz($user, $count = 'count') |
|
| 470 | |||
| 471 | public function createQuizReply($data, $game, $user) |
||
| 613 | |||
| 614 | public function isWinner($game, $quizCorrectAnswers = 0) |
||
| 638 | |||
| 639 | public function getEntriesHeader($game) |
||
| 646 | |||
| 647 | View Code Duplication | public function getEntriesQuery($game) |
|
| 684 | |||
| 685 | public function getGameEntity() |
||
| 689 | |||
| 690 | /** |
||
| 691 | * getQuizMapper |
||
| 692 | * |
||
| 693 | * @return QuizMapperInterface |
||
| 694 | */ |
||
| 695 | public function getQuizMapper() |
||
| 703 | |||
| 704 | /** |
||
| 705 | * setQuizMapper |
||
| 706 | * |
||
| 707 | * @param QuizMapperInterface $quizMapper |
||
| 708 | * @return Game |
||
| 709 | */ |
||
| 710 | public function setQuizMapper(GameMapperInterface $quizMapper) |
||
| 716 | |||
| 717 | /** |
||
| 718 | * getQuizQuestionMapper |
||
| 719 | * |
||
| 720 | * @return QuizQuestionMapperInterface |
||
| 721 | */ |
||
| 722 | public function getQuizQuestionMapper() |
||
| 730 | |||
| 731 | /** |
||
| 732 | * setQuizQuestionMapper |
||
| 733 | * |
||
| 734 | * @param QuizQuestionMapperInterface $quizquestionMapper |
||
| 735 | * @return Quiz |
||
| 736 | */ |
||
| 737 | public function setQuizQuestionMapper($quizquestionMapper) |
||
| 743 | |||
| 744 | /** |
||
| 745 | * setQuizAnswerMapper |
||
| 746 | * |
||
| 747 | * @param QuizAnswerMapperInterface $quizAnswerMapper |
||
| 748 | * @return Quiz |
||
| 749 | */ |
||
| 750 | public function setQuizAnswerMapper($quizAnswerMapper) |
||
| 756 | |||
| 757 | /** |
||
| 758 | * getQuizAnswerMapper |
||
| 759 | * |
||
| 760 | * @return QuizAnswerMapperInterface |
||
| 761 | */ |
||
| 762 | public function getQuizAnswerMapper() |
||
| 770 | |||
| 771 | /** |
||
| 772 | * getQuizReplyMapper |
||
| 773 | * |
||
| 774 | * @return QuizReplyMapperInterface |
||
| 775 | */ |
||
| 776 | public function getQuizReplyMapper() |
||
| 784 | |||
| 785 | /** |
||
| 786 | * setQuizReplyMapper |
||
| 787 | * |
||
| 788 | * @param QuizReplyMapperInterface $quizreplyMapper |
||
| 789 | * @return Quiz |
||
| 790 | */ |
||
| 791 | public function setQuizReplyMapper($quizreplyMapper) |
||
| 797 | |||
| 798 | /** |
||
| 799 | * getQuizReplyAnswerMapper |
||
| 800 | * |
||
| 801 | * @return QuizReplyAnswerMapper |
||
| 802 | */ |
||
| 803 | public function getQuizReplyAnswerMapper() |
||
| 811 | |||
| 812 | /** |
||
| 813 | * setQuizReplyAnswerMapper |
||
| 814 | * |
||
| 815 | * @param QuizReplyAnswerMapper $quizReplyAnswerMapper |
||
| 816 | * @return Quiz |
||
| 817 | */ |
||
| 818 | public function setQuizReplyAnswerMapper($quizReplyAnswerMapper) |
||
| 824 | } |
||
| 825 |
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_functionexpects aPostobject, and outputs the author of the post. The base classPostreturns a simple string and outputting a simple string will work just fine. However, the child classBlogPostwhich is a sub-type ofPostinstead decided to return anobject, and is therefore violating the SOLID principles. If aBlogPostwere passed tomy_function, PHP would not complain, but ultimately fail when executing thestrtouppercall in its body.