UriQueryString.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Illuminate\Support;
  3. use Illuminate\Contracts\Support\Arrayable;
  4. use Illuminate\Support\Traits\InteractsWithData;
  5. use League\Uri\QueryString;
  6. use Stringable;
  7. class UriQueryString implements Arrayable, Stringable
  8. {
  9. use InteractsWithData;
  10. /**
  11. * Create a new URI query string instance.
  12. */
  13. public function __construct(protected Uri $uri)
  14. {
  15. //
  16. }
  17. /**
  18. * Retrieve all data from the instance.
  19. *
  20. * @param mixed $keys
  21. * @return array
  22. */
  23. public function all($keys = null)
  24. {
  25. $query = $this->toArray();
  26. if (! $keys) {
  27. return $query;
  28. }
  29. $results = [];
  30. foreach (is_array($keys) ? $keys : func_get_args() as $key) {
  31. Arr::set($results, $key, Arr::get($query, $key));
  32. }
  33. return $results;
  34. }
  35. /**
  36. * Retrieve data from the instance.
  37. *
  38. * @param string|null $key
  39. * @param mixed $default
  40. * @return mixed
  41. */
  42. protected function data($key = null, $default = null)
  43. {
  44. return $this->get($key, $default);
  45. }
  46. /**
  47. * Get a query string parameter.
  48. */
  49. public function get(?string $key = null, mixed $default = null): mixed
  50. {
  51. return data_get($this->toArray(), $key, $default);
  52. }
  53. /**
  54. * Get the URL decoded version of the query string.
  55. */
  56. public function decode(): string
  57. {
  58. return rawurldecode((string) $this);
  59. }
  60. /**
  61. * Get the string representation of the query string.
  62. */
  63. public function value(): string
  64. {
  65. return (string) $this;
  66. }
  67. /**
  68. * Convert the query string into an array.
  69. */
  70. public function toArray()
  71. {
  72. return QueryString::extract($this->value());
  73. }
  74. /**
  75. * Get the string representation of the query string.
  76. */
  77. public function __toString(): string
  78. {
  79. return (string) $this->uri->getUri()->getQuery();
  80. }
  81. }