Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CurlClientWithCookies.php
Go to the documentation of this file.
1 <?php
8 
11 
16 {
17  const COOKIE_HEADER = 'Set-Cookie: ';
18 
20  protected $curlClient;
21 
23  protected $jsonSerializer;
24 
31  public function __construct(
33  \Magento\TestFramework\Helper\JsonSerializer $jsonSerializer
34  ) {
36  $this->curlClient = $curlClient ? : $objectManager->get(CurlClient::class);
37  $this->jsonSerializer = $jsonSerializer ? : $objectManager->get(JsonSerializer::class);
38  }
39 
45  public function constructResourceUrl($resourcePath)
46  {
47  return rtrim(TESTS_BASE_URL, '/') . '/' . ltrim($resourcePath, '/');
48  }
49 
58  public function get($resourcePath, $data = [], $headers = [])
59  {
60  $url = $this->constructResourceUrl($resourcePath);
61  if (!empty($data)) {
62  $url .= '?' . http_build_query($data);
63  }
64 
65  $curlOpts = [];
66  $curlOpts[CURLOPT_CUSTOMREQUEST] = \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET;
67  $curlOpts[CURLOPT_SSLVERSION] = 3;
68  $response = $this->curlClient->invokeApi($url, $curlOpts, $headers);
69  $response['cookies'] = $this->cookieParse($response['header']);
70  return $response;
71  }
72 
88  private function cookieParse($headerBlock)
89  {
90  $header = explode("\r\n", $headerBlock);
91  $cookies = [];
92  foreach ($header as $line) {
93  $line = trim($line);
94  if (substr($line, 0, strlen(self::COOKIE_HEADER)) == self::COOKIE_HEADER) {
95  $line = trim(substr($line, strlen(self::COOKIE_HEADER)));
96  $cookieData = [];
97  // Check if cookie contains attributes
98  if (strpos($line, ';') === false) {
99  // no attributes, just name and value
100  list($cookieData['name'], $cookieData['value']) = explode('=', $line);
101  } else {
102  // has attributes, must parse them out and loop through
103  list($nvPair, $cookieMetadata) = explode(';', $line, 2);
104  list($cookieData['name'], $cookieData['value']) = explode('=', $nvPair);
105  $rawCookieData = explode(';', $cookieMetadata);
106  foreach ($rawCookieData as $keyValuePairs) {
107  list($key, $value) = array_merge(explode('=', $keyValuePairs), ['true']);
108  $cookieData[strtolower(trim($key))] = trim($value);
109  }
110  }
111  $cookies[] = $cookieData;
112  }
113  }
114  return $cookies;
115  }
116 }
$response
Definition: 404.php:11
$objectManager
Definition: bootstrap.php:17
$value
Definition: gender.phtml:16
__construct(CurlClient $curlClient, \Magento\TestFramework\Helper\JsonSerializer $jsonSerializer)