PluginProbe
Packeta / 2.3.1
Packeta v2.3.1
2.3.2 2.3.1 trunk 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.0 1.3.1 1.3.2 1.4 1.4.1 1.4.2 1.4.3 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 All 56 releases
packeta / src / Packetery / Core / Api / Rest / PickupPointValidate.php

PickupPointValidate.php in Packeta 2.3.1, at src/Packetery/Core/Api/Rest/PickupPointValidate.php

63 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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