Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
RestClient.php
Go to the documentation of this file.
1 <?php
7 
11 
16 {
17  const EMPTY_REQUEST_BODY = 'Empty body';
18 
22  private $restBasePath = '/rest/';
23 
25  private $curlClient;
26 
28  private $jsonSerializer;
29 
36  public function __construct(
37  \Magento\TestFramework\TestCase\HttpClient\CurlClient $curlClient = null,
38  \Magento\TestFramework\Helper\JsonSerializer $jsonSerializer = null
39  ) {
41  $this->curlClient = $curlClient ? : $objectManager->get(CurlClient::class);
42  $this->jsonSerializer = $jsonSerializer ? : $objectManager->get(JsonSerializer::class);
43  }
44 
53  public function get($resourcePath, $data = [], $headers = [])
54  {
55  $url = $this->constructResourceUrl($resourcePath);
56  if (!empty($data)) {
57  $url .= '?' . http_build_query($data);
58  }
59 
60  $responseBody = $this->curlClient->get($url, $data, $headers);
61  return $this->jsonSerializer->jsonDecode($responseBody);
62  }
63 
72  public function post($resourcePath, $data, $headers = [])
73  {
74  $url = $this->constructResourceUrl($resourcePath);
75  if (in_array("Content-Type: application/json", $headers)) {
76  // json encode data
77  if ($data != self::EMPTY_REQUEST_BODY) {
78  $data = $this->jsonSerializer->jsonEncode($data);
79  } else {
80  $data = '';
81  }
82  }
83  $responseBody = $this->curlClient->post($url, $data, $headers);
84  return $this->jsonSerializer->jsonDecode($responseBody);
85  }
86 
95  public function put($resourcePath, $data, $headers = [])
96  {
97  $url = $this->constructResourceUrl($resourcePath);
98  if (in_array("Content-Type: application/json", $headers)) {
99  // json encode data
100  if ($data != self::EMPTY_REQUEST_BODY) {
101  $data = $this->jsonSerializer->jsonEncode($data);
102  } else {
103  $data = '';
104  }
105  }
106  $responseBody = $this->curlClient->put($url, $data, $headers);
107  return $this->jsonSerializer->jsonDecode($responseBody);
108  }
109 
117  public function delete($resourcePath, $headers = [])
118  {
119  $url = $this->constructResourceUrl($resourcePath);
120  $responseBody = $this->curlClient->delete($url, $headers);
121  return $this->jsonSerializer->jsonDecode($responseBody);
122  }
123 
129  public function constructResourceUrl($resourcePath)
130  {
131  return rtrim(TESTS_BASE_URL, '/') . $this->restBasePath . ltrim($resourcePath, '/');
132  }
133 }
$objectManager
Definition: bootstrap.php:17
__construct(\Magento\TestFramework\TestCase\HttpClient\CurlClient $curlClient=null, \Magento\TestFramework\Helper\JsonSerializer $jsonSerializer=null)
Definition: RestClient.php:36