Skip to content

Commit 16c76dc

Browse files
Merge pull request #5 from Hackwar/codestyle
Codestyle
2 parents 51fa4aa + f9bb495 commit 16c76dc

11 files changed

+263
-265
lines changed

src/AbstractProvider.php

Lines changed: 34 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ abstract class AbstractProvider implements ProviderInterface
4646
*
4747
* @param array|\ArrayAccess $options Provider options array.
4848
* @param HttpFactory $httpFactory The http factory
49-
*
49+
*
5050
* @throws \InvalidArgumentException
5151
* @since ___DEPLOY_VERSION___
5252
*/
@@ -65,10 +65,10 @@ public function __construct(array $options = [], ?HttpFactory $httpFactory = nul
6565

6666
/**
6767
* Get an option from the AI provider.
68-
*
68+
*
6969
* @param string $key The name of the option to get.
7070
* @param mixed $default The default value if the option is not set.
71-
*
71+
*
7272
* @return mixed The option value.
7373
* @since ___DEPLOY_VERSION___
7474
*/
@@ -92,9 +92,9 @@ protected function makeGetRequest(string $url, array $headers = [], $timeout = n
9292
{
9393
try {
9494
$response = $this->httpFactory->getHttp([])->get($url, $headers, $timeout);
95-
95+
9696
$this->validateResponse($response);
97-
} catch (AuthenticationException|RateLimitException|QuotaExceededException $e) {
97+
} catch (AuthenticationException | RateLimitException | QuotaExceededException $e) {
9898
throw $e;
9999
} catch (ProviderException $e) {
100100
throw $e;
@@ -106,7 +106,7 @@ protected function makeGetRequest(string $url, array $headers = [], $timeout = n
106106
/**
107107
* Make HTTP POST request.
108108
*
109-
* @param string $url API endpoint URL
109+
* @param string $url API endpoint URL
110110
* @param mixed $data POST data
111111
* @param array $headers HTTP headers
112112
* @param integer $timeout Request timeout
@@ -119,10 +119,9 @@ protected function makePostRequest(string $url, $data, array $headers = [], $tim
119119
{
120120
try {
121121
$response = $this->httpFactory->getHttp([])->post($url, $data, $headers, $timeout);
122-
122+
123123
$this->validateResponse($response);
124-
125-
} catch (AuthenticationException|RateLimitException|QuotaExceededException $e) {
124+
} catch (AuthenticationException | RateLimitException | QuotaExceededException $e) {
126125
throw $e;
127126
} catch (ProviderException $e) {
128127
throw $e;
@@ -134,7 +133,7 @@ protected function makePostRequest(string $url, $data, array $headers = [], $tim
134133
/**
135134
* Make multipart HTTP POST request.
136135
*
137-
* @param string $url API endpoint URL
136+
* @param string $url API endpoint URL
138137
* @param array $data Form data
139138
* @param array $headers HTTP headers
140139
*
@@ -157,12 +156,12 @@ protected function makeMultipartPostRequest(string $url, array $data, array $hea
157156
$filepath = $data['_filepath'];
158157
$filename = $data['_filename'];
159158
$mimeType = $this->detectAudioMimeType($filepath);
160-
159+
161160
$fileResource = fopen($filepath, 'rb');
162161
if (!$fileResource) {
163162
throw new \Exception("Cannot open file: $filepath");
164163
}
165-
164+
166165
$postData .= "--{$boundary}\r\n";
167166
$postData .= "Content-Disposition: form-data; name=\"file\"; filename=\"{$filename}\"\r\n";
168167
$postData .= "Content-Type: {$mimeType}\r\n\r\n";
@@ -171,9 +170,8 @@ protected function makeMultipartPostRequest(string $url, array $data, array $hea
171170
fclose($fileResource);
172171

173172
$postData .= $fileContent . "\r\n";
174-
}
175-
// To do: Currently strict format
176-
elseif ($key === 'image') {
173+
} elseif ($key === 'image') {
174+
// To do: Currently strict format
177175
if (is_array($value)) {
178176
foreach ($value as $index => $imageData) {
179177
$postData .= "--{$boundary}\r\n";
@@ -188,16 +186,14 @@ protected function makeMultipartPostRequest(string $url, array $data, array $hea
188186
$postData .= "Content-Type: image/png\r\n\r\n";
189187
$postData .= $value . "\r\n";
190188
}
191-
}
192-
// Handle mask file
193-
elseif ($key === 'mask') {
189+
} elseif ($key === 'mask') {
190+
// Handle mask file
194191
$postData .= "--{$boundary}\r\n";
195192
$postData .= "Content-Disposition: form-data; name=\"mask\"; filename=\"mask.png\"\r\n";
196193
$postData .= "Content-Type: image/png\r\n\r\n";
197194
$postData .= $value . "\r\n";
198-
}
199-
// Handle regular form fields
200-
else {
195+
} else {
196+
// Handle regular form fields
201197
$postData .= "--{$boundary}\r\n";
202198
$postData .= "Content-Disposition: form-data; name=\"{$key}\"\r\n\r\n";
203199
$postData .= $value . "\r\n";
@@ -230,7 +226,6 @@ protected function extractFilename(string $fieldName, string $data): string
230226
}
231227

232228
return "image.{$extension}";
233-
234229
}
235230

236231
/**
@@ -244,22 +239,22 @@ protected function extractFilename(string $fieldName, string $data): string
244239
protected function detectImageMimeType(string $imageData): string
245240
{
246241
$header = substr($imageData, 0, 16);
247-
242+
248243
// PNG signature
249244
if (substr($header, 0, 8) === "\x89PNG\r\n\x1a\n") {
250245
return 'image/png';
251246
}
252-
247+
253248
// JPEG signature
254249
if (substr($header, 0, 2) === "\xFF\xD8") {
255250
return 'image/jpeg';
256251
}
257-
252+
258253
// WebP signature
259254
if (substr($header, 0, 4) === 'RIFF' && substr($header, 8, 4) === 'WEBP') {
260255
return 'image/webp';
261256
}
262-
257+
263258
throw new \InvalidArgumentException('Unsupported image format. Only PNG, JPEG, and WebP are supported.');
264259
}
265260

@@ -275,7 +270,7 @@ protected function getExtensionFromMimeType(string $mimeType): string
275270
return 'png';
276271
}
277272
}
278-
273+
279274
/**
280275
* Get audio MIME type from file path.
281276
*
@@ -289,7 +284,7 @@ protected function detectAudioMimeType(string $input): string
289284
if (strpos($input, '.') !== false && !in_array($input, ['mp3', 'wav', 'flac', 'mp4', 'mpeg', 'mpga', 'm4a', 'ogg', 'webm', 'opus', 'aac', 'pcm'])) {
290285
$input = strtolower(pathinfo($input, PATHINFO_EXTENSION));
291286
}
292-
287+
293288
$mimeMap = [
294289
'mp3' => 'audio/mpeg',
295290
'wav' => 'audio/wav',
@@ -304,7 +299,7 @@ protected function detectAudioMimeType(string $input): string
304299
'aac' => 'audio/aac',
305300
'pcm' => 'audio/pcm',
306301
];
307-
302+
308303
return $mimeMap[$input];
309304
}
310305

@@ -351,7 +346,7 @@ protected function checkModelCapability(string $model, string $capability, array
351346
if (!isset($capabilityMap[$capability])) {
352347
return false;
353348
}
354-
349+
355350
return $this->isModelAvailable($model, $capabilityMap[$capability]);
356351
}
357352

@@ -377,19 +372,20 @@ protected function validateResponse($response): bool
377372
case 401:
378373
case 403:
379374
throw new AuthenticationException($this->getName(), $errorData, $response->getStatusCode());
380-
375+
381376
case 429:
382-
if (str_contains(strtolower($message), 'quota') || str_contains(strtolower($message), 'credits') ||str_contains(strtolower($message), 'billing')) {
377+
if (str_contains(strtolower($message), 'quota') || str_contains(strtolower($message), 'credits') || str_contains(strtolower($message), 'billing')) {
383378
throw new QuotaExceededException($this->getName(), $errorData, $response->getStatusCode());
384379
} elseif (str_contains(strtolower($message), 'rate') || str_contains(strtolower($message), 'limit') || str_contains(strtolower($message), 'too many requests')) {
385380
throw new RateLimitException($this->getName(), $errorData, $response->getStatusCode());
386381
}
387-
382+
break;
383+
388384
default:
389385
throw new ProviderException($this->getName(), $errorData, $response->getStatusCode(), $providerErrorCode);
390386
}
391387
}
392-
388+
393389
return true;
394390
}
395391

@@ -402,21 +398,21 @@ protected function isJsonResponse(string $responseBody): bool
402398

403399
/**
404400
* Parse JSON response safely
405-
*
401+
*
406402
* @param string $jsonString The JSON string to parse
407-
*
403+
*
408404
* @return array The parsed JSON data
409405
* @throws UnserializableResponseException If JSON parsing fails
410406
* @since ___DEPLOY_VERSION___
411407
*/
412408
protected function parseJsonResponse(string $jsonString): array
413409
{
414410
$decoded = json_decode($jsonString, true);
415-
411+
416412
if (json_last_error() !== JSON_ERROR_NONE) {
417413
throw new UnserializableResponseException($this->getName(), $jsonString, json_last_error_msg(), 422);
418414
}
419-
415+
420416
return $decoded;
421417
}
422418

src/Exception/AIException.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ class AIException extends \Exception
6060
*
6161
* @since __DEPLOY_VERSION__
6262
*/
63-
public function __construct(string $message, string $provider, array $context, ?\Throwable $previous, ?int $httpStatusCode, ?string $providerErrorCode) {
63+
public function __construct(string $message, string $provider, array $context, ?\Throwable $previous, ?int $httpStatusCode, ?string $providerErrorCode)
64+
{
6465
parent::__construct($message, 0, $previous);
6566
$this->provider = $provider;
6667
$this->context = $context;
@@ -134,7 +135,8 @@ public function isRetryable(): bool
134135
*
135136
* @return string Detailed error message
136137
*/
137-
protected function buildDetailedMessage(string $provider, string $errorType, string $message, ?int $httpStatusCode = null, string|int|null $providerErrorCode = null): string {
138+
protected function buildDetailedMessage(string $provider, string $errorType, string $message, ?int $httpStatusCode = null, string|int|null $providerErrorCode = null): string
139+
{
138140
$details = [];
139141
$details[] = "Provider: {$provider}";
140142
$details[] = "HTTP Status: " . ($httpStatusCode ?? 'Unknown');

src/Exception/AuthenticationException.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
/**
1313
* Exception for authentication and authorization errors from AI providers.
14-
*
14+
*
1515
* @since __DEPLOY_VERSION__
1616
*/
1717
class AuthenticationException extends AIException

src/Exception/InvalidArgumentException.php

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,15 @@ class InvalidArgumentException extends AIException
3030
public static function invalidModel(string $model, string $provider, array $validModels = [], string $capability = ''): self
3131
{
3232
$message = "Model '{$model}' is not supported by {$provider}";
33-
33+
3434
if ($capability) {
3535
$message = "Model '{$model}' does not support {$capability} capability on {$provider}";
3636
}
37-
37+
3838
if (!empty($validModels)) {
3939
$message .= ". Valid models: " . implode(', ', $validModels);
4040
}
41-
41+
4242
return new self(
4343
$message,
4444
$provider,
@@ -68,7 +68,7 @@ public static function invalidModel(string $model, string $provider, array $vali
6868
public static function invalidTemperature(float $temperature, string $provider, float $min = 0.0, float $max = 2.0): self
6969
{
7070
$message = "Temperature value {$temperature} is invalid. Must be between {$min} and {$max}";
71-
71+
7272
return new self(
7373
$message,
7474
$provider,
@@ -99,9 +99,9 @@ public static function fileSizeExceeded(string $filePath, int $fileSize, int $ma
9999
{
100100
$fileSizeMB = round($fileSize / 1024 / 1024, 2);
101101
$maxSizeMB = round($maxSize / 1024 / 1024, 2);
102-
102+
103103
$message = "File '{$filePath}' size ({$fileSizeMB}MB) exceeds maximum allowed size ({$maxSizeMB}MB)";
104-
104+
105105
if ($model) {
106106
$message .= " for model '{$model}'";
107107
}
@@ -136,13 +136,13 @@ public static function fileSizeExceeded(string $filePath, int $fileSize, int $ma
136136
public static function invalidFileFormat(string $filePath, string $currentFormat, array $allowedFormats, string $provider, string $operation = ''): self
137137
{
138138
$message = "File '{$filePath}' has unsupported format '{$currentFormat}'";
139-
139+
140140
if ($operation) {
141141
$message .= " for {$operation}";
142142
}
143-
143+
144144
$message .= " on {$provider}. Supported formats: " . implode(', ', $allowedFormats);
145-
145+
146146
return new self(
147147
$message,
148148
$provider,
@@ -172,7 +172,7 @@ public static function invalidFileFormat(string $filePath, string $currentFormat
172172
public static function invalidVoice(string $voice, array $availableVoices, string $provider): self
173173
{
174174
$message = "Voice '{$voice}' is not available on {$provider}. Available voices: " . implode(', ', $availableVoices);
175-
175+
176176
return new self(
177177
$message,
178178
$provider,
@@ -225,7 +225,7 @@ public static function invalidMessages(string $provider, string $reason = 'Messa
225225
public static function invalidImageSize(string $size, array $allowedSizes, string $provider, string $model): self
226226
{
227227
$message = "Image size '{$size}' is not supported";
228-
228+
229229
if ($model) {
230230
$message .= " for model '{$model}'.";
231231
}
@@ -263,14 +263,14 @@ public static function invalidParameter(string $parameter, $value, string $provi
263263
{
264264
$valueStr = is_scalar($value) ? (string)$value : gettype($value);
265265
$message = "Parameter '{$parameter}' has invalid value '{$valueStr}'. {$requirement}";
266-
266+
267267
$contextData = array_merge([
268268
'parameter' => $parameter,
269269
'invalid_value' => $value,
270270
'requirement' => $requirement,
271271
'validation_type' => 'parameter'
272272
], $context);
273-
273+
274274
return new self($message, $provider, $contextData, null, null, null);
275275
}
276276

@@ -287,11 +287,11 @@ public static function invalidParameter(string $parameter, $value, string $provi
287287
public static function missingParameter(string $parameter, string $provider, string $method = ''): self
288288
{
289289
$message = "Required parameter '{$parameter}' is missing";
290-
290+
291291
if ($method) {
292292
$message .= " for {$method}()";
293293
}
294-
294+
295295
return new self(
296296
$message,
297297
$provider,

src/Exception/ProviderException.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<?php
2+
23
/**
34
* Part of the Joomla Framework AI Package
45
*
@@ -25,20 +26,18 @@ class ProviderException extends AIException
2526
*
2627
* @since __DEPLOY_VERSION__
2728
*/
28-
public function __construct(string $provider, string|array $errorData, ?int $httpStatusCode = null, string|int|null $providerErrorCode = null)
29+
public function __construct(string $provider, string|array $errorData, ?int $httpStatusCode = null, string|int|null $providerErrorCode = null)
2930
{
3031
$context = ['error_data' => $errorData];
3132
$providerErrorCode = $errorData['code'] ?? $errorData['error']['code'] ?? null;
3233
$errorType = $errorData['type'] ?? $errorData['error']['type'] ?? 'Unknown Error';
33-
3434
if (is_array($errorData)) {
3535
$message = $errorData['message'] ?? $errorData['error']['message'] ?? $errorData['error'] ?? 'Unknown provider error';
3636
} else {
3737
$message = $errorData;
3838
}
3939

4040
$detailedMessage = $this->buildDetailedMessage($provider, $errorType, $message, $httpStatusCode, $providerErrorCode);
41-
4241
parent::__construct($detailedMessage, $provider, $context, null, $httpStatusCode, $providerErrorCode);
4342
}
4443

0 commit comments

Comments
 (0)