View source
<?php
namespace Drupal\data_policy_export\Plugin\Action;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\data_policy\Entity\UserConsentInterface;
use Drupal\views_bulk_operations\Action\ViewsBulkOperationsActionBase;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\Form\FormStateInterface;
use Psr\Log\LoggerInterface;
use Drupal\Core\Url;
use Drupal\csv_serialization\Encoder\CsvEncoder;
use League\Csv\Writer;
use Drupal\Core\Link;
use Drupal\data_policy_export\Plugin\DataPolicyExportPluginManager;
class ExportDataPolicy extends ViewsBulkOperationsActionBase implements ContainerFactoryPluginInterface, PluginFormInterface {
use MessengerTrait;
protected $dataPolicyExportPlugin;
protected $logger;
protected $currentUser;
protected $dateFormatter;
public function __construct(array $configuration, $plugin_id, $plugin_definition, DataPolicyExportPluginManager $dataPolicyExportPlugin, LoggerInterface $logger, AccountProxyInterface $currentUser, ConfigFactoryInterface $configFactory, DateFormatterInterface $date_formatter) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->dataPolicyExportPlugin = $dataPolicyExportPlugin;
$this->logger = $logger;
$this->currentUser = $currentUser;
$this->dateFormatter = $date_formatter;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('plugin.manager.data_policy_export_plugin'), $container
->get('logger.factory')
->get('action'), $container
->get('current_user'), $container
->get('config.factory'), $container
->get('date.formatter'));
}
public function executeMultiple(array $entities) {
if (empty($this->context['sandbox']['results']['headers'])) {
$this->context['sandbox']['results']['headers'] = [
'Name',
'State',
'Datetime',
];
}
if (empty($this->context['sandbox']['results']['file_path'])) {
$this->context['sandbox']['results']['file_path'] = $this
->generateFilePath();
$file_path = $this
->getBaseOutputDirectory() . DIRECTORY_SEPARATOR . $this->context['sandbox']['results']['file_path'];
$csv = Writer::createFromPath($file_path, 'w');
$csv
->setDelimiter(',');
$csv
->setEnclosure('"');
$csv
->setEscape('\\');
$csv
->insertOne($this->context['sandbox']['results']['headers']);
}
else {
$file_path = $this
->getBaseOutputDirectory() . DIRECTORY_SEPARATOR . $this->context['sandbox']['results']['file_path'];
$csv = Writer::createFromPath($file_path, 'a');
}
$csv
->addFormatter([
new CsvEncoder(),
'formatRow',
]);
foreach ($entities as $entity_id => $entity) {
$row = [];
$owner = $entity
->getOwner();
$ownerName = '';
if ($owner) {
$ownerName = $owner
->getDisplayName();
}
$row[] = $ownerName;
$row[] = $this
->getStateName($entity->state->value);
$row[] = $this->dateFormatter
->format($entity
->getChangedTime(), 'short');
$csv
->insertOne($row);
}
if ($this->context['sandbox']['current_batch'] * $this->context['sandbox']['batch_size'] >= $this->context['sandbox']['total']) {
$data = @file_get_contents($file_path);
$name = basename($this->context['sandbox']['results']['file_path']);
$path = 'private://csv';
if (file_prepare_directory($path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS) && file_save_data($data, $path . '/' . $name)) {
$url = Url::fromUri(file_create_url($path . '/' . $name));
$link = Link::fromTextAndUrl($this
->t('Download file'), $url);
$this
->messenger()
->addMessage($this
->t('Export is complete. @link', [
'@link' => $link
->toString(),
]));
}
else {
$this
->messenger()
->addMessage($this
->t('Could not save the export file.'), 'error');
$this->logger
->error('Could not save the export file on: %name.', [
'%name' => $name,
]);
}
}
}
public function getStateName($state_id) {
$options = [
UserConsentInterface::STATE_UNDECIDED => t('Undecided'),
UserConsentInterface::STATE_NOT_AGREE => t('Not agree'),
UserConsentInterface::STATE_AGREE => t('Agree'),
];
return $options[$state_id];
}
public function execute($object = NULL) {
$this
->executeMultiple([
$object,
]);
}
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
return $object
->access('view', $account, $return_as_object);
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
return $form;
}
protected function getBaseOutputDirectory() : string {
return file_directory_temp();
}
protected function generateFilePath() : string {
$hash = md5(microtime(TRUE));
return 'export-data-policies-' . substr($hash, 20, 12) . '.csv';
}
}