1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace App\Http\Requests;
- use App\Models\CustomField;
- use App\Models\Enums\CustomFieldType;
- use Illuminate\Validation\Rule;
- trait CustomFieldRuleHelper
- {
- protected array $groupLabelValue = [];
- public function getGroupLabelValue(string $group, string $key, string $label = null)
- {
- if (! $label) {
- return null;
- }
- return $this->groupLabelValue[$group][$key][$label] ?? null;
- }
- /**
- * @param string $group
- * @param array $keys
- * @param string $inField value,label
- * @return array
- */
- protected function customFieldRuleByGroup(string $group, array $keys = [], string $inField = "value"): array
- {
- $customFields = CustomField::query()
- ->where("group", $group)
- ->when(count($keys) > 0, function ($query) use ($keys) {
- return $query->whereIn("key", $keys);
- })
- ->get();
- $rules = [];
- foreach ($customFields as $customField) {
- $rule = $this->customFieldToRule($customField, $inField);
- if (! $rule) {
- continue;
- }
- $rules[$customField->key]= $rule;
- }
- return $rules;
- }
- protected function customFieldToRule(CustomField $customField, string $inField = "value"): array
- {
- $rule = [];
- if ($customField->required == 1) {
- $rule[] = "required";
- }
- $inOptions = [];
- if ($inField == "value") {
- $inOptions = array_column($customField->options, "value");
- } else {
- foreach ($customField->options as $option) {
- foreach ($option['lang'] as $label) {
- $inOptions[] = $label;
- $this->groupLabelValue[$customField->group][$customField->key][$label] = $option['value'];
- }
- }
- }
- $typeRule = match (CustomFieldType::tryFrom($customField->type)) {
- CustomFieldType::TEXT => "string",
- CustomFieldType::TEXTAREA => "string",
- CustomFieldType::SELECT => $customField->options ? Rule::in($inOptions) : "",
- CustomFieldType::NUMBER => "numeric",
- default => ""
- };
- if ($typeRule) {
- $rule[] = $typeRule;
- }
- return $rule;
- }
- }
|