tmgmt_xtm-8.x-5.x-dev/src/Plugin/tmgmt/Translator/JobEdit.php
src/Plugin/tmgmt/Translator/JobEdit.php
<?php
namespace Drupal\tmgmt_xtm\Plugin\tmgmt\Translator;
use Drupal\Core\Entity\EntityFormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\tmgmt\Entity\Job;
use Drupal\tmgmt\JobInterface;
use Drupal\tmgmt_xtm\XtmTranslatorUi;
/**
* Handles the job editing functionalities for XTM translator.
*
* @package Drupal\tmgmt_xtm\Plugin\tmgmt\Translator
*/
class JobEdit {
/**
* Provides an AJAX callback to fetch and display project status.
*
* @param array $form
* The form structure to update.
* @param \Drupal\Core\Form\FormStateInterface $formState
* The current state of the form.
*
* @return array
* The render array containing the updated status message.
*/
public function checkoutInfoAjax(array &$form, FormStateInterface $formState) {
$parameters = \Drupal::routeMatch()->getParameters();
$job = $parameters->get('tmgmt_job');
$connector = new Connector();
$response = $connector->checkProjectStatus($job);
$message = '';
/** @var object $response */
if (!$response) {
$message = t('Could not get project status.');
}
else {
if ($response->status == XtmTranslatorUi::XTM_STATE_ERROR) {
\Drupal::messenger()
->addError(t('The project has an error.') .
' ' . t('Please check the project in XTM for more details.')
);
}
else {
[$finished, $jobsErrors] = $this->checkCheckoutJobs($response);
if (empty($jobsErrors)) {
$message = $this->prepareCheckoutMessage($response, $job, $connector, $finished);
}
else {
$error = \Drupal::translation()->formatPlural(
count($jobsErrors),
'The @files file has an error.',
'The following files: @files has errors.',
['@files' => implode(', ', $jobsErrors)]
);
\Drupal::messenger()->addError($error . ' ' . t('Please check the project in XTM for more details.'));
}
}
}
$messageFormated = '<div class="region region-highlighted">
<div role="contentinfo" aria-label="Status message" class="messages messages--status">
<h2 class="visually-hidden">Status message</h2>
' . $message . '
</div> </div>';
$form['translator_wrapper']['info']['status']['message']['wrapper'] = [
'#markup' => $messageFormated,
];
return $form['translator_wrapper']['info']['status']['message'];
}
/**
* Modifies the translation job edit form to include XTM status checks.
*
* Adds a fieldset to the form for checking the project status in XTM,
* allowing users to manually check the status and retrieve translations
* if necessary.
*
* @param array $form
* The form structure to be modified.
* @param \Drupal\Core\Form\FormStateInterface $formState
* The current state of the form.
*/
public function editForm(array &$form, FormStateInterface $formState) {
$formEntity = $formState->getFormObject();
if (!$formEntity instanceof EntityFormInterface) {
throw new \DomainException('The form entity must implement EntityFormInterface.');
}
/** @var \Drupal\tmgmt\Entity\Job $job */
$job = $formEntity->getEntity();
$translator = $job->getTranslator();
if ('xtm' === $translator->getPluginId() && $job->isContinuous()) {
$form['status'] = [
'#type' => 'fieldset',
'#title' => t('XTM status'),
];
$form['status']['desc'] = [
'#markup' => t('Check for the project status in XTM. If the translation has been completed in XTM,
but it is not available there, XTM translator will automatically retrieve the translation after
clicking the button below.'),
'#prefix' => '<div class="fieldset-description" style="margin-bottom:15px">',
'#suffix' => '</div>',
];
$form['status']['message'] = [
'#type' => 'container',
'#prefix' => '<div id="message-wrapper">',
'#suffix' => '</div>',
];
$form['status']['check'] = [
'#type' => 'button',
'#value' => t('Check project status'),
'#ajax' => [
'callback' => [$this, 'checkoutInfoAjax'],
'method' => 'after',
'wrapper' => 'message-wrapper',
'effect' => 'fade',
'progress' => [
'type' => 'throbber',
'message' => t('Checking project status...'),
],
],
];
}
}
/**
* Converts an XTM state code into a human-readable string.
*
* This method translates the provided XTM state code into a more
* understandable text format that can be displayed to users.
*
* @param string $action
* The XTM state code that needs to be translated.
*
* @return \Drupal\Core\StringTranslation\TranslatableMarkup|string
* The human-readable state description,
* or an empty string if the state code is unrecognized.
*/
private function getReadableState($action) {
switch ($action) {
case XtmTranslatorUi::XTM_STATE_ACTIVE:
return t('active');
case XtmTranslatorUi::XTM_STATE_IN_PROGRESS:
return t('in progress');
case XtmTranslatorUi::XTM_STATE_FINISHED:
return t('finished');
case XtmTranslatorUi::XTM_STATE_ERROR:
return t('error');
case XtmTranslatorUi::XTM_STATE_PARTIALLY_FINISHED:
return t('partially finished');
default:
return '';
}
}
/**
* Prepares a checkout status message based on the XTM project status.
*
* This method generates a status message for the XTM project, reflecting
* the current state of the project, translation retrieval success, and
* the number of finished tasks.
*
* @param object $response
* The response object containing the XTM project status and job details.
* @param \Drupal\tmgmt\Entity\Job $job
* The translation job entity.
* @param \Drupal\tmgmt_xtm\Plugin\tmgmt\Translator\Connector $connector
* The connector service used to interact with the XTM API.
* @param int $finished
* The number of finished tasks within the XTM project.
*
* @return string
* The formatted status message to be displayed.
*/
private function prepareCheckoutMessage($response, Job $job, Connector $connector, $finished) {
$message = [
t(
'The project status is <b>@state</b>.',
['@state' => $this->getReadableState($response->status)]
),
];
if ($job->getState() == JobInterface::STATE_CONTINUOUS
&& $response->status == XtmTranslatorUi::XTM_STATE_FINISHED
) {
if (TRUE === $connector->retrieveContinuousTranslation($job)) {
$message[] = t('The translation has been received.');
}
else {
$message[] = t('<b>We were unable to retrieve translation. Check XTM settings</b>');
}
}
else {
if ($finished > 0) {
$message[] = t(
'Finished tasks: @jobs.',
['@jobs' => $finished . '/' . count($response->jobs)]
);
}
}
return implode(' ', $message);
}
/**
* Checks the status of jobs in the given response.
*
* @param object $response
* The response object containing job status information.
*
* @return array
* An array containing the number of finished jobs
* and a list of job files with errors.
*/
private function checkCheckoutJobs($response) {
$finished = 0;
$jobsErrors = [];
foreach ($response->jobs as $jobFile) {
if ($jobFile->status == XtmTranslatorUi::XTM_STATE_FINISHED) {
$finished++;
}
elseif ($jobFile->status == XtmTranslatorUi::XTM_STATE_ERROR) {
$jobsErrors[] = $jobFile->fileName;
}
}
return [$finished, $jobsErrors];
}
}
