12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- namespace App\Model;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Facades\Log;
- class MedicalCalculator extends Model
- {
- protected $table = 'medical_calculators';
- public $timestamps = false;
- protected $fillable = [
- 'name', 'disease_name', 'formula', 'instructions', 'results'
- ];
- // 移除 results 的 cast,因为我们将手动处理它
- // protected $casts = [
- // 'results' => 'array',
- // ];
- public function questions()
- {
- return $this->hasMany(MedicalQuestion::class, 'medical_calculator_id');
- }
- public function calculateResult($inputs)
- {
- $formula = $this->formula;
- // 获取公式中的所有变量名
- preg_match_all('/\b([a-zA-Z_]\w*)\b/', $formula, $matches);
- $formulaVariables = array_unique($matches[1]);
- foreach ($formulaVariables as $variable) {
- if (!isset($inputs[$variable])) {
- throw new \Exception("Missing input for variable: {$variable}");
- }
- if (!is_numeric($inputs[$variable])) {
- throw new \Exception("Non-numeric input for variable: {$variable}");
- }
- // 使用正则表达式确保只替换完整的变量名
- $formula = preg_replace('/\b' . preg_quote($variable, '/') . '\b/', $inputs[$variable], $formula);
- }
- // 使用 eval() 可能存在安全风险,建议使用更安全的表达式解析库
- $result = eval('return ' . $formula . ';');
- return $result;
- }
- protected $casts = [
- 'results' => 'array',
- ];
- public function setResultsAttribute($value)
- {
-
- if (is_array($value)) {
- $this->attributes['results'] = json_encode(array_values($value));
- } elseif (is_string($value)) {
- $decoded = json_decode($value, true);
- if (is_array($decoded)) {
- $this->attributes['results'] = json_encode(array_values($decoded));
- } else {
- $this->attributes['results'] = '[]';
- }
- } else {
- $this->attributes['results'] = '[]';
- }
-
- }
- public function getResultsAttribute($value)
- {
-
- if (is_string($value)) {
- $decoded = json_decode($value, true);
- $result = is_array($decoded) ? array_values($decoded) : [];
- } else {
- $result = is_array($value) ? array_values($value) : [];
- }
-
- return $result;
- }
- }
|