getFilter('testId'); $data['videoId'] = $this->parseVideoId($data['youtubeUrl']); return parent::initFromForm($data); } protected function parseVideoId($url) { $pattern = '/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/'; $matches = []; if (preg_match($pattern, $url, $matches)) { return $matches[1]; } return null; } protected function _insertDependency() { return $this->_saveDependency(); } protected function _updateDependency() { return $this->_saveDependency(); } protected function _saveDependency() { $this->saveQuestions(Qs_Array::get($this->_data, 'questions', [])); return $this; } protected function saveQuestions(array $questions) { $questionTable = $this->_getTable('TestSlideQuestion'); $questionTable->saveRelations($questions, ['testSlideId' => $this->getPrimaryKey()]); $answerTable = $this->_getTable('TestSlideQuestionAnswer'); foreach ($questions as &$question) { $answerTable->saveRelations($question['answers'], ['questionId' => $question['id']]); $correctAnswerId = Qs_Array::get($question['answers'], "{$question['correctAnswerIndex']}[id]"); $questionTable->updateByKey(['correctAnswerId' => $correctAnswerId], $question['id']); } return $this; } protected function _addDependenciesFromDb(array &$data) { $data['questions'] = $this->getQuestions(['testSlideId' => $this->getPrimaryKey()]); return $this; } protected function getQuestions($key) { $questions = $this->_getTable('TestSlideQuestion')->getList(['id', 'text', 'correctAnswerId'], $key); if (empty($questions)) { return $questions; } $questionIds = array_column($questions, 'id'); $select = $this->_db->select(); $select->from($this->_getPair('TestSlideQuestionAnswer', 'tsqa'), ['questionId', 'id', 'text']); Qs_Db::filter($select, ['questionId' => $questionIds], 'tsqa'); $select->order('sorter'); $group = $this->_db->fetchAll($select, [], Qs_Db::FETCH_GROUP); foreach ($questions as &$question) { $question['answers'] = Qs_Array::get($group, $question['id'], []); if (false !== ($index = Qs_Array::search($question['answers'], ['id' => $question['correctAnswerId']]))) { $question['correctAnswerIndex'] = $index; $question['answers'][$index]['correct'] = $index; } } return $questions; } }