commercetools-8.x-1.2-alpha1/modules/commercetools_decoupled/src/Controller/CtAuthController.php

modules/commercetools_decoupled/src/Controller/CtAuthController.php
<?php

namespace Drupal\commercetools_decoupled\Controller;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\commercetools_decoupled\CtAuth;

/**
 * Returns Authorization header for FE.
 */
class CtAuthController extends ControllerBase {

  /**
   * CtAuthController constructor.
   *
   * @param \Drupal\commercetools_decoupled\CtAuth $ctAuth
   *   The commercetools authorization service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   System time service.
   */
  public function __construct(
    private readonly CtAuth $ctAuth,
    protected TimeInterface $time,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get('commercetools_decoupled.auth'),
      $container->get('datetime.time'),
    );
  }

  /**
   * Returns a FE authorization header as JSON.
   *
   * Payload:
   *   {
   *     "feApiAuthorizationHeader": "Bearer <token>"
   *   }
   *
   * @return \Drupal\Core\Cache\CacheableJsonResponse
   *   JSON response containing the FE authorization header.
   */
  public function getAuth(): CacheableJsonResponse {
    $response = new CacheableJsonResponse([
      'feApiAuthorizationHeader' => $this->ctAuth->getAuthorizationHeader(),
    ]);

    $expiresAt = $this->ctAuth->getCacheExpire();
    $ttl = max(0, $expiresAt - $this->time->getRequestTime());

    $cacheability = (new CacheableMetadata())
      ->setCacheMaxAge($ttl);
    $response->addCacheableDependency($cacheability);

    $response->setPrivate();
    $response->setMaxAge($ttl);

    return $response;
  }

}

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

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