| 1 |
<?php |
| 2 |
|
| 3 |
declare( strict_types=1 ); |
| 4 |
|
| 5 |
namespace Packetery\Core\Api\Rest; |
| 6 |
|
| 7 |
use Exception; |
| 8 |
use Packetery\Core\Api\Rest\Exception\InvalidApiKeyException; |
| 9 |
use Packetery\Core\Interfaces\IWebRequestClient; |
| 10 |
|
| 11 |
class PickupPointValidate { |
| 12 |
|
| 13 |
private const URL_VALIDATE_ENDPOINT = 'https://widget.packeta.com/v6/pps/api/widget/v1/validate'; |
| 14 |
|
| 15 |
/** @var IWebRequestClient */ |
| 16 |
private $webRequestClient; |
| 17 |
|
| 18 |
/** @var string */ |
| 19 |
private $apiKey; |
| 20 |
|
| 21 |
private function __construct( IWebRequestClient $webRequestClient, string $apiKey ) { |
| 22 |
$this->webRequestClient = $webRequestClient; |
| 23 |
$this->apiKey = $apiKey; |
| 24 |
} |
| 25 |
|
| 26 |
public static function createWithValidApiKey( IWebRequestClient $webRequestClient, ?string $apiKey ): PickupPointValidate { |
| 27 |
if ( $apiKey === null ) { |
| 28 |
throw InvalidApiKeyException::createFromMissingKey(); |
| 29 |
} |
| 30 |
|
| 31 |
return new self( $webRequestClient, $apiKey ); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* @throws RestException |
| 36 |
*/ |
| 37 |
public function validate( PickupPointValidateRequest $request ): PickupPointValidateResponse { |
| 38 |
$postData = $request->getSubmittableData(); |
| 39 |
$postData['apiKey'] = $this->apiKey; |
| 40 |
$options = [ |
| 41 |
// phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode |
| 42 |
'body' => json_encode( $postData ), |
| 43 |
'headers' => [ |
| 44 |
'Content-Type' => 'application/json', |
| 45 |
], |
| 46 |
]; |
| 47 |
|
| 48 |
try { |
| 49 |
$result = $this->webRequestClient->post( self::URL_VALIDATE_ENDPOINT, $options ); |
| 50 |
$resultArray = json_decode( $result, true ); |
| 51 |
$errors = is_array( $resultArray['errors'] ) ? $resultArray['errors'] : []; |
| 52 |
|
| 53 |
if ( isset( $resultArray['status'] ) && in_array( (int) $resultArray['status'], [ 400, 401 ], true ) ) { |
| 54 |
return new PickupPointValidateResponse( true, $errors ); |
| 55 |
} |
| 56 |
|
| 57 |
return new PickupPointValidateResponse( $resultArray['isValid'] ?? false, $errors ); |
| 58 |
} catch ( Exception $exception ) { |
| 59 |
throw new RestException( $exception->getMessage() ); |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|