QueryBag.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. declare(strict_types=1);
  3. namespace Enqueue\Dsn;
  4. class QueryBag
  5. {
  6. /**
  7. * @var array
  8. */
  9. private $query;
  10. public function __construct(array $query)
  11. {
  12. $this->query = $query;
  13. }
  14. public function toArray(): array
  15. {
  16. return $this->query;
  17. }
  18. public function getString(string $name, string $default = null): ?string
  19. {
  20. return array_key_exists($name, $this->query) ? $this->query[$name] : $default;
  21. }
  22. public function getDecimal(string $name, int $default = null): ?int
  23. {
  24. $value = $this->getString($name);
  25. if (null === $value) {
  26. return $default;
  27. }
  28. if (false == preg_match('/^[\+\-]?[0-9]*$/', $value)) {
  29. throw InvalidQueryParameterTypeException::create($name, 'decimal');
  30. }
  31. return (int) $value;
  32. }
  33. public function getOctal(string $name, int $default = null): ?int
  34. {
  35. $value = $this->getString($name);
  36. if (null === $value) {
  37. return $default;
  38. }
  39. if (false == preg_match('/^0[\+\-]?[0-7]*$/', $value)) {
  40. throw InvalidQueryParameterTypeException::create($name, 'octal');
  41. }
  42. return intval($value, 8);
  43. }
  44. public function getFloat(string $name, float $default = null): ?float
  45. {
  46. $value = $this->getString($name);
  47. if (null === $value) {
  48. return $default;
  49. }
  50. if (false == is_numeric($value)) {
  51. throw InvalidQueryParameterTypeException::create($name, 'float');
  52. }
  53. return (float) $value;
  54. }
  55. public function getBool(string $name, bool $default = null): ?bool
  56. {
  57. $value = $this->getString($name);
  58. if (null === $value) {
  59. return $default;
  60. }
  61. if (in_array($value, ['', '0', 'false'], true)) {
  62. return false;
  63. }
  64. if (in_array($value, ['1', 'true'], true)) {
  65. return true;
  66. }
  67. throw InvalidQueryParameterTypeException::create($name, 'bool');
  68. }
  69. public function getArray(string $name, array $default = []): self
  70. {
  71. if (false == array_key_exists($name, $this->query)) {
  72. return new self($default);
  73. }
  74. $value = $this->query[$name];
  75. if (is_array($value)) {
  76. return new self($value);
  77. }
  78. throw InvalidQueryParameterTypeException::create($name, 'array');
  79. }
  80. }