|
| 1 | +<?php |
| 2 | +namespace TurboLabIt\ShopifySdk\Request; |
| 3 | + |
| 4 | +use Saloon\Http\Request; |
| 5 | +use Saloon\Traits\Body\HasBody; |
| 6 | +use Saloon\Enums\Method; |
| 7 | +use Saloon\Contracts\Body\HasBody as HasBodyContract; |
| 8 | +use TurboLabIt\ShopifySdk\Exception\ShopifyConfigurationException; |
| 9 | +use Saloon\Http\Response; |
| 10 | +use Symfony\Component\HttpFoundation\Response as SymfonyResponse; |
| 11 | +use TurboLabIt\ShopifySdk\Exception\ShopifyResponseException; |
| 12 | + |
| 13 | + |
| 14 | +abstract class ShopifyBaseRequest extends Request implements HasBodyContract |
| 15 | +{ |
| 16 | + protected Method $method = Method::POST; |
| 17 | + |
| 18 | + protected string $templateDir = 'request/shopify/graphql/'; |
| 19 | + protected string $templateFile = ''; |
| 20 | + |
| 21 | + use HasBody; |
| 22 | + |
| 23 | + |
| 24 | + public function setQueryFromTemplateBuilt(array $arrData = []) : static |
| 25 | + { |
| 26 | + if( empty($this->templateFile) ) { |
| 27 | + throw new ShopifyConfigurationException("$this->templateFile not set!"); |
| 28 | + } |
| 29 | + |
| 30 | + $template = $this->templateDir . $this->templateFile . ".graphql.twig"; |
| 31 | + $graphQlQuery = $this->twig->render($template, $arrData); |
| 32 | + |
| 33 | + return $this->setQuery($graphQlQuery); |
| 34 | + } |
| 35 | + |
| 36 | + |
| 37 | + public function setQuery(string $graphQl) : static |
| 38 | + { |
| 39 | + $this->body()->set($graphQl); |
| 40 | + return $this; |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + public function resolveEndpoint(): string |
| 45 | + { |
| 46 | + return ''; |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + public function buildFromResponse(Response $response) |
| 51 | + { |
| 52 | + $errorMessages = []; |
| 53 | + |
| 54 | + $httpStatusCode = $response->status() ?? null; |
| 55 | + |
| 56 | + if( |
| 57 | + empty($httpStatusCode) || |
| 58 | + $httpStatusCode < SymfonyResponse::HTTP_OK || |
| 59 | + $httpStatusCode >= SymfonyResponse::HTTP_MULTIPLE_CHOICES |
| 60 | + ) { |
| 61 | + $errorMessages[] = "HTTP response error: ##$httpStatusCode##"; |
| 62 | + } |
| 63 | + |
| 64 | + try { |
| 65 | + $json = $response->json(); |
| 66 | + } catch (\JsonException $ex) { |
| 67 | + $errorMessages[] = "JSON decode error: ##" . $response->body() . "##"; |
| 68 | + } |
| 69 | + |
| 70 | + if( !empty($json) && is_array($json) && !empty($json["errors"]) ) { |
| 71 | + |
| 72 | + $arrErrorFromJson = array_column($json["errors"], 'message') ?? null; |
| 73 | + $errorMessages = array_merge($errorMessages, $arrErrorFromJson); |
| 74 | + } |
| 75 | + |
| 76 | + if( !empty($errorMessages) ) { |
| 77 | + |
| 78 | + $message = implode(PHP_EOL, $errorMessages); |
| 79 | + throw new ShopifyResponseException($message, $httpStatusCode); |
| 80 | + } |
| 81 | + |
| 82 | + return $json; |
| 83 | + } |
| 84 | +} |
0 commit comments