WebformAttachmentController.php in Webform 8.5
File
modules/webform_attachment/src/Controller/WebformAttachmentController.php
View source
<?php
namespace Drupal\webform_attachment\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\ElementInfoManagerInterface;
use Drupal\webform\Plugin\WebformElementManagerInterface;
use Drupal\webform\WebformInterface;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform_attachment\Plugin\WebformElement\WebformAttachmentBase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\DependencyInjection\ContainerInterface;
class WebformAttachmentController extends ControllerBase implements ContainerInjectionInterface {
protected $elementInfo;
protected $elementManager;
public function __construct(ElementInfoManagerInterface $element_info, WebformElementManagerInterface $element_manager) {
$this->elementInfo = $element_info;
$this->elementManager = $element_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.element_info'), $container
->get('plugin.manager.webform.element'));
}
public function download(WebformInterface $webform, WebformSubmissionInterface $webform_submission, $element, $filename) {
if ($webform
->id() !== $webform_submission
->getWebform()
->id()) {
throw new NotFoundHttpException();
}
$element = $webform_submission
->getWebform()
->getElement($element) ?: [];
$element_plugin = $this->elementManager
->getElementInstance($element, $webform_submission);
if (!$element_plugin instanceof WebformAttachmentBase) {
throw new NotFoundHttpException();
}
if (!Element::isVisibleElement($element)) {
throw new AccessDeniedHttpException();
}
if (!$element_plugin
->checkAccessRules('view', $element)) {
throw new AccessDeniedHttpException();
}
list($type) = explode(':', $element['#type']);
$element_info = $this->elementInfo
->createInstance($type);
$attachment_name = $element_info::getFileName($element, $webform_submission);
$attachment_mime = $element_info::getFileMimeType($element, $webform_submission);
$attachment_content = $element_info::getFileContent($element, $webform_submission);
$attachment_size = strlen($attachment_content);
$attachment_download = !empty($element['#download']) ? 'attachment;' : '';
if (empty($attachment_name) || empty($attachment_content) || empty($attachment_mime)) {
throw new NotFoundHttpException();
}
$headers = [
'Content-Length' => $attachment_size,
'Content-Type' => $attachment_mime,
'Content-Disposition' => $attachment_download . 'filename="' . $filename . '"',
];
return new Response($attachment_content, 200, $headers);
}
}