-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathEntityRESTApiHelper.php
112 lines (98 loc) · 2.91 KB
/
EntityRESTApiHelper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\Helper;
use GuzzleHttp\Client;
/**
* Class EntityRESTApiHelper
* @package Magento\FunctionalTestingFramework\Helper
*/
class EntityRESTApiHelper
{
/**
* Integration admin token uri.
*/
const INTEGRATION_ADMIN_TOKEN_URI = '/rest/V1/integration/admin/token';
/**
* Application json header.
*/
const APPLICATION_JSON_HEADER = ['Content-Type' => 'application/json'];
/**
* Rest API client.
*
* @var Client
*/
private $guzzle_client;
/**
* EntityRESTApiHelper constructor.
* @param string $host
* @param string $port
*/
public function __construct($host, $port)
{
$this->guzzle_client = new Client([
'base_uri' => "http://${host}:${port}",
'timeout' => 5.0,
]);
}
/**
* Submit Auth API Request.
*
* @param string $apiMethod
* @param string $requestURI
* @param string $jsonBody
* @param array $headers
* @return \Psr\Http\Message\ResponseInterface
*/
public function submitAuthAPIRequest($apiMethod, $requestURI, $jsonBody, $headers)
{
$allHeaders = $headers;
$authTokenVal = $this->getAuthToken();
$authToken = ['Authorization' => 'Bearer ' . $authTokenVal];
$allHeaders = array_merge($allHeaders, $authToken);
return $this->submitAPIRequest($apiMethod, $requestURI, $jsonBody, $allHeaders);
}
/**
* Function that sends a REST call to the integration endpoint for an authorization token.
*
* @return string
*/
private function getAuthToken()
{
$jsonArray = json_encode(['username' => 'admin', 'password' => 'admin123']);
$response = $this->submitAPIRequest(
'POST',
self::INTEGRATION_ADMIN_TOKEN_URI,
$jsonArray,
self::APPLICATION_JSON_HEADER
);
if ($response->getStatusCode() != 200) {
throwException($response->getReasonPhrase() .' Could not get admin token from service, please check logs.');
}
$authToken = str_replace('"', "", $response->getBody()->getContents());
return $authToken;
}
/**
* Function that submits an api request from the guzzle client using the following parameters:
*
* @param string $apiMethod
* @param string $requestURI
* @param string $jsonBody
* @param array $headers
* @return \Psr\Http\Message\ResponseInterface
*/
private function submitAPIRequest($apiMethod, $requestURI, $jsonBody, $headers)
{
$response = $this->guzzle_client->request(
$apiMethod,
$requestURI,
[
'headers' => $headers,
'body' => $jsonBody
]
);
return $response;
}
}