UpdateConfigValuesRequest.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Http\Requests;
  3. use App\Models\Config;
  4. use Illuminate\Foundation\Http\FormRequest;
  5. /**
  6. * 仅更新配置的值时的验证请求,从配置中收集配置的验证规则来进行验证
  7. *
  8. * @package App\Http\Requests
  9. */
  10. class UpdateConfigValuesRequest extends FormRequest
  11. {
  12. /**
  13. * @var Config[]|\Illuminate\Database\Eloquent\Collection
  14. */
  15. protected $configs;
  16. protected $validationRules = [];
  17. protected $validationAttributes = [];
  18. /**
  19. * Get the validation rules that apply to the request.
  20. *
  21. * @return array
  22. */
  23. public function rules()
  24. {
  25. $this->gatherRulesAndAttributes();
  26. return $this->validationRules;
  27. }
  28. public function getConfigs()
  29. {
  30. if (!$this->configs) {
  31. $this->configs = Config::query()
  32. ->whereIn('slug', $this->keys())
  33. ->get();
  34. }
  35. return $this->configs;
  36. }
  37. /**
  38. * 从数据库中收集本次请求要更新的字段的 name 和 validation_rules
  39. */
  40. protected function gatherRulesAndAttributes()
  41. {
  42. $configs = $this->getConfigs();
  43. $rules = [];
  44. $attributes = [];
  45. foreach ($configs as $config) {
  46. /** @var Config $config */
  47. $rules[$config->slug] = $config->validation_rules ?: 'nullable';
  48. $attributes[$config->slug] = $config->name;
  49. }
  50. $this->validationRules = $rules;
  51. $this->validationAttributes = $attributes;
  52. }
  53. public function attributes()
  54. {
  55. return $this->validationAttributes;
  56. }
  57. }