diff --git a/commerce_loko.services.yml b/commerce_loko.services.yml index 582bfc9c7f66bedbd3c420495b320793e041264b..cdafe5f2ddb300114862695cfadb57779da7f778 100644 --- a/commerce_loko.services.yml +++ b/commerce_loko.services.yml @@ -1,4 +1,4 @@ services: commerce_loko.client: class: Drupal\commerce_loko\LokoClient - arguments: ['@http_client'] + arguments: ['@config.factory', '@http_client'] diff --git a/src/LokoClient.php b/src/LokoClient.php index 44c8854e0439d6dcd266ecd8f28918da88a57944..4c55aa5c3b514eae8c7c41eb12d6b693ea441168 100644 --- a/src/LokoClient.php +++ b/src/LokoClient.php @@ -2,6 +2,9 @@ namespace Drupal\commerce_loko; +use Drupal\Component\Serialization\Json; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Config\ImmutableConfig; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException; @@ -10,18 +13,35 @@ use GuzzleHttp\Exception\GuzzleException; */ class LokoClient implements LokoClientInterface { + /** + * Parcel lockers endpoint. + */ + private const ALL_PARCEL_LOCKERS = '/api/ParcelLocker/AllParcelLockers'; + + /** + * The main Loko config. + * + * @var \Drupal\Core\Config\ImmutableConfig + */ + protected ImmutableConfig $lokoConfig; + /** * Constructor for the LokoClient Service. * + * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory + * Config Factory. * @param \GuzzleHttp\ClientInterface $httpClient * The HTTP client. * @param string $endpointDomain * The API domain endpoint. */ public function __construct( + ConfigFactoryInterface $config_factory, protected ClientInterface $httpClient, protected string $endpointDomain = 'https://api.mint-dispatch.com' - ) {} + ) { + $this->lokoConfig = $config_factory->get('commerce_loko.settings'); + } /** * {@inheritdoc} @@ -45,4 +65,32 @@ class LokoClient implements LokoClientInterface { return $response->getStatusCode() === 200; } + /** + * {@inheritdoc} + */ + public function getAllParcelLockers(): array { + $token_key = $this->lokoConfig->get('loko_token'); + + try { + $response = $this->httpClient->get( + $this->endpointDomain . self::ALL_PARCEL_LOCKERS, + [ + 'headers' => [ + 'Authorization' => 'Bearer ' . $token_key, + 'accept' => 'text/plain', + ], + ] + ); + } + catch (GuzzleException) { + return []; + } + + if ($response->getStatusCode() !== 200) { + return []; + } + + return Json::decode((string) $response->getBody()); + } + } diff --git a/src/LokoClientInterface.php b/src/LokoClientInterface.php index 3bfa0d81435df70f8119e3425808589d394f9eae..9ef857445db9e860acf856e3d657850ded1f76d2 100644 --- a/src/LokoClientInterface.php +++ b/src/LokoClientInterface.php @@ -26,7 +26,7 @@ interface LokoClientInterface { * @return array|false * Gets the all parcel terminals. */ - // public function getAllParcelLockers(): ?array; + public function getAllParcelLockers(): ?array; /** * Method for gets the details for current parcel terminal.