JsonLocation.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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\MessageInterface;
  8. use Psr\Http\Message\RequestInterface;
  9. /**
  10. * Creates a JSON document
  11. */
  12. class JsonLocation extends AbstractLocation
  13. {
  14. /** @var string Whether or not to add a Content-Type header when JSON is found */
  15. private $jsonContentType;
  16. /** @var array */
  17. private $jsonData;
  18. /**
  19. * @param string $locationName Name of the location
  20. * @param string $contentType Content-Type header to add to the request if
  21. * JSON is added to the body. Pass an empty string to omit.
  22. */
  23. public function __construct($locationName = 'json', $contentType = 'application/json')
  24. {
  25. parent::__construct($locationName);
  26. $this->jsonContentType = $contentType;
  27. }
  28. /**
  29. * @param CommandInterface $command
  30. * @param RequestInterface $request
  31. * @param Parameter $param
  32. *
  33. * @return RequestInterface
  34. */
  35. public function visit(
  36. CommandInterface $command,
  37. RequestInterface $request,
  38. Parameter $param
  39. ) {
  40. $this->jsonData[$param->getWireName()] = $this->prepareValue(
  41. $command[$param->getName()],
  42. $param
  43. );
  44. return $request->withBody(Psr7\stream_for(\GuzzleHttp\json_encode($this->jsonData)));
  45. }
  46. /**
  47. * @param CommandInterface $command
  48. * @param RequestInterface $request
  49. * @param Operation $operation
  50. *
  51. * @return MessageInterface
  52. */
  53. public function after(
  54. CommandInterface $command,
  55. RequestInterface $request,
  56. Operation $operation
  57. ) {
  58. $data = $this->jsonData;
  59. $this->jsonData = [];
  60. // Add additional parameters to the JSON document
  61. $additional = $operation->getAdditionalParameters();
  62. if ($additional && ($additional->getLocation() === $this->locationName)) {
  63. foreach ($command->toArray() as $key => $value) {
  64. if (!$operation->hasParam($key)) {
  65. $data[$key] = $this->prepareValue($value, $additional);
  66. }
  67. }
  68. }
  69. // Don't overwrite the Content-Type if one is set
  70. if ($this->jsonContentType && !$request->hasHeader('Content-Type')) {
  71. $request = $request->withHeader('Content-Type', $this->jsonContentType);
  72. }
  73. return $request->withBody(Psr7\stream_for(\GuzzleHttp\json_encode($data)));
  74. }
  75. }