Ajax.php
3 months ago
Assets.php
1 month ago
Loader.php
1 year ago
Rest.php
1 year ago
SurveyLoader.php
1 year ago
SurveyManager.php
1 month ago
Rest.php
88 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\Surveys; |
| 4 | |
| 5 | use Hostinger\WpHelper\Requests\Client; |
| 6 | |
| 7 | defined('ABSPATH') || exit; |
| 8 | |
| 9 | class Rest |
| 10 | { |
| 11 | public const SUBMIT_SURVEY = '/v3/wordpress/survey/store'; |
| 12 | public const CLIENT_SURVEY_ELIGIBILITY = '/v3/wordpress/survey/client-eligible'; |
| 13 | public const CLIENT_SURVEY_IDENTIFIER = 'customer_satisfaction_score'; |
| 14 | |
| 15 | private Client $client; |
| 16 | |
| 17 | public function __construct(Client $client) |
| 18 | { |
| 19 | $this->client = $client; |
| 20 | } |
| 21 | |
| 22 | public function isClientEligible(): bool |
| 23 | { |
| 24 | $response = $this->client->get( |
| 25 | self::CLIENT_SURVEY_ELIGIBILITY, |
| 26 | [ |
| 27 | 'identifier' => self::CLIENT_SURVEY_IDENTIFIER, |
| 28 | ], |
| 29 | [], |
| 30 | 10 |
| 31 | ); |
| 32 | |
| 33 | $decoded_response = $this->decodeResponse($response); |
| 34 | $response_data = $decoded_response['response_data']['data'] ?? null; |
| 35 | |
| 36 | if ($response_data !== true) { |
| 37 | return false; |
| 38 | } |
| 39 | |
| 40 | return (bool) $this->getResult($response); |
| 41 | } |
| 42 | |
| 43 | public function submitSurveyData(array $data): bool |
| 44 | { |
| 45 | $response = $this->client->post(self::SUBMIT_SURVEY, $data); |
| 46 | return $this->getResult($response); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * @param array|WP_Error $response |
| 51 | * |
| 52 | * @return mixed |
| 53 | */ |
| 54 | public function getResult($response) |
| 55 | { |
| 56 | $data = $this->decodeResponse($response); |
| 57 | |
| 58 | if (is_wp_error($data) || $data['response_code'] !== 200) { |
| 59 | error_log('Error: ' . $data['response_body']); |
| 60 | return false; |
| 61 | } |
| 62 | |
| 63 | return $data['response_data']['data']; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * @param array|WP_Error $response |
| 68 | * |
| 69 | * @return array |
| 70 | */ |
| 71 | public function decodeResponse($response): array |
| 72 | { |
| 73 | $response_body = wp_remote_retrieve_body($response); |
| 74 | $response_code = wp_remote_retrieve_response_code($response); |
| 75 | $response_data = json_decode($response_body, true); |
| 76 | |
| 77 | if (! is_array($response_data)) { |
| 78 | $response_data = [ 'data' => null ]; |
| 79 | } |
| 80 | |
| 81 | return [ |
| 82 | 'response_code' => $response_code, |
| 83 | 'response_data' => $response_data, |
| 84 | 'response_body' => $response_body, |
| 85 | ]; |
| 86 | } |
| 87 | } |
| 88 |