1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
<?php
/*
* Copyright (C) 2013-2016 Mailgun
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace Mailgun;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Message\MultipartStream\MultipartStreamBuilder;
use Http\Message\RequestFactory;
use Psr\Http\Message\RequestInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class RequestBuilder
{
/**
* @var RequestFactory
*/
private $requestFactory;
/**
* @var MultipartStreamBuilder
*/
private $multipartStreamBuilder;
/**
* Creates a new PSR-7 request.
*
* @param string $method
* @param string $uri
* @param array $headers
* @param array|string|null $body Request body. If body is an array we will send a as multipart stream request.
* If array, each array *item* MUST look like:
* array (
* 'content' => string|resource|StreamInterface,
* 'name' => string,
* 'filename'=> string (optional)
* 'headers' => array (optinal) ['header-name' => 'header-value']
* )
*
* @return RequestInterface
*/
public function create($method, $uri, array $headers = [], $body = null)
{
if (!is_array($body)) {
return $this->getRequestFactory()->createRequest($method, $uri, $headers, $body);
}
$builder = $this->getMultipartStreamBuilder();
foreach ($body as $item) {
$name = $item['name'];
$content = $item['content'];
unset($item['name']);
unset($item['content']);
$builder->addResource($name, $content, $item);
}
$multipartStream = $builder->build();
$boundary = $builder->getBoundary();
$builder->reset();
$headers['Content-Type'] = 'multipart/form-data; boundary="'.$boundary.'"';
return $this->getRequestFactory()->createRequest($method, $uri, $headers, $multipartStream);
}
/**
* @return RequestFactory
*/
private function getRequestFactory()
{
if ($this->requestFactory === null) {
$this->requestFactory = MessageFactoryDiscovery::find();
}
return $this->requestFactory;
}
/**
* @param RequestFactory $requestFactory
*
* @return RequestBuilder
*/
public function setRequestFactory($requestFactory)
{
$this->requestFactory = $requestFactory;
return $this;
}
/**
* @return MultipartStreamBuilder
*/
private function getMultipartStreamBuilder()
{
if ($this->multipartStreamBuilder === null) {
$this->multipartStreamBuilder = new MultipartStreamBuilder();
}
return $this->multipartStreamBuilder;
}
/**
* @param MultipartStreamBuilder $multipartStreamBuilder
*
* @return RequestBuilder
*/
public function setMultipartStreamBuilder($multipartStreamBuilder)
{
$this->multipartStreamBuilder = $multipartStreamBuilder;
return $this;
}
}
|