HasHtmlAttributes.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Dcat\Admin\Traits;
  3. use Dcat\Admin\Support\Helper;
  4. use Illuminate\Support\Arr;
  5. trait HasHtmlAttributes
  6. {
  7. protected $htmlAttributes = [];
  8. public function defaultHtmlAttribute($attribute, $value)
  9. {
  10. if (! array_key_exists($attribute, $this->htmlAttributes)) {
  11. $this->setHtmlAttribute($attribute, $value);
  12. }
  13. return $this;
  14. }
  15. public function setHtmlAttribute($key, $value = null)
  16. {
  17. if (is_array($key)) {
  18. $this->htmlAttributes = array_merge($this->htmlAttributes, $key);
  19. return $this;
  20. }
  21. $this->htmlAttributes[$key] = $value;
  22. return $this;
  23. }
  24. public function appendHtmlAttribute($key, $value)
  25. {
  26. $result = $this->getHtmlAttribute($key);
  27. if (is_array($result)) {
  28. $result[] = $value;
  29. } else {
  30. $result = "{$result} {$value}";
  31. }
  32. return $this->setHtmlAttribute($key, $result);
  33. }
  34. public function forgetHtmlAttribute($keys)
  35. {
  36. Arr::forget($this->htmlAttributes, $keys);
  37. return $this;
  38. }
  39. public function getHtmlAttributes()
  40. {
  41. return $this->htmlAttributes;
  42. }
  43. public function getHtmlAttribute($key, $default = null)
  44. {
  45. return $this->htmlAttributes[$key] ?? $default;
  46. }
  47. public function hasHtmlAttribute($key)
  48. {
  49. return array_key_exists($key, $this->htmlAttributes);
  50. }
  51. public function formatHtmlAttributes()
  52. {
  53. return Helper::buildHtmlAttributes($this->htmlAttributes);
  54. }
  55. }