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\ActionCode
public function executeMultiple(array $entities) {
// Check if headers exists.
if (empty($this->context['sandbox']['results']['headers'])) {
$this->context['sandbox']['results']['headers'] = [
'Name',
'State',
'Datetime',
];
}
// Create the file if applicable.
if (empty($this->context['sandbox']['results']['file_path'])) {
// Store only the name relative to the output directory. On platforms such
// as Pantheon, different batch ticks can happen on different webheads.
// This can cause the file mount path to change, thus changing where on
// disk the tmp folder is actually located.
$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');
}
// Add formatter.
$csv
->addFormatter([
new CsvEncoder(),
'formatRow',
]);
// Now add the entities to export.
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,
]);
}
}
}