fix sse error handling if shop api error part 1

This commit is contained in:
team2
2026-04-25 20:16:40 +02:00
parent 93ff6262cc
commit cf970d2b49
3 changed files with 204 additions and 70 deletions

View File

@@ -33,13 +33,13 @@ final readonly class StoreApiClient
$url = rtrim($this->baseUrl, '/') . '/store-api/search';
$sanitizedCriteria = $this->sanitizeValue($criteria);
$body = json_encode(
$sanitizedCriteria,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE
);
if (!is_string($body)) {
throw new RuntimeException('Failed to encode Store API criteria.');
try {
$body = json_encode(
$sanitizedCriteria,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE
);
} catch (\JsonException $e) {
throw new RuntimeException('Failed to encode Store API criteria as valid JSON.', 0, $e);
}
$response = $this->httpClient->request('POST', $url, [
@@ -83,9 +83,10 @@ final readonly class StoreApiClient
return new StoreApiException(
sprintf(
'Shopware Store API request failed with status %d. Response: %s',
'Shopware Store API request failed with status %d. Response: %s%s',
$statusCode,
$preview
$preview,
$utf8Failure ? ' Hint: The request body was valid JSON; this Shopware error usually means Shopware failed while encoding response/product data as UTF-8.' : ''
),
$statusCode,
$serverFailure,
@@ -126,26 +127,34 @@ final readonly class StoreApiClient
private function sanitizeString(string $value): string
{
if (preg_match('//u', $value) === 1) {
return $value;
}
if (preg_match('//u', $value) !== 1) {
if (function_exists('mb_convert_encoding')) {
$value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
}
if (function_exists('mb_convert_encoding')) {
$value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
}
if (preg_match('//u', $value) !== 1 && function_exists('iconv')) {
$converted = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
if (preg_match('//u', $value) === 1) {
return $value;
}
if (function_exists('iconv')) {
$converted = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
if (is_string($converted) && $converted !== '') {
return $converted;
if (is_string($converted)) {
$value = $converted;
}
}
}
return '';
if (preg_match('//u', $value) !== 1) {
return '';
}
if (class_exists('Normalizer')) {
$normalized = \Normalizer::normalize($value, \Normalizer::FORM_C);
if (is_string($normalized)) {
$value = $normalized;
}
}
// Keep tab/newline/carriage-return, strip other control characters that can
// make downstream JSON handling and logs harder to diagnose.
return (string) preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value);
}
}