QueryLocation.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace GuzzleHttp\Command\Guzzle\RequestLocation;
  3. use GuzzleHttp\Command\CommandInterface;
  4. use GuzzleHttp\Command\Guzzle\Operation;
  5. use GuzzleHttp\Command\Guzzle\Parameter;
  6. use GuzzleHttp\Command\Guzzle\QuerySerializer\QuerySerializerInterface;
  7. use GuzzleHttp\Command\Guzzle\QuerySerializer\Rfc3986Serializer;
  8. use GuzzleHttp\Psr7;
  9. use Psr\Http\Message\RequestInterface;
  10. /**
  11. * Adds query string values to requests
  12. */
  13. class QueryLocation extends AbstractLocation
  14. {
  15. /**
  16. * @var QuerySerializerInterface
  17. */
  18. private $querySerializer;
  19. /**
  20. * Set the name of the location
  21. *
  22. * @param string $locationName
  23. */
  24. public function __construct($locationName = 'query', QuerySerializerInterface $querySerializer = null)
  25. {
  26. parent::__construct($locationName);
  27. $this->querySerializer = $querySerializer ?: new Rfc3986Serializer();
  28. }
  29. /**
  30. * @return RequestInterface
  31. */
  32. public function visit(
  33. CommandInterface $command,
  34. RequestInterface $request,
  35. Parameter $param
  36. ) {
  37. $uri = $request->getUri();
  38. $query = Psr7\Query::parse($uri->getQuery());
  39. $query[$param->getWireName()] = $this->prepareValue(
  40. $command[$param->getName()],
  41. $param
  42. );
  43. $uri = $uri->withQuery($this->querySerializer->aggregate($query));
  44. return $request->withUri($uri);
  45. }
  46. /**
  47. * @return RequestInterface
  48. */
  49. public function after(
  50. CommandInterface $command,
  51. RequestInterface $request,
  52. Operation $operation
  53. ) {
  54. $additional = $operation->getAdditionalParameters();
  55. if ($additional && $additional->getLocation() == $this->locationName) {
  56. foreach ($command->toArray() as $key => $value) {
  57. if (!$operation->hasParam($key)) {
  58. $uri = $request->getUri();
  59. $query = Psr7\Query::parse($uri->getQuery());
  60. $query[$key] = $this->prepareValue(
  61. $value,
  62. $additional
  63. );
  64. $uri = $uri->withQuery($this->querySerializer->aggregate($query));
  65. $request = $request->withUri($uri);
  66. }
  67. }
  68. }
  69. return $request;
  70. }
  71. }