Question.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. <?php
  2. namespace app\admin\controller\exam;
  3. use addons\exam\enum\CommonStatus;
  4. use addons\exam\library\FrontService;
  5. use app\admin\model\exam\MaterialQuestionModel;
  6. use app\admin\model\exam\QuestionModel;
  7. use app\common\controller\Backend;
  8. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  9. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  10. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  11. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  12. use think\Db;
  13. use think\exception\PDOException;
  14. use think\exception\ValidateException;
  15. use think\Session;
  16. /**
  17. * 试题
  18. * @icon fa fa-circle-o
  19. */
  20. class Question extends Backend
  21. {
  22. /**
  23. * QuestionModel模型对象
  24. * @var \app\admin\model\exam\QuestionModel
  25. */
  26. protected $model = null;
  27. protected $noNeedRight = ['*'];
  28. protected $multiFields = 'status';
  29. public function _initialize()
  30. {
  31. parent::_initialize();
  32. $this->model = new \app\admin\model\exam\QuestionModel;
  33. $this->view->assign("kindList", $this->model->getKindList());
  34. $this->view->assign("difficultyList", $this->model->getDifficultyList());
  35. $this->view->assign("statusList", $this->model->getStatusList());
  36. }
  37. /**
  38. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  39. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  40. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  41. */
  42. /**
  43. * 查看
  44. */
  45. public function index()
  46. {
  47. //当前是否为关联查询
  48. $this->relationSearch = true;
  49. //设置过滤方法
  50. $this->request->filter(['strip_tags', 'trim']);
  51. if ($this->request->isAjax()) {
  52. //如果发送的来源是Selectpage,则转发到Selectpage
  53. if ($this->request->request('keyField')) {
  54. return $this->selectpage();
  55. }
  56. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  57. $list = $this->model
  58. ->with(['cate'])
  59. ->where($where)
  60. ->order($sort, $order)
  61. ->paginate($limit);
  62. foreach ($list as $row) {
  63. $row->getRelation('cate')->visible(['name']);
  64. }
  65. $result = array("total" => $list->total(), "rows" => $list->items());
  66. return json($result);
  67. }
  68. return $this->view->fetch();
  69. }
  70. /**
  71. * 添加
  72. */
  73. public function add()
  74. {
  75. if ($this->request->isPost()) {
  76. $params = $this->request->post("row/a");
  77. // if ($params['options_extend']) {
  78. // $params['options_extend'] = json_decode(urldecode($params['options_extend']), true);
  79. // }
  80. // dd($params);
  81. if ($params) {
  82. $params = $this->preExcludeFields($params);
  83. // 检查题目输入
  84. $this->checkTitle($params);
  85. // 检查答案输入
  86. $this->checkAnswer($params);
  87. // 处理选项图片链接域名
  88. $this->optionsImage($params);
  89. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  90. $params[$this->dataLimitField] = $this->auth->id;
  91. }
  92. $result = false;
  93. Db::startTrans();
  94. try {
  95. //是否采用模型验证
  96. if ($this->modelValidate) {
  97. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  98. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  99. $this->model->validateFailException(true)->validate($validate);
  100. }
  101. $result = $this->model->allowField(true)->save($params);
  102. // 保存材料题父题目
  103. $this->saveMaterialParentQuestion($this->model);
  104. // 保存材料题子题目
  105. $this->saveMaterialQuestions($this->model, $params['material_questions'] ?? []);
  106. Db::commit();
  107. } catch (ValidateException $e) {
  108. Db::rollback();
  109. $this->error($e->getMessage());
  110. } catch (PDOException $e) {
  111. Db::rollback();
  112. $this->error($e->getMessage());
  113. } catch (Exception $e) {
  114. Db::rollback();
  115. $this->error($e->getMessage());
  116. }
  117. if ($result !== false) {
  118. $this->success();
  119. } else {
  120. $this->error(__('No rows were inserted'));
  121. }
  122. }
  123. $this->error(__('Parameter %s can not be empty', ''));
  124. }
  125. return $this->view->fetch();
  126. }
  127. /**
  128. * 编辑
  129. */
  130. public function edit($ids = null)
  131. {
  132. $row = $this->model->get($ids, [
  133. 'material_questions' => function ($query) {
  134. return $query->with([
  135. 'question' => function ($query) {
  136. return $query->with('cates');
  137. }
  138. ])->order('weigh');
  139. }
  140. ]);
  141. // dd($row->toArray());
  142. if (!$row) {
  143. $this->error(__('No Results were found'));
  144. }
  145. $adminIds = $this->getDataLimitAdminIds();
  146. if (is_array($adminIds)) {
  147. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  148. $this->error(__('You have no permission'));
  149. }
  150. }
  151. if ($this->request->isPost()) {
  152. $params = $this->request->post("row/a");
  153. if ($params) {
  154. $params = $this->preExcludeFields($params);
  155. // 检查题目输入
  156. $this->checkTitle($params);
  157. // 检查答案输入
  158. $this->checkAnswer($params);
  159. // 处理选项图片链接域名
  160. $this->optionsImage($params);
  161. $result = false;
  162. Db::startTrans();
  163. try {
  164. //是否采用模型验证
  165. if ($this->modelValidate) {
  166. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  167. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  168. $row->validateFailException(true)->validate($validate);
  169. }
  170. $result = $row->allowField(true)->save($params);
  171. // 保存材料题父题目
  172. $this->saveMaterialParentQuestion($row);
  173. // 保存材料题子题目
  174. $this->saveMaterialQuestions($row, $params['material_questions'] ?? []);
  175. Db::commit();
  176. } catch (ValidateException $e) {
  177. Db::rollback();
  178. $this->error($e->getMessage());
  179. } catch (PDOException $e) {
  180. Db::rollback();
  181. $this->error($e->getMessage());
  182. } catch (Exception $e) {
  183. Db::rollback();
  184. $this->error($e->getMessage());
  185. }
  186. if ($result !== false) {
  187. $this->success();
  188. } else {
  189. $this->error(__('No rows were updated'));
  190. }
  191. }
  192. $this->error(__('Parameter %s can not be empty', ''));
  193. }
  194. $this->view->assign("row", $row);
  195. return $this->view->fetch();
  196. }
  197. /**
  198. * 选项图片页面
  199. * @return string
  200. */
  201. public function image()
  202. {
  203. if ($this->request->isPost()) {
  204. $this->success($this->request->post());
  205. }
  206. return $this->view->fetch();
  207. }
  208. /**
  209. * 试题导入
  210. */
  211. public function importExcel()
  212. {
  213. if ($this->request->isPost()) {
  214. // parent::import();
  215. $cate = $this->request->param('cate');
  216. // $exam_type = $this->request->param('exam_type');
  217. if (!$cate) { // || !$exam_type
  218. $this->error('请先选择所属类型及考试分类再进行上传');
  219. }
  220. $file = $this->request->request('file');
  221. if (!$file) {
  222. $this->error(__('Parameter %s can not be empty', 'file'));
  223. }
  224. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  225. if (!is_file($filePath)) {
  226. $this->error(__('No results were found'));
  227. }
  228. //实例化reader
  229. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  230. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  231. $this->error(__('Unknown data format'));
  232. }
  233. if ($ext === 'csv') {
  234. $file = fopen($filePath, 'r');
  235. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  236. $fp = fopen($filePath, "w");
  237. $n = 0;
  238. while ($line = fgets($file)) {
  239. $line = rtrim($line, "\n\r\0");
  240. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  241. if ($encoding != 'utf-8') {
  242. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  243. }
  244. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  245. fwrite($fp, $line . "\n");
  246. } else {
  247. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  248. }
  249. $n++;
  250. }
  251. fclose($file) || fclose($fp);
  252. $reader = new Csv();
  253. } elseif ($ext === 'xls') {
  254. $reader = new Xls();
  255. } else {
  256. $reader = new Xlsx();
  257. }
  258. //加载文件
  259. $insert = [];
  260. try {
  261. if (!$PHPExcel = $reader->load($filePath)) {
  262. throw new \Exception(__('Unknown data format'));
  263. }
  264. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  265. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  266. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  267. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  268. $fields = [
  269. 'kind',
  270. 'title',
  271. 'explain',
  272. 'difficulty',
  273. 'answer',
  274. 'A',
  275. 'B',
  276. 'C',
  277. 'D',
  278. 'E',
  279. 'F',
  280. 'G',
  281. 'H',
  282. ];
  283. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  284. $values = [];
  285. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  286. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  287. $values[] = is_null($val) ? '' : $val;
  288. }
  289. // $temp = array_combine($fields, $values);
  290. $row = [];
  291. $options = [];
  292. // 选项及字段组合
  293. for ($i = 0; $i < min($maxColumnNumber, count($fields)); $i++) {
  294. $field = $fields[$i];
  295. $value = $values[$i];
  296. if ($i > 4) {
  297. if (!empty($value) || $value == '0') {
  298. $options[$field] = $value;
  299. }
  300. } else {
  301. $row[$field] = $value;
  302. }
  303. }
  304. // 过滤空行
  305. if (!$row['title']) {
  306. continue;
  307. }
  308. // 特殊字段处理
  309. foreach ($row as $key => $item) {
  310. if ($key == 'kind') {
  311. switch ($item) {
  312. case '判断':
  313. case '判断题':
  314. $item = 'JUDGE';
  315. break;
  316. case '单选':
  317. case '单选题':
  318. $item = 'SINGLE';
  319. break;
  320. case '多选':
  321. case '多选题':
  322. $item = 'MULTI';
  323. break;
  324. case '填空':
  325. case '填空题':
  326. $item = 'FILL';
  327. break;
  328. case '简答':
  329. case '简答题':
  330. $item = 'SHORT';
  331. break;
  332. }
  333. } else if ($key == 'difficulty') {
  334. switch ($item) {
  335. case '低':
  336. case '简单':
  337. $item = 'EASY';
  338. break;
  339. case '高':
  340. case '困难':
  341. $item = 'HARD';
  342. break;
  343. default:
  344. $item = 'GENERAL';
  345. break;
  346. }
  347. }
  348. $row[$key] = $item;
  349. }
  350. // 判断题特殊情况处理
  351. if ($row['kind'] == 'JUDGE') {
  352. switch ($row['answer']) {
  353. case '正确':
  354. case '对':
  355. $row['answer'] = 'A';
  356. break;
  357. case '错误':
  358. case '错':
  359. $row['answer'] = 'B';
  360. break;
  361. }
  362. $options = $options ? $options : ['A' => '正确', 'B' => '错误'];
  363. }
  364. // 答案特殊处理
  365. $row['answer'] = str_replace(' ', '', $row['answer']);
  366. $row['answer'] = str_replace(' ', '', $row['answer']);
  367. $row['answer'] = str_replace(',', ',', $row['answer']);
  368. if (!$row['answer'] || ($row['kind'] == 'MULTI' && !strpos($row['answer'], ','))) {
  369. throw new \Exception('题目【' . $row['title'] . '】答案格式有误');
  370. }
  371. // 填空题
  372. if ($row['kind'] == 'FILL') {
  373. $row['answer'] = explode('|||', $row['answer']);
  374. $fill_count = count(explode('______', $row['title'])) - 1;
  375. $answer_count = count($row['answer']);
  376. if ($fill_count != $answer_count) {
  377. throw new \Exception('题目【' . $row['title'] . '】填空位与答案数量不匹配');
  378. }
  379. $fill_answers = [];
  380. foreach ($row['answer'] as $item) {
  381. $fill_answers[] = ['answers' => explode(',', $item)];
  382. }
  383. $row['answer'] = json_encode($fill_answers, JSON_UNESCAPED_UNICODE);
  384. }
  385. // 简答题
  386. if ($row['kind'] == 'SHORT') {
  387. $row['answer'] = explode('|||', $row['answer']);
  388. if ($row['answer']) {
  389. $short_answers = [
  390. 'answer' => $row['answer'][0],
  391. 'config' => [],
  392. ];
  393. if (isset($row['answer'][1]) && $row['answer'][1]) {
  394. $keywords = explode(',', str_replace(',', ',', $row['answer'][1]));
  395. foreach ($keywords as $keyword) {
  396. $short_answers['config'][] = [
  397. 'answer' => $keyword,
  398. 'score' => 1,
  399. ];
  400. }
  401. }
  402. $row['answer'] = json_encode($short_answers, JSON_UNESCAPED_UNICODE);
  403. }
  404. }
  405. $row['options_json'] = json_encode($options, JSON_UNESCAPED_UNICODE);
  406. $row['cate_id'] = $cate;
  407. // $row['exam_type_id'] = $exam_type;
  408. $insert[] = $row;
  409. }
  410. Session::set('import_question', $insert);
  411. } catch (\Exception $exception) {
  412. $this->error($exception->getMessage());
  413. }
  414. if (!$insert) {
  415. $this->error(__('No rows were updated'));
  416. }
  417. $this->success('识别成功', '', ['count' => count($insert)]);
  418. }
  419. $this->error('错误的提交方式');
  420. }
  421. /**
  422. * 试题导入提交
  423. * @return string|void
  424. */
  425. public function import()
  426. {
  427. if ($this->request->isPost()) {
  428. // 加载数据
  429. $insert = Session::pull('import_question');
  430. if (!$insert) {
  431. $this->error(__('没有可以导入的数据,请重新上传Excel文件'));
  432. }
  433. try {
  434. $this->model->saveAll($insert);
  435. } catch (PDOException $exception) {
  436. $msg = $exception->getMessage();
  437. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  438. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  439. };
  440. $this->error($msg);
  441. } catch (\Exception $exception) {
  442. $this->error($exception->getMessage());
  443. }
  444. $this->success();
  445. }
  446. return $this->view->fetch();
  447. }
  448. /**
  449. * 获取题库数量
  450. */
  451. public function getCount()
  452. {
  453. $cate_ids = $this->request->param('cate_ids');
  454. if (!$cate_ids) {
  455. $this->error('请先选择题库');
  456. }
  457. $this->success('', '', $this->model->getCount($cate_ids));
  458. }
  459. /**
  460. * 选择题目页面
  461. */
  462. public function select()
  463. {
  464. //当前是否为关联查询
  465. $this->relationSearch = true;
  466. //设置过滤方法
  467. $this->request->filter(['strip_tags', 'trim']);
  468. if ($this->request->isAjax()) {
  469. //如果发送的来源是Selectpage,则转发到Selectpage
  470. if ($this->request->request('keyField')) {
  471. return $this->selectpage();
  472. }
  473. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  474. $list = $this->model
  475. ->with(['cate'])
  476. ->where($where)
  477. ->order($sort, $order)
  478. ->paginate($limit);
  479. foreach ($list as $row) {
  480. $row->getRelation('cate')->visible(['name']);
  481. }
  482. $rows = $list->items();
  483. foreach ($rows as &$row) {
  484. $row['title'] = strip_tags($row['title']);
  485. }
  486. $result = array("total" => $list->total(), "rows" => $rows);
  487. return json($result);
  488. }
  489. return $this->view->fetch();
  490. }
  491. public function test()
  492. {
  493. $this->success('', '', Session::get('import_question'));
  494. }
  495. /**
  496. * 检查答案输入
  497. * @param $params
  498. */
  499. protected function checkAnswer(&$params)
  500. {
  501. $answer = $params['answer'] ?? '';
  502. $options = $params['options_json'] ?? [];
  503. if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
  504. if (!$answer) {
  505. $this->error('请设置题目答案');
  506. }
  507. if (!$options) {
  508. $this->error('请设置题目选项');
  509. }
  510. $options = json_decode($options, true);
  511. $option_keys = array_keys($options);
  512. // 多选题
  513. if (strpos($answer, ',') !== false) {
  514. $answer_arr = explode(',', trim($answer));
  515. foreach ($answer_arr as $item) {
  516. if (!in_array($item, $option_keys)) {
  517. $this->error('答案设置有误,答案选项不存在');
  518. }
  519. }
  520. } else {
  521. if (!in_array($answer, $option_keys)) {
  522. $this->error('答案设置有误,答案选项不存在');
  523. }
  524. }
  525. }
  526. // 后期拓展题型
  527. switch ($params['kind']) {
  528. // 填空题
  529. case 'FILL':
  530. if (!is_array($answer) || !count($answer)) {
  531. $this->error('未设置填空题答案,至少设置一个');
  532. }
  533. // 转json
  534. $params['answer'] = json_encode($params['answer'], JSON_UNESCAPED_UNICODE);
  535. break;
  536. // 简答题
  537. case 'SHORT':
  538. $answer = $params['short_answer'] ?? '';
  539. if (!$answer) {
  540. $this->error('请设置简答题标准答案');
  541. }
  542. $answer_config = $params['answer_config'] ?? [];
  543. if (!$answer_config) {
  544. $this->error('请设置简答题答案关键词');
  545. }
  546. foreach ($answer_config as &$item) {
  547. if (!$item['answer']) {
  548. $this->error('简答题答案关键词不能为空');
  549. }
  550. if (!is_numeric($item['score']) || $item['score'] < 0) {
  551. $this->error('简答题分数设置有误,必须为数字且不能小于0');
  552. }
  553. // $item['score'] = 0;
  554. }
  555. // 转json
  556. $params['answer'] = json_encode([
  557. 'answer' => $answer,
  558. 'config' => $answer_config
  559. ], JSON_UNESCAPED_UNICODE);
  560. break;
  561. // 材料题
  562. case 'MATERIAL':
  563. // dd([$params, $answer, $options]);
  564. if ($params['is_material_child']) {
  565. $this->error('题型设置有误,材料题不能再设置为材料题的子题');
  566. }
  567. $params['is_material_child'] = 0;
  568. $params['material_question_id'] = 0;
  569. $params['material_questions'] = $params['material_questions'] ? json_decode($params['material_questions'], true) : [];
  570. if (!$params['material_questions']) {
  571. if ($params['status'] == CommonStatus::NORMAL) {
  572. $this->error('请设置材料题的子题(或者状态先设置隐藏)');
  573. }
  574. }
  575. // foreach ($params['material_questions'] as $material_question) {
  576. // if ($material_question['kind'] == 'MATERIAL') {
  577. // $this->error('材料题的子题不能为材料题');
  578. // }
  579. // }
  580. // 转json
  581. $params['answer'] = json_encode([
  582. 'questions' => $params['material_questions']
  583. ], JSON_UNESCAPED_UNICODE);
  584. break;
  585. }
  586. if ($params['is_material_child']) {
  587. $params['material_question_id'] = $params['material_question_id'] ?? 0;
  588. if (!$params['material_question_id']) {
  589. $this->error('请设置材料题的父题');
  590. }
  591. if ($params['material_score'] <= 0) {
  592. $this->error('请设置材料题子题的分数');
  593. }
  594. }
  595. }
  596. /**
  597. * 保存材料题父题
  598. * @param $question
  599. * @return void
  600. */
  601. protected function saveMaterialParentQuestion($question)
  602. {
  603. if (!$question || !$question['is_material_child'] || $question['kind'] == 'MATERIAL') {
  604. return;
  605. }
  606. if ($parentQuestion = QuestionModel::where('id', $question['material_question_id'])
  607. ->where('kind', 'MATERIAL')
  608. ->find()) {
  609. $answer = json_decode($parentQuestion->answer, true);
  610. if (!$answer) {
  611. $answer = [
  612. 'questions' => [
  613. [
  614. 'id' => $question['id'],
  615. 'score' => $question['material_score'],
  616. 'answer' => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
  617. 'answer_config' => null,
  618. ]
  619. ],
  620. ];
  621. } else {
  622. $has_child = false;
  623. foreach ($answer['questions'] as &$child_question) {
  624. if ($child_question['id'] == $question['id']) {
  625. $has_child = true;
  626. $child_question['score'] = $question['material_score'];
  627. $child_question['answer'] = is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'];
  628. break;
  629. }
  630. }
  631. if (!$has_child) {
  632. $answer['questions'][] = [
  633. 'id' => $question['id'],
  634. 'score' => $question['material_score'],
  635. 'answer' => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
  636. 'answer_config' => null,
  637. ];
  638. }
  639. }
  640. // 材料题父题答案追加子题设置
  641. $parentQuestion->answer = json_encode($answer, JSON_UNESCAPED_UNICODE);
  642. $parentQuestion->save();
  643. if ($materialQuestion = MaterialQuestionModel::where('parent_question_id', $question['material_question_id'])
  644. ->where('question_id', $question['id'])
  645. ->find()) {
  646. $materialQuestion->score = $question['material_score'];
  647. $materialQuestion->answer = is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'];
  648. $materialQuestion->save();
  649. } else {
  650. // 保存材料题子题关联
  651. MaterialQuestionModel::create([
  652. 'parent_question_id' => $question['material_question_id'],
  653. 'question_id' => $question['id'],
  654. 'score' => $question['material_score'],
  655. 'answer' => $question['answer'],
  656. 'weigh' => 0,
  657. ]);
  658. }
  659. } else {
  660. $this->error('未找到所属材料题');
  661. }
  662. }
  663. /**
  664. * 保存材料题子题
  665. * @param $parentQuestion
  666. * @param $questions
  667. * @return void
  668. */
  669. protected function saveMaterialQuestions($parentQuestion, $questions)
  670. {
  671. if (!$parentQuestion || $parentQuestion['kind'] != 'MATERIAL' || !$questions) {
  672. return;
  673. }
  674. // 删除旧的子题
  675. MaterialQuestionModel::where('parent_question_id', $parentQuestion->id)->delete();
  676. // 保存新的子题
  677. $inserts = [];
  678. foreach ($questions as $key => $question) {
  679. $inserts[] = [
  680. 'parent_question_id' => $parentQuestion->id,
  681. 'question_id' => $question['id'],
  682. 'score' => $question['score'],
  683. 'answer' => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
  684. 'weigh' => $key,
  685. 'createtime' => time(),
  686. ];
  687. }
  688. (new MaterialQuestionModel())->saveAll($inserts);
  689. }
  690. /**
  691. * 处理选项图片链接域名
  692. * @param $data
  693. */
  694. protected function optionsImage(&$data)
  695. {
  696. $options_img = $data['options_img'] ?? null;
  697. $options_img = json_decode($options_img, true);
  698. if ($options_img) {
  699. foreach ($options_img as &$item) {
  700. if (strpos($item['value'], '://') === false) {
  701. $item['value'] = cdnurl($item['value'], true);
  702. }
  703. }
  704. }
  705. $data['options_img'] = json_encode($options_img);
  706. }
  707. /**
  708. * 检查题目内容输入
  709. * @param $params
  710. */
  711. protected function checkTitle(&$params)
  712. {
  713. if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
  714. if (!($params['title'] ?? '')) {
  715. $this->error('请输入题目内容');
  716. }
  717. } else if ($params['kind'] == 'FILL') {
  718. if (!($params['title_fill'] ?? '')) {
  719. $this->error('请输入填空题题目内容');
  720. }
  721. $params['title'] = $params['title_fill'];
  722. }
  723. // 替换题目图片CDN链接
  724. $params['title'] = FrontService::replaceImgUrl($params['title']);
  725. }
  726. }