You are here

class ThemeCompilerController in Theme Compiler 2.0.x

Same name and namespace in other branches
  1. 8 src/Controller/ThemeCompilerController.php \Drupal\theme_compiler\Controller\ThemeCompilerController

Defines the controller used to compile assets provided by themes.

Copyright (C) 2021 Library Solutions, LLC (et al.).

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

@internal

Hierarchy

Expanded class hierarchy of ThemeCompilerController

1 string reference to 'ThemeCompilerController'
theme_compiler.services.yml in ./theme_compiler.services.yml
theme_compiler.services.yml
1 service uses ThemeCompilerController
theme_compiler.controller in ./theme_compiler.services.yml
\Drupal\theme_compiler\Controller\ThemeCompilerController

File

src/Controller/ThemeCompilerController.php, line 28

Namespace

Drupal\theme_compiler\Controller
View source
class ThemeCompilerController extends ControllerBase implements ThemeCompilerControllerInterface {
  const DEFAULT_MIME_TYPE = 'application/octet-stream';

  /**
   * The compiler service.
   *
   * @var \Drupal\theme_compiler\Compiler
   */
  protected $compiler;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The theme manager service.
   *
   * @var \Drupal\Core\Theme\ThemeManagerInterface
   */
  protected $themeManager;

  /**
   * Constructs a ThemeCompilerController object.
   *
   * @param \Drupal\theme_compiler\Compiler $compiler
   *   The compiler service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
   *   The theme manager service.
   */
  public function __construct(Compiler $compiler, ModuleHandlerInterface $module_handler, ThemeManagerInterface $theme_manager) {
    $this->compiler = $compiler;
    $this->moduleHandler = $module_handler;
    $this->themeManager = $theme_manager;
  }

  /**
   * Serve a theme compiler asset as a cacheable response.
   *
   * @param \Drupal\compiler\CompilerContextInterface $theme_compiler_context
   *   A compiler context used to define a compilation.
   *
   * @see hook_theme_compiler_asset_alter()
   *   For more information about how to alter the asset response.
   *
   * @return \Drupal\Core\Cache\CacheableResponse
   *   A cacheable response for the requested resource.
   */
  public function serve(CompilerContextInterface $theme_compiler_context) : CacheableResponse {

    // The default response should be HTTP 404 (Not Found).
    $response = new CacheableResponse('', CacheableResponse::HTTP_NOT_FOUND);
    try {
      $metadata = $theme_compiler_context
        ->getOption('theme_compiler');
      if (!is_array($metadata) || !array_key_exists('theme', $metadata) || !array_key_exists('path', $metadata)) {
        throw new \InvalidArgumentException('The compiler context is missing the required theme compiler metadata');
      }

      // Prepare the asset path for retrieval from the file system.
      $target = $this->compiler
        ->normalizeAndResolveTargetPath("{$metadata['theme']}/{$metadata['path']}");

      // Ensure that the asset could be read from the file system.
      if (($asset = @file_get_contents($target)) !== FALSE) {

        // Assume that the file content retrieval went according to plan.
        $status = CacheableResponse::HTTP_OK;
        if (strlen($asset) === 0) {

          // If the file is empty, status '204 No Content' is more appropriate.
          $status = CacheableResponse::HTTP_NO_CONTENT;
        }

        // Replace the original response with a new one containing the contents.
        $response = new CacheableResponse($asset, $status, [
          'Content-Type' => self::DEFAULT_MIME_TYPE,
        ]);
      }
    } catch (\Exception $previous) {
      watchdog_exception('theme_compiler', $previous);
    }

    // Define the default cacheability for this response.
    $hash = hash('sha384', $target);
    $cacheability = new CacheableMetadata();
    $cacheability
      ->addCacheTags([
      'theme_compiler_asset',
      "theme_compiler_asset:{$hash}",
    ]);

    // Set the initial cacheability for this response.
    $response
      ->addCacheableDependency($cacheability);

    // Allow modules & themes to alter the compiler response.
    $this->moduleHandler
      ->alter([
      'theme_compiler_response',
      "theme_compiler_response_{$theme_compiler_context->getCompiler()}",
    ], $response);
    $this->themeManager
      ->alter([
      'theme_compiler_response',
      "theme_compiler_response_{$theme_compiler_context->getCompiler()}",
    ], $response);
    return $response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 46
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
ThemeCompilerController::$compiler protected property The compiler service.
ThemeCompilerController::$moduleHandler protected property The module handler service. Overrides ControllerBase::$moduleHandler
ThemeCompilerController::$themeManager protected property The theme manager service.
ThemeCompilerController::DEFAULT_MIME_TYPE constant
ThemeCompilerController::serve public function Serve a theme compiler asset as a cacheable response. Overrides ThemeCompilerControllerInterface::serve
ThemeCompilerController::__construct public function Constructs a ThemeCompilerController object.