ai_agents_test-1.0.0-alpha1/src/Form/ExportGroupResultsForm.php
src/Form/ExportGroupResultsForm.php
<?php
declare(strict_types=1);
namespace Drupal\ai_agents_test\Form;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
/**
* Form controller for importing tests.
*/
final class ExportGroupResultsForm extends FormBase {
/**
* The constructor.
*/
public function __construct(
protected EntityTypeManagerInterface $entityTypeManager,
) {
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get(EntityTypeManagerInterface::class),
);
}
/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'ai_agents_export_group_results';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
// Write a description for the form.
$form['description']['#markup'] = $this->t('This allows you to export the latest test results for one or many specific test groups. You can select the test groups and the export format.') . '<hr/>';
$form['export_type'] = [
'#type' => 'select',
'#title' => $this->t('Export Type'),
'#description' => $this->t('Select the format for exporting the test results.'),
'#options' => [
'csv' => $this->t('CSV'),
],
'#default_value' => 'csv',
'#required' => TRUE,
];
// Get all the test groups.
$test_group_options = [];
foreach ($this->entityTypeManager->getStorage('ai_agents_test_group')->loadMultiple() as $test) {
$test_group_options[$test->id()] = $test->label();
}
$form['test_group'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Test Group'),
'#description' => $this->t('Select the test group to export results from. This will export the latest results for each test in the group.'),
'#options' => $test_group_options,
'#required' => TRUE,
'#multiple' => TRUE,
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Export'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$export_data = [];
// Get the selected test groups.
foreach ($form_state->getValue('test_group') as $test_group_id => $selected) {
if ($selected) {
// Load the test group entity.
$test_group = $this->entityTypeManager->getStorage('ai_agents_test_group')->load($test_group_id);
// Check so there is a test result for the test group.
$test_results_storage = $this->entityTypeManager->getStorage('ai_agents_test_group_result');
$test_results_query = $test_results_storage->getQuery()
->condition('ai_agents_test_group', $test_group_id)
->sort('id', 'DESC')
->accessCheck(TRUE)
->range(0, 1);
$test_results_ids = $test_results_query->execute();
if (empty($test_results_ids)) {
$form_state->setErrorByName('test_group', $this->t('No test results found for the selected test group: @group', ['@group' => $test_group->label()]));
continue;
}
// Load the latest test result.
/** @var \Drupal\ai_agents_test\Entity\AgentTestGroupResult $test_group_result */
$test_group_result = $test_results_storage->load(reset($test_results_ids));
/** @var \Drupal\ai_agents_test\Entity\AgentTestResult $test_result */
foreach ($test_group_result->get('ai_agents_test_results') as $test_result) {
// Get the test result entity.
$test_result_entity = $test_result->entity;
// Get the test entity.
$test_entity = $test_result_entity->test_id->entity;
// Prepare the export data.
$export_data[] = [
'test_label' => $test_result_entity->label(),
'date_time' => $test_result_entity->created->value,
'result' => $test_result_entity->result->value,
'agent_version_id' => $test_result_entity->agent_version_id->value,
'test_group_id_label' => $test_group->label(),
'chat_provider' => $test_result_entity->chat_provider->value,
'model' => $test_result_entity->model->value,
'description' => $test_entity->description->value,
'triggering_instructions' => $test_entity->triggering_instructions->value,
];
}
}
}
// Right now we only support CSV export.
// @todo Create a plugin system for export formats.
ob_start();
$handle = fopen('php://output', 'w');
$headers = [
'Triggering Instructions',
'Test Label',
'Result',
'Description',
'Date Time',
'Agent Version ID',
'Test Group ID Label',
'Chat Provider',
'Model',
];
fputcsv($handle, $headers, ',');
foreach ($export_data as $data) {
$row = [
$data['triggering_instructions'],
$data['test_label'],
$data['result'],
$data['description'],
date('Y-m-d H:i:s', (int) $data['date_time']),
$data['agent_version_id'],
$data['test_group_id_label'],
$data['chat_provider'],
$data['model'],
];
fputcsv($handle, $row, ',');
}
fclose($handle);
$csv = ob_get_clean();
// Return the CSV as a response.
$filename = 'test_group_results_' . date('Y-m-d_H-i-s') . '.csv';
$response = new Response($csv);
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
// Prevent further processing.
$form_state->setResponse($response);
}
}
