MedicalCalculator.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Model;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Facades\Log;
  5. class MedicalCalculator extends Model
  6. {
  7. protected $table = 'medical_calculators';
  8. public $timestamps = false;
  9. protected $fillable = [
  10. 'name', 'disease_name', 'formula', 'instructions', 'results'
  11. ];
  12. // 移除 results 的 cast,因为我们将手动处理它
  13. // protected $casts = [
  14. // 'results' => 'array',
  15. // ];
  16. public function questions()
  17. {
  18. return $this->hasMany(MedicalQuestion::class, 'medical_calculator_id');
  19. }
  20. public function calculateResult($inputs)
  21. {
  22. $formula = $this->formula;
  23. // 获取公式中的所有变量名
  24. preg_match_all('/\b([a-zA-Z_]\w*)\b/', $formula, $matches);
  25. $formulaVariables = array_unique($matches[1]);
  26. foreach ($formulaVariables as $variable) {
  27. if (!isset($inputs[$variable])) {
  28. throw new \Exception("Missing input for variable: {$variable}");
  29. }
  30. if (!is_numeric($inputs[$variable])) {
  31. throw new \Exception("Non-numeric input for variable: {$variable}");
  32. }
  33. // 使用正则表达式确保只替换完整的变量名
  34. $formula = preg_replace('/\b' . preg_quote($variable, '/') . '\b/', $inputs[$variable], $formula);
  35. }
  36. // 使用 eval() 可能存在安全风险,建议使用更安全的表达式解析库
  37. $result = eval('return ' . $formula . ';');
  38. return $result;
  39. }
  40. protected $casts = [
  41. 'results' => 'array',
  42. ];
  43. public function setResultsAttribute($value)
  44. {
  45. if (is_array($value)) {
  46. $this->attributes['results'] = json_encode(array_values($value));
  47. } elseif (is_string($value)) {
  48. $decoded = json_decode($value, true);
  49. if (is_array($decoded)) {
  50. $this->attributes['results'] = json_encode(array_values($decoded));
  51. } else {
  52. $this->attributes['results'] = '[]';
  53. }
  54. } else {
  55. $this->attributes['results'] = '[]';
  56. }
  57. }
  58. public function getResultsAttribute($value)
  59. {
  60. if (is_string($value)) {
  61. $decoded = json_decode($value, true);
  62. $result = is_array($decoded) ? array_values($decoded) : [];
  63. } else {
  64. $result = is_array($value) ? array_values($value) : [];
  65. }
  66. return $result;
  67. }
  68. }