Fix variable reference errors ($term → $keyword)

Ensure array keys exist before accessing them
Optimize API calls to prevent unnecessary requests
Improve error handling for better debugging
Enhance readability and maintainability of functions
This commit is contained in:
Marc Kreidler 2025-02-25 16:40:20 +01:00
parent ac83297811
commit 43801bbcde

View file

@ -69,43 +69,40 @@ class BuerklinProvider implements InfoProviderInterface
*/ */
private function getToken(): string private function getToken(): string
{ {
//Check if we already have a token saved for this app, otherwise we have to retrieve one via OAuth if ($this->authTokenManager->hasToken(self::OAUTH_APP_NAME)) {
if (!$this->authTokenManager->hasToken(self::OAUTH_APP_NAME)) { return $this->authTokenManager->getAlwaysValidTokenString(self::OAUTH_APP_NAME);
$this->authTokenManager->retrieveClientCredentialsToken(self::OAUTH_APP_NAME);
} }
$tmp = $this->authTokenManager->getAlwaysValidTokenString(self::OAUTH_APP_NAME); $this->authTokenManager->retrieveClientCredentialsToken(self::OAUTH_APP_NAME);
if ($tmp === null) { $token = $this->authTokenManager->getAlwaysValidTokenString(self::OAUTH_APP_NAME);
if ($token === null) {
throw new \RuntimeException('Could not retrieve OAuth token for Buerklin'); throw new \RuntimeException('Could not retrieve OAuth token for Buerklin');
} }
return $tmp; return $token;
} }
/** /**
* Make a http get request to the Buerklin API * Make a http get request to the Buerklin API
* @return array * @return array
*/ */
private function makeAPICall(string $query, ?array $variables = null): array private function makeAPICall(string $endpoint, array $queryParams = []): array
{ {
if ($variables === []) { try {
$variables = null; $response = $this->client->request('GET', self::ENDPOINT_URL . $endpoint, [
'auth_bearer' => $this->getToken(),
'query' => $queryParams,
]);
return $response->toArray();
} catch (\Exception $e) {
throw new \RuntimeException("Buerklin API request failed: " . $e->getMessage());
} }
$options = (new HttpOptions())
->setJson(['query' => $query, 'variables' => $variables])
->setAuthBearer($this->getToken())
;
$response = $this->client->request(
'GET',
self::ENDPOINT_URL,
$options->toArray(),
);
return $response->toArray(true);
} }
public function getProviderInfo(): array public function getProviderInfo(): array
{ {
return [ return [
@ -134,11 +131,7 @@ class BuerklinProvider implements InfoProviderInterface
*/ */
private function queryDetail(string $id): PartDetailDTO private function queryDetail(string $id): PartDetailDTO
{ {
$response = $this->client->request('GET', self::ENDPOINT_URL . "/products", [ $response = $this->makeAPICall('/products', ['sku' => $id]);
'query' => [
'sku' => $id,
],
]);
$arr = $response->toArray(); $arr = $response->toArray();
$product = $arr['result'] ?? null; $product = $arr['result'] ?? null;
@ -181,10 +174,12 @@ class BuerklinProvider implements InfoProviderInterface
} }
// Find the footprint in classifications->features. en: name='Design'; de: name='Bauform' // Find the footprint in classifications->features. en: name='Design'; de: name='Bauform'
foreach ($product[classifications][features] as $feature) { if (isset($product['classifications']['features'])) {
if($feature[name]=='Design'||$feature[name]=='Bauform') foreach ($product['classifications']['features'] as $feature) {
{ if (isset($feature['name']) && ($feature['name'] === 'Design' || $feature['name'] === 'Bauform')) {
$footprint = $feature["featureValues"]["value"]; $footprint = $feature['featureValues']['value'] ?? null;
break;
}
} }
} }
@ -217,27 +212,24 @@ class BuerklinProvider implements InfoProviderInterface
*/ */
private function pricesToVendorInfo(string $sku, string $url, array $prices): array private function pricesToVendorInfo(string $sku, string $url, array $prices): array
{ {
$price_dtos = []; $priceDTOs = array_map(fn($price) => new PriceDTO(
minimum_discount_amount: $price['minQuantity'],
foreach ($prices as $price) { price: $price['value'],
$price_dtos[] = new PriceDTO( currency_iso_code: $price['currencyIso'],
minimum_discount_amount: $price['minQuantity'], includes_tax: false
price: $price['value'], ), $prices);
currency_iso_code: $price['currencyIso'],
includes_tax: false,
);
}
return [ return [
new PurchaseInfoDTO( new PurchaseInfoDTO(
distributor_name: self::DISTRIBUTOR_NAME, distributor_name: self::DISTRIBUTOR_NAME,
order_number: $sku, order_number: $sku,
prices: $price_dtos, prices: $priceDTOs,
product_url: $url, product_url: $url,
) )
]; ];
} }
/** /**
* Returns a valid Buerklin product short URL from product code * Returns a valid Buerklin product short URL from product code
* @param string $product_code * @param string $product_code
@ -265,62 +257,50 @@ class BuerklinProvider implements InfoProviderInterface
private function attributesToParameters(?array $attributes): array private function attributesToParameters(?array $attributes): array
{ {
$result = []; $result = [];
foreach ($attributes as $attribute) { foreach ($attributes as $attribute) {
if (!isset($attribute['name'], $attribute['featureValues']['value'])) {
//Skip this attribute if it's empty continue;
if (in_array(trim((string) $attribute['featureValues']['value']), ['', '-'], true)) {
continue;
} }
$result[] = ParameterDTO::parseValueIncludingUnit(name: $attribute['name'], value: $attribute['featureValues']['value'], group: null); $value = trim((string)$attribute['featureValues']['value']);
if ($value === '' || $value === '-') {
continue;
}
$result[] = ParameterDTO::parseValueIncludingUnit(
name: $attribute['name'],
value: $value,
group: null
);
} }
return $result; return $result;
} }
public function searchByKeyword(string $keyword): array public function searchByKeyword(string $keyword): array
{ {
$response = $this->client->request('GET', self::ENDPOINT_URL . "products/search/", [ $response = $this->makeAPICall('/products/search', [
'auth_bearer' => $this->getToken(), 'curr' => $this->currency,
'query' => [ 'language' => $this->language,
'curr' => $this->currency, 'pageSize' => '50',
'language' => $this->language, 'currentPage' => '1',
'pageSize' => '50', 'keyword' => $keyword,
'currentPage' => '1', 'sort' => 'relevance']);
'query' => $term,
'sort' => 'relevance' return array_map(fn($product) => $this->getPartDetail($product), $response['products'] ?? []);
],
]);
$arr = $response->toArray();
// Get products list
$products = $arr['products'] ?? [];
$result = [];
foreach ($products as $product) {
$result[] = $this->getPartDetail($product);
}
return $result;
} }
public function getDetails(string $id): PartDetailDTO public function getDetails(string $id): PartDetailDTO
{ {
$tmp = $this->searchByKeyword($id); $response = $this->makeAPICall("/products", ['sku' => $id]);
if (empty($response['result'])) {
if (count($tmp) === 0) { throw new \RuntimeException("No part found with ID $id");
throw new \RuntimeException('No part found with ID ' . $id);
} }
if (count($tmp) > 1) { return $this->getPartDetail($response['result']);
throw new \RuntimeException('Multiple parts found with ID ' . $id);
}
return $tmp[0];
} }
public function getCapabilities(): array public function getCapabilities(): array