Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
WebapiExecutor.php
Go to the documentation of this file.
1 <?php
8 
12 
17 {
23  private $transport;
24 
30  private $headers = [
31  'Accept: application/json',
32  'Content-Type: application/json',
33  ];
34 
40  private $response;
41 
45  const ADMIN_AUTH_URL = '/V1/integration/admin/token';
46 
52  private $storeCode;
53 
60  public function __construct($storeCode = null)
61  {
62  if (!isset(parent::$baseUrl)) {
63  parent::resolveBaseUrl();
64  }
65 
66  $this->storeCode = $storeCode;
67  $this->transport = new CurlTransport();
68  $this->authorize();
69  }
70 
77  protected function authorize()
78  {
79  $authUrl = $this->getFormattedUrl(self::ADMIN_AUTH_URL);
80  $authCreds = [
81  'username' => getenv('MAGENTO_ADMIN_USERNAME'),
82  'password' => getenv('MAGENTO_ADMIN_PASSWORD')
83  ];
84 
85  $this->transport->write($authUrl, json_encode($authCreds), CurlInterface::POST, $this->headers);
86  $this->headers = array_merge(
87  ['Authorization: Bearer ' . str_replace('"', "", $this->read())],
88  $this->headers
89  );
90  }
91 
102  public function write($url, $data = [], $method = CurlInterface::POST, $headers = [])
103  {
104  $this->transport->write(
105  $this->getFormattedUrl($url),
106  json_encode($data, JSON_PRETTY_PRINT),
107  $method,
108  array_unique(array_merge($headers, $this->headers))
109  );
110  }
111 
120  public function read($successRegex = null, $returnRegex = null)
121  {
122  $this->response = $this->transport->read();
123  return $this->response;
124  }
125 
133  public function addOption($option, $value)
134  {
135  $this->transport->addOption($option, $value);
136  }
137 
143  public function close()
144  {
145  $this->transport->close();
146  }
147 
153  public function getFormattedUrl($resource)
154  {
155  $urlResult = parent::$baseUrl . 'rest/';
156  if ($this->storeCode != null) {
157  $urlResult .= $this->storeCode . "/";
158  }
159  $urlResult.= trim($resource, "/");
160  return $urlResult;
161  }
162 }
write($url, $data=[], $method=CurlInterface::POST, $headers=[])
$resource
Definition: bulk.php:12
$value
Definition: gender.phtml:16
$method
Definition: info.phtml:13