ExportController.php in Bibliography & Citation 8
File
modules/bibcite_export/src/Controller/ExportController.php
View source
<?php
namespace Drupal\bibcite_export\Controller;
use Drupal\bibcite\Plugin\BibciteFormatInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Serializer\SerializerInterface;
class ExportController extends ControllerBase {
protected $serializer;
protected $entityTypeManager;
public function __construct(SerializerInterface $serializer, EntityTypeManagerInterface $entity_type_manager) {
$this->serializer = $serializer;
$this->entityTypeManager = $entity_type_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('serializer'), $container
->get('entity_type.manager'));
}
protected function processExport(array $entities, BibciteFormatInterface $bibcite_format, $filename = NULL) {
if (!$filename) {
$filename = $bibcite_format
->getLabel();
}
$response = new Response();
if ($result = $this->serializer
->serialize($entities, $bibcite_format
->getPluginId())) {
$response->headers
->set('Cache-Control', 'no-cache');
$response->headers
->set('Content-type', 'text/plain');
$response->headers
->set('Content-Disposition', 'attachment; filename="' . $filename . '.' . $bibcite_format
->getExtension() . '";');
$response
->sendHeaders();
$result = is_array($result) ? implode("\n", $result) : $result;
$response
->setContent($result);
}
return $response;
}
public function export(BibciteFormatInterface $bibcite_format, $entity_type, EntityInterface $entity) {
if (!$entity
->access('view')) {
throw new AccessDeniedHttpException();
}
if (!$bibcite_format
->isExportFormat()) {
throw new NotFoundHttpException();
}
$filename = vsprintf('%s-%s-%s', [
$entity_type,
$entity
->id(),
$bibcite_format
->getLabel(),
]);
return $this
->processExport([
$entity,
], $bibcite_format, $filename);
}
public function exportMultiple(BibciteFormatInterface $bibcite_format, $entity_type, Request $request) {
if (!$bibcite_format
->isExportFormat()) {
throw new NotFoundHttpException();
}
$storage = $this->entityTypeManager
->getStorage($entity_type);
if (!$request->query
->has('id')) {
throw new NotFoundHttpException();
}
$ids = explode(' ', $request->query
->get('id'));
$entities = $storage
->loadMultiple($ids);
if (!$entities) {
throw new NotFoundHttpException();
}
$filename = vsprintf('%s-%s', [
$entity_type,
$bibcite_format
->getLabel(),
]);
return $this
->processExport($entities, $bibcite_format, $filename);
}
}