CustomFieldRuleHelper.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Http\Requests;
  3. use App\Models\CustomField;
  4. use App\Models\Enums\CustomFieldType;
  5. use Illuminate\Validation\Rule;
  6. trait CustomFieldRuleHelper
  7. {
  8. protected array $groupLabelValue = [];
  9. public function getGroupLabelValue(string $group, string $key, string $label = null)
  10. {
  11. if (! $label) {
  12. return null;
  13. }
  14. return $this->groupLabelValue[$group][$key][$label] ?? null;
  15. }
  16. /**
  17. * @param string $group
  18. * @param array $keys
  19. * @param string $inField value,label
  20. * @return array
  21. */
  22. protected function customFieldRuleByGroup(string $group, array $keys = [], string $inField = "value"): array
  23. {
  24. $customFields = CustomField::query()
  25. ->where("group", $group)
  26. ->when(count($keys) > 0, function ($query) use ($keys) {
  27. return $query->whereIn("key", $keys);
  28. })
  29. ->get();
  30. $rules = [];
  31. foreach ($customFields as $customField) {
  32. $rule = $this->customFieldToRule($customField, $inField);
  33. if (! $rule) {
  34. continue;
  35. }
  36. $rules[$customField->key]= $rule;
  37. }
  38. return $rules;
  39. }
  40. protected function customFieldToRule(CustomField $customField, string $inField = "value"): array
  41. {
  42. $rule = [];
  43. if ($customField->required == 1) {
  44. $rule[] = "required";
  45. }
  46. $inOptions = [];
  47. if ($inField == "value") {
  48. $inOptions = array_column($customField->options, "value");
  49. } else {
  50. foreach ($customField->options as $option) {
  51. foreach ($option['lang'] as $label) {
  52. $inOptions[] = $label;
  53. $this->groupLabelValue[$customField->group][$customField->key][$label] = $option['value'];
  54. }
  55. }
  56. }
  57. $typeRule = match (CustomFieldType::tryFrom($customField->type)) {
  58. CustomFieldType::TEXT => "string",
  59. CustomFieldType::TEXTAREA => "string",
  60. CustomFieldType::SELECT => $customField->options ? Rule::in($inOptions) : "",
  61. CustomFieldType::NUMBER => "numeric",
  62. default => ""
  63. };
  64. if ($typeRule) {
  65. $rule[] = $typeRule;
  66. }
  67. return $rule;
  68. }
  69. }