gotem_content_moderation-1.1.6-alpha1/src/OpenAIModerationClient.php
src/OpenAIModerationClient.php
<?php
namespace Drupal\gotem;
use GuzzleHttp\ClientInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\gotem\Moderation\ModerationInterface;
/**
* Class for interacting with the OpenAI Moderation API.
*/
class OpenAIModerationClient implements ModerationInterface {
/**
* The HTTP client for making requests.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $httpClient;
/**
* The API key for accessing OpenAI.
*
* @var string
*/
protected $apiKey;
/**
* Constructs an OpenAIModerationClient object.
*
* @param \GuzzleHttp\ClientInterface $http_client
* The Guzzle HTTP client.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
*/
public function __construct(ClientInterface $http_client, ConfigFactoryInterface $config_factory) {
$this->httpClient = $http_client;
$this->apiKey = \Drupal::state()->get('gotem_content_moderation.api_key');
}
/**
* {@inheritdoc}
*/
public function moderateText(string $text): ?array {
try {
$authorization = 'Bearer ' . $this->apiKey;
$response = $this->httpClient->post('https://api.openai.com/v1/moderations', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => $authorization,
],
'json' => [
'input' => $text,
],
]);
$data = json_decode($response->getBody(), TRUE);
return $data['results'][0];
}
catch (\Exception $e) {
\Drupal::logger('gotem')->error($e->getMessage());
return NULL;
}
}
}
