FileDownloadController.php in Commerce File 8.2
File
src/Controller/FileDownloadController.php
View source
<?php
namespace Drupal\commerce_file\Controller;
use Drupal\commerce_file\DownloadLoggerInterface;
use Drupal\commerce_file\LicenseFileManagerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
use Drupal\file\FileInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class FileDownloadController extends ControllerBase {
protected $licenseFileManager;
protected $downloadLogger;
protected $streamWrapperManager;
public function __construct(AccountInterface $current_user, LicenseFileManagerInterface $license_file_manager, DownloadLoggerInterface $download_logger, StreamWrapperManagerInterface $stream_wrapper_manager) {
$this->currentUser = $current_user;
$this->licenseFileManager = $license_file_manager;
$this->downloadLogger = $download_logger;
$this->streamWrapperManager = $stream_wrapper_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('current_user'), $container
->get('commerce_file.license_file_manager'), $container
->get('commerce_file.download_logger'), $container
->get('stream_wrapper_manager'));
}
public function download(FileInterface $file) {
$uri = $file
->getFileUri();
$scheme = $this->streamWrapperManager
->getScheme($uri);
if ($scheme === 's3') {
$licenses = $this->licenseFileManager
->getActiveLicenses($file);
if (!$licenses) {
throw new AccessDeniedHttpException();
}
$license = reset($licenses);
if ($this->licenseFileManager
->shouldLogDownload($license)) {
$this->downloadLogger
->log($license, $file);
}
return new TrustedRedirectResponse($file
->createFileUrl(FALSE));
}
if (!$this->streamWrapperManager
->isValidScheme($scheme) || !file_exists($uri)) {
throw new NotFoundHttpException("The file {$uri} does not exist.");
}
$headers = $this
->moduleHandler()
->invokeAll('file_download', [
$uri,
]);
if (!count($headers)) {
throw new AccessDeniedHttpException();
}
foreach ($headers as $result) {
if ($result == -1) {
throw new AccessDeniedHttpException();
}
}
$filename = $file
->getFilename();
$response = new BinaryFileResponse($uri, Response::HTTP_OK, $headers, FALSE);
if (empty($headers['Content-Disposition'])) {
$response
->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
}
return $response;
}
}