API.php
77 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Services\Release; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\WP\Functions as WPFunctions; |
| 9 | |
| 10 | class API { |
| 11 | private $apiKey; |
| 12 | private $wp; |
| 13 | public $urlProducts = 'https://release.mailpoet.com/products/'; |
| 14 | |
| 15 | public function __construct( |
| 16 | $apiKey |
| 17 | ) { |
| 18 | $this->setKey($apiKey); |
| 19 | $this->wp = new WPFunctions(); |
| 20 | } |
| 21 | |
| 22 | public function getPluginInformation($pluginName) { |
| 23 | $result = $this->request( |
| 24 | $this->urlProducts . $pluginName |
| 25 | ); |
| 26 | |
| 27 | $code = $this->wp->wpRemoteRetrieveResponseCode($result); |
| 28 | switch ($code) { |
| 29 | case 200: |
| 30 | $body = $this->wp->wpRemoteRetrieveBody($result); |
| 31 | if ($body) { |
| 32 | $body = $this->formatPluginInformation(json_decode($body)); |
| 33 | } |
| 34 | break; |
| 35 | default: |
| 36 | $body = null; |
| 37 | break; |
| 38 | } |
| 39 | |
| 40 | return $body; |
| 41 | } |
| 42 | |
| 43 | public function setKey($apiKey) { |
| 44 | $this->apiKey = $apiKey; |
| 45 | } |
| 46 | |
| 47 | public function getKey() { |
| 48 | return $this->apiKey; |
| 49 | } |
| 50 | |
| 51 | private function formatPluginInformation($info) { |
| 52 | if (!$info instanceof \stdClass) return $info; |
| 53 | |
| 54 | $propKeys = array_keys(get_object_vars($info)); |
| 55 | $newInfo = clone $info; |
| 56 | |
| 57 | foreach ($propKeys as $key) { |
| 58 | if (gettype($newInfo->{$key}) === 'object') { |
| 59 | // cast objects to array for WP to understand |
| 60 | $newInfo->{$key} = (array)$newInfo->{$key}; |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | return $newInfo; |
| 65 | } |
| 66 | |
| 67 | private function request($url, $params = []) { |
| 68 | $params['license'] = $this->apiKey; |
| 69 | $url = WPFunctions::get()->addQueryArg($params, $url); |
| 70 | $args = [ |
| 71 | 'timeout' => 10, |
| 72 | 'httpversion' => '1.0', |
| 73 | ]; |
| 74 | return $this->wp->wpRemoteGet($url, $args); |
| 75 | } |
| 76 | } |
| 77 |