MultiPartLocation.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. * Adds POST files to a request
  10. */
  11. class MultiPartLocation extends AbstractLocation
  12. {
  13. /** @var string */
  14. protected $contentType = 'multipart/form-data; boundary=';
  15. /** @var array */
  16. protected $multipartData = [];
  17. /**
  18. * Set the name of the location
  19. *
  20. * @param string $locationName
  21. */
  22. public function __construct($locationName = 'multipart')
  23. {
  24. parent::__construct($locationName);
  25. }
  26. /**
  27. * @return RequestInterface
  28. */
  29. public function visit(
  30. CommandInterface $command,
  31. RequestInterface $request,
  32. Parameter $param
  33. ) {
  34. $this->multipartData[] = [
  35. 'name' => $param->getWireName(),
  36. 'contents' => $this->prepareValue($command[$param->getName()], $param),
  37. ];
  38. return $request;
  39. }
  40. /**
  41. * @return RequestInterface
  42. */
  43. public function after(
  44. CommandInterface $command,
  45. RequestInterface $request,
  46. Operation $operation
  47. ) {
  48. $data = $this->multipartData;
  49. $this->multipartData = [];
  50. $modify = [];
  51. $body = new Psr7\MultipartStream($data);
  52. $modify['body'] = Psr7\Utils::streamFor($body);
  53. $request = Psr7\Utils::modifyRequest($request, $modify);
  54. if ($request->getBody() instanceof Psr7\MultipartStream) {
  55. // Use a multipart/form-data POST if a Content-Type is not set.
  56. $request->withHeader('Content-Type', $this->contentType.$request->getBody()->getBoundary());
  57. }
  58. return $request;
  59. }
  60. }