l10n_server-2.x-dev/l10n_remote/src/Plugin/rest/resource/L10nServerContributorResource.php

l10n_remote/src/Plugin/rest/resource/L10nServerContributorResource.php
<?php

namespace Drupal\l10n_remote\Plugin\rest\resource;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\l10n_remote\TranslationContribution;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Represents L10 server contributor records as resources.
 *
 * @RestResource (
 *   id = "l10n_remote",
 *   label = @Translation("L10N server contributor"),
 *   serialization_class = "Drupal\l10n_remote\TranslationContribution",
 *   uri_paths = {
 *     "canonical" = "/api/l10n-server-contributor/{id}",
 *     "create" = "/api/l10n-server-contributor"
 *   }
 * )
 */
class L10nServerContributorResource extends ResourceBase implements ContainerInjectionInterface {

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    KeyValueFactoryInterface $keyValueFactory,
    protected EntityTypeManagerInterface $entityTypeManager,
    protected AccountProxyInterface $currentUser,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger, $keyValueFactory);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration = [], $plugin_id = '', $plugin_definition = []) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('l10n_remote'),
      $container->get('keyvalue'),
      $container->get('entity_type.manager'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to POST requests and saves the new record.
   *
   * @param \Drupal\l10n_remote\TranslationContribution $translation_contribution
   *   Data to write into the database.
   *
   * @return \Drupal\rest\ResourceResponse
   *   The HTTP response object.
   */
  public function post(TranslationContribution $translation_contribution) {
    $success = FALSE;

    // Make sure we handle string contexts correctly.
    $context_operator = is_null($translation_contribution->getContext()) ? 'IS NULL' : '=';
    $sids = $this->entityTypeManager->getStorage('l10n_server_string')->getQuery()
      ->accessCheck(FALSE)
      ->condition('value', $translation_contribution->getSource())
      ->condition('context', $translation_contribution->getContext(), $context_operator)
      ->execute();

    $translation_storage = $this->entityTypeManager->getStorage('l10n_server_translation');
    foreach ($sids as $sid) {
      $translation = $translation_storage->create([
        'sid' => $sid,
        'language' => $translation_contribution->getLangcode(),
        'translation' => $translation_contribution->getTranslation(),
        'suggestion' => TRUE,
        'uid' => $this->currentUser->id(),
      ]);

      $translation->save();
      $success = TRUE;
    }

    $replacements = [
      '@uid' => $this->currentUser->id(),
      '@source' => $translation_contribution->getSource(),
      '@langcode' => $translation_contribution->getLangcode(),
    ];

    if ($success) {
      $this->logger->notice($this->t('New translation added by user @uid for @source @langcode', $replacements));
      return new ResourceResponse('Translation created', 201);
    }

    $this->logger->notice($this->t('Failed to add translation by @uid for @source @langcode', $replacements));
    return new ResourceResponse('Not translated', 304);
  }

  /**
   * {@inheritdoc}
   */
  protected function getBaseRoute($canonical_path, $method) {
    $route = parent::getBaseRoute($canonical_path, $method);
    $route->setRequirement('_custom_access', self::class . '::access');

    return $route;
  }

  /**
   * Access check for the contribution endpoint.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(?AccountInterface $account = NULL) {
    if (!$account instanceof AccountInterface) {
      return AccessResult::forbidden();
    }

    // @todo Clarify when we want to allow translation contributions.
    return AccessResult::allowedIf($account->isAuthenticated());
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc