Commit 8f47b9ae authored by Maxime Roux's avatar Maxime Roux
Browse files

Issue #3262296 by MacSim, danflanagan8, apaderno: Get rid of the API key file...

Issue #3262296 by MacSim, danflanagan8, apaderno: Get rid of the API key file + follow coding standards
parent d5516bc8
Loading
Loading
Loading
Loading
+56 −0
Original line number Diff line number Diff line
<?php

namespace Drupal\index_now\Controller;

use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\State\StateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * API key controller.
 */
class ApiKeyController extends ControllerBase {

  /**
   * API key controller constructor.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service.
   */
  public function __construct(StateInterface $state) {
    $this->state = $state;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('state')
    );
  }

  /**
   * Render the API key.
   *
   * @param string $api_key
   *   A string representing the api key.
   */
  public function build(string $api_key) {
    $state_api_key = $this->state->get('index_now_api_key');

    if (empty($state_api_key) || $state_api_key !== $api_key) {
      throw new NotFoundHttpException();
    }

    $response = new CacheableResponse($api_key, Response::HTTP_OK, ['content-type' => 'text/plain']);
    $metadata = $response->getCacheableMetadata();
    $metadata->addCacheTags(['state:index_now_api_key']);

    return $response;
  }

}
+43 −0
Original line number Diff line number Diff line
<?php

namespace Drupal\index_now\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\State\StateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Index Now path processor.
 */
class IndexNowPathProcessor implements InboundPathProcessorInterface {

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * Class constructor.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service.
   */
  public function __construct(StateInterface $state) {
    $this->state = $state;
  }

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    $api_key = $this->state->get('index_now_api_key');
    if (!empty($api_key) && '/index_now_api_key_' . $api_key . '.txt' === $path) {
      return '/index_now_api_key/' . $api_key;
    }

    return $path;
  }

}