monster_menus-9.0.x-dev/src/Plugin/MMSearchAction/ResultsCSV.php
src/Plugin/MMSearchAction/ResultsCSV.php
<?php
namespace Drupal\monster_menus\Plugin\MMSearchAction;
use Drupal\Core\Form\EnforcedResponseException;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\monster_menus\Annotation\MMSearchAction;
use Drupal\monster_menus\Controller\DefaultController;
use Drupal\monster_menus\MMSearchAction\MMSearchActionBase;
use Symfony\Component\HttpFoundation\Response;
/**
* Provides the MM Search Results Action to download results as a CSV file.
*
* @MMSearchAction(
* id = "mm_search_action_get_csv",
* label = @Translation("download results as a CSV file"),
* description = @Translation("Provides the MM Search Results Action to download results as a CSV file."),
* )
*/
class ResultsCSV extends MMSearchActionBase {
/**
* @inheritDoc
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['actions'] = [
'#type' => 'actions',
'result' => [
'#type' => 'submit',
'#value' => $this->t('Download Results'),
'#attributes' => ['onclick' => 'MMSR_recalculate_action(this); return false;'],
],
];
return $form;
}
/**
* @inheritDoc
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$hdrs = [];
$t_page = $this->t('Page')->render();
$t_title = $this->t('Title')->render();
foreach ($this->getConfiguration('header') as $row) {
$h = $row['data']->render();
$hdrs[] = $h;
if ($h == $t_page || $h == $t_title) {
$hdrs[] = $this->t('URL');
}
}
ob_start();
$fp = fopen('php://output', 'w');
fputcsv($fp, $hdrs);
$t_unknown = $this->t('(unknown)')->render();
$this->iterate(function ($row) use ($t_unknown, $fp) {
$title = trim($row->title);
fputcsv($fp, [
$title == '' ? $t_unknown : $title,
Url::fromRoute('entity.node.canonical', ['node' => $row->nid], ['absolute' => TRUE])
->toString(),
DefaultController::getNodeTypeLabel($row->type),
mm_format_date($row->changed, 'short'),
mm_format_date($row->created, 'short'),
mm_content_uid2name($row->uid, 'fmlu', $row, $hover)
]);
}, function ($row) use ($t_unknown, $fp) {
$title = trim($row->pgname);
fputcsv($fp, [
$title == '' ? $t_unknown : $title,
mm_content_get_mmtid_url($row->mmtid, ['absolute' => TRUE])->toString(),
mm_content_uid2name($row->uid, 'fmlu', $row, $hover)
]);
});
fclose($fp);
$resp = new Response(ob_get_clean(), 200, [
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename=mm_search_result_' . date('YmdHis') . '.csv',
'Pragma' => 'no-cache',
'Expires' => '0',
]);
throw new EnforcedResponseException($resp);
}
/**
* @inheritDoc
*/
public function applies() {
return TRUE;
}
/**
* @inheritDoc
*/
public function access() {
return TRUE;
}
}