You are here

class TextimageDownloadController in Textimage 8.3

Same name and namespace in other branches
  1. 8.4 src/Controller/TextimageDownloadController.php \Drupal\textimage\Controller\TextimageDownloadController

Defines a controller to serve image styles.

Hierarchy

Expanded class hierarchy of TextimageDownloadController

File

src/Controller/TextimageDownloadController.php, line 24

Namespace

Drupal\textimage\Controller
View source
class TextimageDownloadController extends FileDownloadController implements ContainerInjectionInterface {

  /**
   * The Textimage factory.
   *
   * @var \Drupal\textimage\TextimageFactory
   */
  protected $textimageFactory;

  /**
   * The image factory.
   *
   * @var \Drupal\Core\Image\ImageFactory
   */
  protected $imageFactory;

  /**
   * The configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The Textimage logger.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * Constructs a TextimageDownloadController object.
   *
   * @param \Drupal\textimage\TextimageFactory $textimage_factory
   *   The Textimage factory.
   * @param \Drupal\Core\Image\ImageFactory $image_factory
   *   The image factory.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Psr\Log\LoggerInterface $logger
   *   The Textimage logger.
   * @param \Drupal\Core\File\FileSystemInterface|null $file_system
   *   The file system service.
   */
  public function __construct(TextimageFactory $textimage_factory, ImageFactory $image_factory, ConfigFactoryInterface $config_factory, LoggerInterface $logger, FileSystemInterface $file_system = NULL) {

    // @todo in next major, add the 'stream_wrapper_manager' service to the
    // constructor to ensure D8.8+ compatibility.
    parent::__construct();
    $this->textimageFactory = $textimage_factory;
    $this->imageFactory = $image_factory;
    $this->configFactory = $config_factory;
    $this->logger = $logger;
    $this->fileSystem = $file_system ?: \Drupal::service('file_system');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('textimage.factory'), $container
      ->get('image.factory'), $container
      ->get('config.factory'), $container
      ->get('logger.channel.textimage'), $container
      ->get('file_system'));
  }

  /**
   * Deliver directly a Textimage from the URL request.
   *
   * After generating an image, transfer it to the requesting agent.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object. The 'text' query parameter coming from the URL
   *   contains the text elements to be used to deliver the Textimage.
   * @param \Drupal\image\ImageStyleInterface $image_style
   *   The image style to deliver.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   *   Thrown when Textimage URL generation is not enabled.
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Thrown when the image style is missing.
   *
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response
   *   The transferred file as response or some error response.
   */
  public function urlDeliver(Request $request, ImageStyleInterface $image_style) {

    // Check if the URL generation is enabled.
    if (!$this->configFactory
      ->get('textimage.settings')
      ->get('url_generation.enabled')) {
      throw new AccessDeniedHttpException('Textimage URL generation is not enabled on this site');
    }

    // Check if the style exists, is relevant, and set to 'public' scheme in
    // TPS.
    if (!$this->textimageFactory
      ->isTextimage($image_style)) {
      $this->logger
        ->error("URL generation - The image style '%style_name' is not relevant for Textimage.", [
        '%style_name' => $image_style
          ->getName(),
      ]);
      throw new NotFoundHttpException("The image style requested is not relevant for Textimage");
    }
    if ($image_style
      ->getThirdPartySetting('textimage', 'uri_scheme', $this->configFactory
      ->get('system.file')
      ->get('default_scheme')) !== 'public') {
      $this->logger
        ->error("URL generation - The image style '%style_name' is not set to produce image files for the 'public' file scheme -> disabled.", [
        '%style_name' => $image_style
          ->getName(),
      ]);
      throw new AccessDeniedHttpException("The image style requested is not set to produce image files for the 'public' file scheme");
    }

    // {Text_0}[sep]{Text_1}[sep]...[sep]{Text_n} to the $text array.
    $text_string = $request->query
      ->get('text');
    $text = explode($this->configFactory
      ->get('textimage.settings')
      ->get('url_generation.text_separator'), $text_string);

    // Manage the [extension].
    $last_text = array_pop($text);
    $extension = pathinfo($last_text, PATHINFO_EXTENSION);
    if ($extension) {
      $text[] = str_replace('.' . $extension, '', pathinfo($last_text, PATHINFO_BASENAME));
    }
    else {
      $this->logger
        ->error("URL generation - No file extension specified.");
      throw new NotFoundHttpException('No file extension specified');
    }

    // Get the Textimage URI.
    $file_uri = 'public://textimage/' . $image_style
      ->id() . '/' . $text_string;
    try {
      $image_uri = $this->textimageFactory
        ->get()
        ->setStyle($image_style)
        ->setTargetUri($file_uri)
        ->process($text)
        ->buildImage()
        ->getUri();
      return $this
        ->returnBinary($request, $image_uri);
    } catch (TextimageException $e) {
      $this->logger
        ->error("URL generation - Failed to build an image at '%file_uri'.", [
        '%file_uri' => $file_uri,
      ]);
      throw new NotFoundHttpException('Image not found');
    }
  }

  /**
   * Deliver a Textimage from a deferred request.
   *
   * After generating an image, transfer it to the requesting agent.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Thrown when the textimage ID is not found.
   *
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response
   *   The transferred file as response or some error response.
   */
  public function deferredDelivery(Request $request) {

    // Identify Textimage id.
    $file = $request->query
      ->get('file');
    $tiid = str_replace('.' . pathinfo($file, PATHINFO_EXTENSION), '', pathinfo($file, PATHINFO_BASENAME));

    // Get the Textimage URI.
    try {
      $image_uri = $this->textimageFactory
        ->load($tiid)
        ->buildImage()
        ->getUri();
      return $this
        ->returnBinary($request, $image_uri);
    } catch (TextimageException $e) {
      $this->logger
        ->error("Failed to build an image at '%file_uri'.", [
        '%file_uri' => $file,
      ]);
      throw new NotFoundHttpException('Image not found');
    }
  }

  /**
   * Returns the image file at URI.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   * @param string $uri
   *   The URI of the file to be returned.
   *
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\Response
   *   The transferred file as response or some error response.
   */
  protected function returnBinary(Request $request, $uri) {

    // Don't try to send file if it is missing.
    if (!file_exists($uri)) {
      $this->logger
        ->notice("Textimage image at '%source_image_path' not found.", [
        '%source_image_path' => $uri,
      ]);
      return new Response($this
        ->t('Error downloading a textimage.'), 404);
    }
    if (($scheme = $this->fileSystem
      ->uriScheme($uri)) == 'private') {

      // If using the private scheme, defer control to FileDownloadController.
      $request->query
        ->set('file', file_uri_target($uri));
      return parent::download($request, $scheme);
    }
    else {

      // Get the image and transfer to client.
      $image = $this->imageFactory
        ->get($uri);
      $uri = $image
        ->getSource();
      $headers = [
        'Content-Type' => $image
          ->getMimeType(),
        'Content-Length' => $image
          ->getFileSize(),
      ];
      return new BinaryFileResponse($uri, 200, $headers);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
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::$moduleHandler protected property The module handler. 2
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::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
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. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
FileDownloadController::$streamWrapperManager protected property The stream wrapper manager.
FileDownloadController::download public function Handles private file transfers.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator 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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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. 1
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.
TextimageDownloadController::$configFactory protected property The configuration factory. Overrides ControllerBase::$configFactory
TextimageDownloadController::$fileSystem protected property The file system service.
TextimageDownloadController::$imageFactory protected property The image factory.
TextimageDownloadController::$logger protected property The Textimage logger.
TextimageDownloadController::$textimageFactory protected property The Textimage factory.
TextimageDownloadController::create public static function Instantiates a new instance of this class. Overrides FileDownloadController::create
TextimageDownloadController::deferredDelivery public function Deliver a Textimage from a deferred request.
TextimageDownloadController::returnBinary protected function Returns the image file at URI.
TextimageDownloadController::urlDeliver public function Deliver directly a Textimage from the URL request.
TextimageDownloadController::__construct public function Constructs a TextimageDownloadController object. Overrides FileDownloadController::__construct
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.