Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
HttpClientFactory.php
Go to the documentation of this file.
1 <?php
7 
9 use Magento\Framework\HTTP\ZendClientFactory;
12 
18 {
24  private static $authorizationType = 'Authorization';
25 
31  private static $jsonDataType = 'application/json';
32 
36  private static $urlSeparator = '/';
37 
41  private $config;
42 
46  private $clientFactory;
47 
51  private $dataEncoder;
52 
60  public function __construct(
61  Config $config,
62  ZendClientFactory $clientFactory,
63  EncoderInterface $dataEncoder
64  ) {
65  $this->config = $config;
66  $this->clientFactory = $clientFactory;
67  $this->dataEncoder = $dataEncoder;
68  }
69 
79  public function create($url, $method, array $params = [], $storeId = null): ZendClient
80  {
81  $apiKey = $this->getApiKey($storeId);
82  $apiUrl = $this->buildFullApiUrl($url, $storeId);
83 
84  $client = $this->createNewClient();
85  $client->setHeaders(
86  self::$authorizationType,
87  sprintf('Basic %s', base64_encode($apiKey))
88  );
89  if (!empty($params)) {
90  $encodedData = $this->dataEncoder->encode($params);
91  $client->setRawData($encodedData, self::$jsonDataType);
92  }
93  $client->setMethod($method);
94  $client->setUri($apiUrl);
95 
96  return $client;
97  }
98 
102  private function createNewClient()
103  {
104  return $this->clientFactory->create();
105  }
106 
114  private function getApiKey($storeId): string
115  {
116  return $this->config->getApiKey($storeId);
117  }
118 
126  private function buildFullApiUrl($url, $storeId): string
127  {
128  $baseApiUrl = $this->getBaseApiUrl($storeId);
129  $fullUrl = $baseApiUrl . self::$urlSeparator . ltrim($url, self::$urlSeparator);
130 
131  return $fullUrl;
132  }
133 
140  private function getBaseApiUrl($storeId): string
141  {
142  $baseApiUrl = $this->config->getApiUrl($storeId);
143 
144  return rtrim($baseApiUrl, self::$urlSeparator);
145  }
146 }
__construct(Config $config, ZendClientFactory $clientFactory, EncoderInterface $dataEncoder)
$config
Definition: fraud_order.php:17
$method
Definition: info.phtml:13
create($url, $method, array $params=[], $storeId=null)
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18