KeyValue.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Form\Field;
  4. use Dcat\Admin\Support\Helper;
  5. use Illuminate\Support\Arr;
  6. class KeyValue extends Field
  7. {
  8. const DEFAULT_FLAG_NAME = '_def_';
  9. /**
  10. * {@inheritdoc}
  11. */
  12. public function formatFieldData($data)
  13. {
  14. $this->data = $data;
  15. return Helper::array(Arr::get($data, $this->normalizeColumn(), $this->value));
  16. }
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public function getValidator(array $input)
  21. {
  22. if ($this->validator) {
  23. return $this->validator->call($this, $input);
  24. }
  25. if (! is_string($this->column)) {
  26. return false;
  27. }
  28. $rules = $attributes = [];
  29. if (! $fieldRules = $this->getRules()) {
  30. return false;
  31. }
  32. if (! Arr::has($input, $this->column)) {
  33. return false;
  34. }
  35. $rules["{$this->column}.keys.*"] = 'distinct';
  36. $rules["{$this->column}.values.*"] = $fieldRules;
  37. $attributes["{$this->column}.keys.*"] = __('Key');
  38. $attributes["{$this->column}.values.*"] = __('Value');
  39. $input = $this->prepareValidatorInput($input);
  40. return validator($input, $rules, $this->getValidationMessages(), $attributes);
  41. }
  42. protected function prepareValidatorInput(array $input)
  43. {
  44. Arr::forget($input, $this->column.'.'.static::DEFAULT_FLAG_NAME);
  45. return $input;
  46. }
  47. protected function prepareInputValue($value)
  48. {
  49. unset($value[static::DEFAULT_FLAG_NAME]);
  50. if (empty($value)) {
  51. return [];
  52. }
  53. return array_combine($value['keys'], $value['values']);
  54. }
  55. public function render()
  56. {
  57. $value = $this->value();
  58. $this->addVariables([
  59. 'count' => $value ? count($value) : 0,
  60. ]);
  61. return parent::render();
  62. }
  63. }