QueryLocation.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. * @param QuerySerializerInterface|null $querySerializer
  24. */
  25. public function __construct($locationName = 'query', QuerySerializerInterface $querySerializer = null)
  26. {
  27. parent::__construct($locationName);
  28. $this->querySerializer = $querySerializer ?: new Rfc3986Serializer();
  29. }
  30. /**
  31. * @param CommandInterface $command
  32. * @param RequestInterface $request
  33. * @param Parameter $param
  34. *
  35. * @return RequestInterface
  36. */
  37. public function visit(
  38. CommandInterface $command,
  39. RequestInterface $request,
  40. Parameter $param
  41. ) {
  42. $uri = $request->getUri();
  43. $query = Psr7\parse_query($uri->getQuery());
  44. $query[$param->getWireName()] = $this->prepareValue(
  45. $command[$param->getName()],
  46. $param
  47. );
  48. $uri = $uri->withQuery($this->querySerializer->aggregate($query));
  49. return $request->withUri($uri);
  50. }
  51. /**
  52. * @param CommandInterface $command
  53. * @param RequestInterface $request
  54. * @param Operation $operation
  55. *
  56. * @return RequestInterface
  57. */
  58. public function after(
  59. CommandInterface $command,
  60. RequestInterface $request,
  61. Operation $operation
  62. ) {
  63. $additional = $operation->getAdditionalParameters();
  64. if ($additional && $additional->getLocation() == $this->locationName) {
  65. foreach ($command->toArray() as $key => $value) {
  66. if (!$operation->hasParam($key)) {
  67. $uri = $request->getUri();
  68. $query = Psr7\parse_query($uri->getQuery());
  69. $query[$key] = $this->prepareValue(
  70. $value,
  71. $additional
  72. );
  73. $uri = $uri->withQuery($this->querySerializer->aggregate($query));
  74. $request = $request->withUri($uri);
  75. }
  76. }
  77. }
  78. return $request;
  79. }
  80. }