InvoicePrintBuilder.php in Commerce Invoice 8.2
File
src/InvoicePrintBuilder.php
View source
<?php
namespace Drupal\commerce_invoice;
use Drupal\commerce_invoice\Entity\InvoiceInterface;
use Drupal\commerce_invoice\Event\InvoiceEvents;
use Drupal\commerce_invoice\Event\InvoiceFilenameEvent;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\entity_print\FilenameGeneratorInterface;
use Drupal\entity_print\Plugin\PrintEngineInterface;
use Drupal\entity_print\PrintBuilderInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class InvoicePrintBuilder implements InvoicePrintBuilderInterface {
protected $configFactory;
protected $fileStorage;
protected $printBuilder;
protected $filenameGenerator;
protected $eventDispatcher;
protected $currentUser;
public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, PrintBuilderInterface $print_builder, FilenameGeneratorInterface $filename_generator, EventDispatcherInterface $event_dispatcher, AccountInterface $current_user) {
$this->configFactory = $config_factory;
$this->fileStorage = $entity_type_manager
->getStorage('file');
$this->printBuilder = $print_builder;
$this->filenameGenerator = $filename_generator;
$this->eventDispatcher = $event_dispatcher;
$this->currentUser = $current_user;
}
public function generateFilename(InvoiceInterface $invoice) {
$filename = $this->filenameGenerator
->generateFilename([
$invoice,
]);
$filename .= '-' . $invoice
->language()
->getId() . '-' . str_replace('_', '', $invoice
->getState()
->getId());
$event = new InvoiceFilenameEvent($filename, $invoice);
$this->eventDispatcher
->dispatch(InvoiceEvents::INVOICE_FILENAME, $event);
$filename = $event
->getFilename() . '.pdf';
return $filename;
}
public function savePrintable(InvoiceInterface $invoice, PrintEngineInterface $print_engine, $scheme = 'private') {
$filename = $this
->generateFilename($invoice);
$config = $this->configFactory
->get('entity_print.settings');
$uri = $this->printBuilder
->savePrintable([
$invoice,
], $print_engine, $scheme, $filename, $config
->get('default_css'));
if (!$uri) {
return FALSE;
}
$file = $this->fileStorage
->create([
'uri' => $uri,
'uid' => $this->currentUser
->id(),
'langcode' => $invoice
->language()
->getId(),
'status' => FILE_STATUS_PERMANENT,
]);
$file
->save();
return $file;
}
}