alt_text_generator-1.0.3/src/Controller/AltTextGeneratorController.php
src/Controller/AltTextGeneratorController.php
<?php
namespace Drupal\alt_text_generator\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\File\FileSystemInterface;
use Drupal\file\Entity\File;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Config\ConfigFactoryInterface;
/**
* Controller for generating alt text.
*/
class AltTextGeneratorController extends ControllerBase {
/**
* The HTTP client.
*
* @var \GuzzleHttp\Client
*/
protected $httpClient;
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Constructs an AltTextGeneratorController object.
*
* @param \GuzzleHttp\Client $http_client
* The HTTP client.
* @param \Drupal\Core\File\FileSystemInterface $file_system
* The file system service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
*/
public function __construct(
Client $http_client,
FileSystemInterface $file_system,
ConfigFactoryInterface $config_factory
) {
$this->httpClient = $http_client;
$this->fileSystem = $file_system;
$this->configFactory = $config_factory;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('http_client'),
$container->get('file_system'),
$container->get('config.factory')
);
}
/**
* Generates alt text for an image.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* The JSON response.
*/
public function generate(Request $request) {
try {
$fid = $request->request->get('fid');
$language = $request->request->get('language');
if (!$fid) {
throw new \InvalidArgumentException('Missing file ID.');
}
$file = File::load($fid);
if (!$file) {
throw new \InvalidArgumentException('Invalid file ID.');
}
$file_uri = $file->getFileUri();
$file_path = $this->fileSystem->realpath($file_uri);
if (!$file_path || !file_exists($file_path)) {
throw new \InvalidArgumentException('File not found.');
}
$config = $this->configFactory->get('alt_text_generator.settings');
$apiKey = $config->get('api_key');
if (!$apiKey) {
throw new \InvalidArgumentException('API key not configured.');
}
// Create a base64 encoded version of the image
$imageData = base64_encode(file_get_contents($file_path));
$mimeType = mime_content_type($file_path);
$dataUri = "data:{$mimeType};base64,{$imageData}";
// Make API call with base64 image data
$response = $this->httpClient->post('https://alttextgeneratorai.com/api/drupal', [
'json' => [
'image' => $dataUri,
'wpkey' => $apiKey,
'language' => $language,
],
]);
if ($response->getStatusCode() === 200) {
$result = $response->getBody()->getContents();
return new JsonResponse(['success' => TRUE, 'altText' => $result]);
}
throw new \RuntimeException('Invalid API response.');
}
catch (GuzzleException $e) {
\Drupal::logger('alt_text_generator')->error('API error: @error', ['@error' => $e->getMessage()]);
return new JsonResponse(['success' => FALSE, 'error' => 'API error occurred.'], 500);
}
catch (\Exception $e) {
\Drupal::logger('alt_text_generator')->error('Error: @error', ['@error' => $e->getMessage()]);
return new JsonResponse(['success' => FALSE, 'error' => $e->getMessage()], 400);
}
}
} 