-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
♻️ Refactored DocBlockWriter class to DocumentationGenerator, added s…
…tatic createDocBlock method, and added writeDocBlock method to FileWriter class for writing docblocks to files.
- Loading branch information
Showing
3 changed files
with
92 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
<?php | ||
|
||
namespace Molbal\AiPhpdoc; | ||
|
||
class DocumentationGenerator | ||
{ | ||
public static function createDocBlock(string $function): string { | ||
$key = getenv('OPENAI_KEY'); | ||
|
||
$openai = \OpenAI::client($key); | ||
|
||
$completion = $openai->completions()->create([ | ||
'model' => 'text-davinci-003', | ||
'prompt' => 'Read the following PHP function: """ '.$function.' """ PHPDoc block for the function:', | ||
'max_tokens' => 1024, | ||
'stop' => ['"""'], | ||
'temperature' => 0.3 | ||
]); | ||
|
||
try { | ||
// Check if the OpenAI API returned an error response | ||
if (isset($completion['error'])) { | ||
throw new \RuntimeException($completion['error']); | ||
} | ||
|
||
return $completion['choices'][0]['text']; | ||
} | ||
catch (\Throwable $e) { | ||
throw new \RuntimeException('An error occurred while trying to get the doc block: ' . $e->getMessage()); | ||
} | ||
} | ||
|
||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<?php | ||
|
||
namespace Molbal\AiPhpdoc; | ||
|
||
class FileWriter | ||
{ | ||
public static function writeDocBlock(string $file, string $body, string $docblock): bool | ||
{ | ||
return file_put_contents( | ||
$file, | ||
str_replace($body, $docblock.PHP_EOL.$body, file_get_contents($file)) | ||
) !== false; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters