Client.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. <?php
  2. /*
  3. * This file is part of the Goutte package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Goutte;
  11. use GuzzleHttp\Client as GuzzleClient;
  12. use GuzzleHttp\ClientInterface as GuzzleClientInterface;
  13. use GuzzleHttp\Cookie\CookieJar;
  14. use GuzzleHttp\Exception\RequestException;
  15. use Psr\Http\Message\ResponseInterface;
  16. use Psr\Http\Message\UriInterface;
  17. use Symfony\Component\BrowserKit\Client as BaseClient;
  18. use Symfony\Component\BrowserKit\Request;
  19. use Symfony\Component\BrowserKit\Response;
  20. /**
  21. * Client.
  22. *
  23. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  24. * @author Michael Dowling <michael@guzzlephp.org>
  25. * @author Charles Sarrazin <charles@sarraz.in>
  26. * @author Kévin Dunglas <dunglas@gmail.com>
  27. */
  28. class Client extends BaseClient
  29. {
  30. protected $client;
  31. private $headers = array();
  32. private $auth;
  33. public function setClient(GuzzleClientInterface $client)
  34. {
  35. $this->client = $client;
  36. /**
  37. * @var $baseUri UriInterface
  38. */
  39. if (null !== $this->getServerParameter('HTTP_HOST', null) || null === $baseUri = $client->getConfig('base_uri')) {
  40. return $this;
  41. }
  42. $path = $baseUri->getPath();
  43. if ('' !== $path && '/' !== $path) {
  44. throw new \InvalidArgumentException('Setting a path in the Guzzle "base_uri" config option is not supported by Goutte yet.');
  45. }
  46. if (null === $this->getServerParameter('HTTPS', null) && 'https' === $baseUri->getScheme()) {
  47. $this->setServerParameter('HTTPS', 'on');
  48. }
  49. $host = $baseUri->getHost();
  50. if (null !== $port = $baseUri->getPort()) {
  51. $host .= ":$port";
  52. }
  53. $this->setServerParameter('HTTP_HOST', $host);
  54. return $this;
  55. }
  56. public function getClient()
  57. {
  58. if (!$this->client) {
  59. $this->client = new GuzzleClient(array('allow_redirects' => false, 'cookies' => true));
  60. }
  61. return $this->client;
  62. }
  63. public function setHeader($name, $value)
  64. {
  65. $this->headers[strtolower($name)] = $value;
  66. return $this;
  67. }
  68. public function removeHeader($name)
  69. {
  70. unset($this->headers[strtolower($name)]);
  71. }
  72. public function resetHeaders()
  73. {
  74. $this->headers = array();
  75. return $this;
  76. }
  77. /**
  78. * {@inheritdoc}
  79. */
  80. public function restart()
  81. {
  82. parent::restart();
  83. $this->resetAuth()
  84. ->resetHeaders();
  85. }
  86. public function setAuth($user, $password = '', $type = 'basic')
  87. {
  88. $this->auth = array($user, $password, $type);
  89. return $this;
  90. }
  91. public function resetAuth()
  92. {
  93. $this->auth = null;
  94. return $this;
  95. }
  96. /**
  97. * @param Request $request
  98. *
  99. * @return Response
  100. */
  101. protected function doRequest($request)
  102. {
  103. $headers = array();
  104. foreach ($request->getServer() as $key => $val) {
  105. $key = strtolower(str_replace('_', '-', $key));
  106. $contentHeaders = array('content-length' => true, 'content-md5' => true, 'content-type' => true);
  107. if (0 === strpos($key, 'http-')) {
  108. $headers[substr($key, 5)] = $val;
  109. }
  110. // CONTENT_* are not prefixed with HTTP_
  111. elseif (isset($contentHeaders[$key])) {
  112. $headers[$key] = $val;
  113. }
  114. }
  115. $cookies = CookieJar::fromArray(
  116. $this->getCookieJar()->allRawValues($request->getUri()),
  117. parse_url($request->getUri(), PHP_URL_HOST)
  118. );
  119. $requestOptions = array(
  120. 'cookies' => $cookies,
  121. 'allow_redirects' => false,
  122. 'auth' => $this->auth,
  123. );
  124. if (!in_array($request->getMethod(), array('GET', 'HEAD'))) {
  125. if (null !== $content = $request->getContent()) {
  126. $requestOptions['body'] = $content;
  127. } else {
  128. if ($files = $request->getFiles()) {
  129. $requestOptions['multipart'] = [];
  130. $this->addPostFields($request->getParameters(), $requestOptions['multipart']);
  131. $this->addPostFiles($files, $requestOptions['multipart']);
  132. } else {
  133. $requestOptions['form_params'] = $request->getParameters();
  134. }
  135. }
  136. }
  137. if (!empty($headers)) {
  138. $requestOptions['headers'] = $headers;
  139. }
  140. $method = $request->getMethod();
  141. $uri = $request->getUri();
  142. foreach ($this->headers as $name => $value) {
  143. $requestOptions['headers'][$name] = $value;
  144. }
  145. // Let BrowserKit handle redirects
  146. try {
  147. $response = $this->getClient()->request($method, $uri, $requestOptions);
  148. } catch (RequestException $e) {
  149. $response = $e->getResponse();
  150. if (null === $response) {
  151. throw $e;
  152. }
  153. }
  154. return $this->createResponse($response);
  155. }
  156. protected function addPostFiles(array $files, array &$multipart, $arrayName = '')
  157. {
  158. if (empty($files)) {
  159. return;
  160. }
  161. foreach ($files as $name => $info) {
  162. if (!empty($arrayName)) {
  163. $name = $arrayName.'['.$name.']';
  164. }
  165. $file = [
  166. 'name' => $name,
  167. ];
  168. if (is_array($info)) {
  169. if (isset($info['tmp_name'])) {
  170. if ('' !== $info['tmp_name']) {
  171. $file['contents'] = fopen($info['tmp_name'], 'r');
  172. if (isset($info['name'])) {
  173. $file['filename'] = $info['name'];
  174. }
  175. } else {
  176. continue;
  177. }
  178. } else {
  179. $this->addPostFiles($info, $multipart, $name);
  180. continue;
  181. }
  182. } else {
  183. $file['contents'] = fopen($info, 'r');
  184. }
  185. $multipart[] = $file;
  186. }
  187. }
  188. public function addPostFields(array $formParams, array &$multipart, $arrayName = '')
  189. {
  190. foreach ($formParams as $name => $value) {
  191. if (!empty($arrayName)) {
  192. $name = $arrayName.'['.$name.']';
  193. }
  194. if (is_array($value)) {
  195. $this->addPostFields($value, $multipart, $name);
  196. } else {
  197. $multipart[] = [
  198. 'name' => $name,
  199. 'contents' => $value,
  200. ];
  201. }
  202. }
  203. }
  204. protected function createResponse(ResponseInterface $response)
  205. {
  206. return new Response((string) $response->getBody(), $response->getStatusCode(), $response->getHeaders());
  207. }
  208. }