Curl.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Analytics\Model\Connector\Http\Client;
  7. use Magento\Analytics\Model\Connector\Http\ConverterInterface;
  8. use Psr\Log\LoggerInterface;
  9. use Magento\Framework\HTTP\Adapter\CurlFactory;
  10. use Magento\Framework\HTTP\ResponseFactory;
  11. /**
  12. * A CURL HTTP client.
  13. *
  14. * Sends requests via a CURL adapter.
  15. */
  16. class Curl implements \Magento\Analytics\Model\Connector\Http\ClientInterface
  17. {
  18. /**
  19. * @var CurlFactory
  20. */
  21. private $curlFactory;
  22. /**
  23. * @var ResponseFactory
  24. */
  25. private $responseFactory;
  26. /**
  27. * @var ConverterInterface
  28. */
  29. private $converter;
  30. /**
  31. * @var LoggerInterface
  32. */
  33. private $logger;
  34. /**
  35. * @param CurlFactory $curlFactory
  36. * @param ResponseFactory $responseFactory
  37. * @param ConverterInterface $converter
  38. * @param LoggerInterface $logger
  39. */
  40. public function __construct(
  41. CurlFactory $curlFactory,
  42. ResponseFactory $responseFactory,
  43. ConverterInterface $converter,
  44. LoggerInterface $logger
  45. ) {
  46. $this->curlFactory = $curlFactory;
  47. $this->responseFactory = $responseFactory;
  48. $this->converter = $converter;
  49. $this->logger = $logger;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function request($method, $url, array $body = [], array $headers = [], $version = '1.1')
  55. {
  56. $response = new \Zend_Http_Response(0, []);
  57. try {
  58. $curl = $this->curlFactory->create();
  59. $headers = $this->applyContentTypeHeaderFromConverter($headers);
  60. $curl->write($method, $url, $version, $headers, $this->converter->toBody($body));
  61. $result = $curl->read();
  62. if ($curl->getErrno()) {
  63. $this->logger->critical(
  64. new \Exception(
  65. sprintf(
  66. 'MBI service CURL connection error #%s: %s',
  67. $curl->getErrno(),
  68. $curl->getError()
  69. )
  70. )
  71. );
  72. return $response;
  73. }
  74. $response = $this->responseFactory->create($result);
  75. } catch (\Exception $e) {
  76. $this->logger->critical($e);
  77. }
  78. return $response;
  79. }
  80. /**
  81. * @param array $headers
  82. *
  83. * @return array
  84. */
  85. private function applyContentTypeHeaderFromConverter(array $headers)
  86. {
  87. $contentTypeHeaderKey = array_search($this->converter->getContentTypeHeader(), $headers);
  88. if ($contentTypeHeaderKey === false) {
  89. $headers[] = $this->converter->getContentTypeHeader();
  90. }
  91. return $headers;
  92. }
  93. }