store-manage/app/Admin/Services/Train/PaperService.php

53 lines
1.6 KiB
PHP

<?php
namespace App\Admin\Services\Train;
use App\Admin\Filters\TrianPaperFilter;
use App\Admin\Services\BaseService;
use App\Models\Train\Paper;
class PaperService extends BaseService
{
protected array $withRelationships = ['examination', 'employee'];
protected string $modelName = Paper::class;
protected string $modelFilterName = TrianPaperFilter::class;
/**
* 答题
*
* @param array $answers [[0, 1], [1], [2, 3]]
* @return bool
*/
public function answer(Paper $paper, array $answers)
{
if ($paper->finished_at) {
return $this->setError('已经答过了');
}
$content = [];
$mark = 0;
foreach ($paper->content as $index => $item) {
$options = [];
$item['user_answer'] = data_get($answers, $index, []);
$score = $item['score'];
foreach ($item['options'] as $subIndex => $option) {
$option['selected'] = in_array($subIndex, $item['user_answer']);
if ((! $option['is_true'] && $option['selected']) || ($option['is_true'] && ! $option['selected'])) {
$score = 0;
}
array_push($options, $option);
}
$item['user_score'] = $score;
$item['options'] = $options;
$item['user_right'] = $score == $item['score'];
array_push($content, $item);
$mark += $score;
}
$paper->update(['content' => $content, 'mark' => $mark, 'finished_at' => now()]);
return true;
}
}