| Conditions | 7 |
| Paths | 14 |
| Total Lines | 55 |
| Code Lines | 37 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 44 | public function generateQuestions(string $topic, int $numQuestions, string $questionType, string $language): ?string |
||
| 45 | { |
||
| 46 | $prompt = sprintf( |
||
| 47 | 'Generate %d "%s" questions in Aiken format in the %s language about "%s".', |
||
| 48 | $numQuestions, $questionType, $language, $topic |
||
| 49 | ); |
||
| 50 | |||
| 51 | $payload = [ |
||
| 52 | 'model' => $this->model, |
||
| 53 | 'prompt' => $prompt, |
||
| 54 | 'temperature' => $this->temperature, |
||
| 55 | 'max_tokens' => 2000, |
||
| 56 | 'frequency_penalty' => 0, |
||
| 57 | 'presence_penalty' => 0.6, |
||
| 58 | 'top_p' => 1.0, |
||
| 59 | ]; |
||
| 60 | |||
| 61 | try { |
||
| 62 | $response = $this->httpClient->request('POST', $this->apiUrl . '/completions', [ |
||
| 63 | 'headers' => [ |
||
| 64 | 'Authorization' => 'Bearer ' . $this->apiKey, |
||
| 65 | 'Content-Type' => 'application/json', |
||
| 66 | ], |
||
| 67 | 'body' => json_encode($payload), |
||
| 68 | ]); |
||
| 69 | |||
| 70 | $statusCode = $response->getStatusCode(); |
||
| 71 | $responseContent = $response->getContent(false); |
||
| 72 | |||
| 73 | if ($statusCode === 200) { |
||
| 74 | $data = json_decode($responseContent, true); |
||
| 75 | |||
| 76 | return $data['choices'][0]['text'] ?? null; |
||
| 77 | } |
||
| 78 | |||
| 79 | $errorData = json_decode($responseContent, true); |
||
| 80 | |||
| 81 | if (isset($errorData['error']['code'])) { |
||
| 82 | switch ($errorData['error']['code']) { |
||
| 83 | case 'insufficient_quota': |
||
| 84 | throw new \Exception("You have exceeded your OpenAI quota. Please check your OpenAI plan."); |
||
| 85 | case 'invalid_api_key': |
||
| 86 | throw new \Exception("Invalid API key. Please check your OpenAI configuration."); |
||
| 87 | case 'server_error': |
||
| 88 | throw new \Exception("OpenAI encountered an internal error. Try again later."); |
||
| 89 | default: |
||
| 90 | throw new \Exception("An error occurred: " . $errorData['error']['message']); |
||
| 91 | } |
||
| 92 | } |
||
| 93 | |||
| 94 | throw new \Exception("Unexpected error from OpenAI."); |
||
| 95 | |||
| 96 | } catch (\Exception $e) { |
||
| 97 | error_log("ERROR - OpenAI Request failed: " . $e->getMessage()); |
||
| 98 | return "Error: " . $e->getMessage(); |
||
| 99 | } |
||
| 102 |