public function ExportDataPolicy::executeMultiple in Data Policy 8
1 call to ExportDataPolicy::executeMultiple()
- ExportDataPolicy::execute in modules/data_policy_export/src/Plugin/Action/ExportDataPolicy.php
File
- modules/data_policy_export/src/Plugin/Action/ExportDataPolicy.php, line 109
Class
- ExportDataPolicy
- Exports data policies to CSV.
Namespace
Drupal\data_policy_export\Plugin\Action
Code
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,
]);
}
}
}