VendorFileDownloadController.php in Vendor Stream Wrapper 8
File
src/Controller/VendorFileDownloadController.php
View source
<?php
namespace Drupal\vendor_stream_wrapper\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
class VendorFileDownloadController extends ControllerBase implements VendorFileDownloadControllerInterface {
protected $mimeTypeGuesser;
protected $logger;
public function __construct(MimeTypeGuesserInterface $mimeTypeGuesser, LoggerChannelFactoryInterface $loggerFactory) {
$this->mimeTypeGuesser = $mimeTypeGuesser;
$this->logger = $loggerFactory
->get('Vendor File Download');
}
public static function create(ContainerInterface $container) {
return new static($container
->get('file.mime_type.guesser'), $container
->get('logger.factory'));
}
public function download(Request $request) {
$filepath = str_replace(':', '/', $request
->get('filepath'));
$scheme = 'vendor';
$uri = $scheme . '://' . $filepath;
$mime_type = '';
try {
$mime_type = $this->mimeTypeGuesser
->guess($uri);
} catch (\Exception $e) {
$this->logger
->error('Vendor file download error: %message', [
'%message' => $e
->getMessage(),
]);
}
if (!empty($mime_type)) {
$headers = [
'Content-Type' => $mime_type,
];
try {
return new BinaryFileResponse($uri, 200, $headers, TRUE);
} catch (FileNotFoundException $e) {
throw new NotFoundHttpException();
}
}
throw new NotFoundHttpException();
}
}