FormParamLocation.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\Psr7;
  7. use Psr\Http\Message\RequestInterface;
  8. /**
  9. * Add form_params to a request
  10. */
  11. class FormParamLocation extends AbstractLocation
  12. {
  13. /** @var string $contentType */
  14. protected $contentType = 'application/x-www-form-urlencoded; charset=utf-8';
  15. /** @var array $formParamsData */
  16. protected $formParamsData = [];
  17. /**
  18. * Set the name of the location
  19. *
  20. * @param string $locationName
  21. */
  22. public function __construct($locationName = 'formParam')
  23. {
  24. parent::__construct($locationName);
  25. }
  26. /**
  27. * @param CommandInterface $command
  28. * @param RequestInterface $request
  29. * @param Parameter $param
  30. *
  31. * @return RequestInterface
  32. */
  33. public function visit(
  34. CommandInterface $command,
  35. RequestInterface $request,
  36. Parameter $param
  37. ) {
  38. $this->formParamsData['form_params'][$param->getWireName()] = $this->prepareValue(
  39. $command[$param->getName()],
  40. $param
  41. );
  42. return $request;
  43. }
  44. /**
  45. * @param CommandInterface $command
  46. * @param RequestInterface $request
  47. * @param Operation $operation
  48. *
  49. * @return RequestInterface
  50. */
  51. public function after(
  52. CommandInterface $command,
  53. RequestInterface $request,
  54. Operation $operation
  55. ) {
  56. $data = $this->formParamsData;
  57. $this->formParamsData = [];
  58. $modify = [];
  59. // Add additional parameters to the form_params array
  60. $additional = $operation->getAdditionalParameters();
  61. if ($additional && $additional->getLocation() == $this->locationName) {
  62. foreach ($command->toArray() as $key => $value) {
  63. if (!$operation->hasParam($key)) {
  64. $data['form_params'][$key] = $this->prepareValue($value, $additional);
  65. }
  66. }
  67. }
  68. $body = http_build_query($data['form_params'], '', '&');
  69. $modify['body'] = Psr7\stream_for($body);
  70. $modify['set_headers']['Content-Type'] = $this->contentType;
  71. $request = Psr7\modify_request($request, $modify);
  72. return $request;
  73. }
  74. }