You are here

VboExportBase.php in VBO export 8

File

src/Plugin/Action/VboExportBase.php
View source
<?php

namespace Drupal\vbo_export\Plugin\Action;

use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\views\Views;
use Drupal\Core\Url;

/**
 * Base class for export actions.
 */
abstract class VboExportBase extends ActionBase {
  const THEME = '';

  /**
   * Output generated string to file. Message user.
   */
  protected function sendToFile($csv_string, $filename) {
    $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
    $wrappers = $stream_wrapper_manager
      ->getWrappers();
    if (isset($wrappers['private'])) {
      $wrapper = 'private';
    }
    else {
      $wrapper = 'public';
    }
    if (!empty($csv_string)) {
      $destination = $wrapper . '://' . $filename;
      $file = file_save_data($csv_string, $destination, FILE_EXISTS_REPLACE);
      $file
        ->setTemporary();
      $file
        ->save();
      $file_url = Url::fromUri(file_create_url($file
        ->getFileUri()));
      $link = \Drupal::l(t('Click here'), $file_url);
      drupal_set_message(t('Export file created, @link to download.', array(
        '@link' => $link,
      )));
    }
  }

  /**
   * Execute multiple handler.
   *
   * Execute action on multiple entities to generate csv output
   * and display a download link.
   */
  public function executeMultiple(array $entities) {
    $params = \Drupal::routeMatch()
      ->getRouteObject()
      ->getDefaults();
    if (!empty($params['view_id'])) {
      $view = Views::getView($params['view_id']);
      $view
        ->setDisplay($params['display_id']);
      $nids = array();
      foreach ($entities as $entity) {
        $id = $entity
          ->id();
        $nids[$id] = $entity
          ->id();
      }
      $view
        ->build();
      $base_table = $view->storage
        ->get('base_table');
      $alias = $view->query->tables[$base_table][$base_table]['alias'];
      $view->build_info['query']
        ->condition($alias . '.' . $view->storage
        ->get('base_field'), $nids, 'in');
      $view->query
        ->execute($view);
      $view->result = array_values($view->result);

      // Variables for vbo_export theme.
      $renderable = [
        '#theme' => static::THEME,
      ];

      // Build csv structure array.
      $structure = [];
      foreach ($view->field as $id => $field) {
        if ($id == 'node_bulk_form' || $field->options['exclude'] || empty($field->options['entity_field'])) {
          continue;
        }
        $structure[$id] = [
          'id' => $id,
          'label' => $field->options['label'],
          'entity_type' => $field->options['entity_type'],
          'field' => $field->options['entity_field'],
          'plugin_id' => $field->options['plugin_id'],
        ];
      }
      if (!empty($structure) && !empty($view->result)) {

        // Build csv header.
        foreach ($structure as $item) {
          $renderable['#header'][] = $item['label'];
        }

        // Render csv rows.
        $view->style_plugin
          ->preRender($view->result);
        foreach ($view->result as $num => $row) {
          foreach ($structure as $field_id => $item) {
            $renderable['#rows'][$num][$field_id] = $view->style_plugin
              ->getField($num, $field_id)
              ->__toString();
          }
        }
        $renderer = \Drupal::service('renderer');
        $csv_string = $renderer
          ->render($renderable);
        $rand = substr(hash('ripemd160', uniqid()), 0, 8);
        $filename = $params['view_id'] . '_' . date('Y_m_d_H_i', REQUEST_TIME) . '-' . $rand . '.' . static::EXTENSION;
        $this
          ->sendToFile($csv_string, $filename);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function execute($entity = NULL) {
    $this
      ->executeMultiple([
      $entity,
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    $access = $object
      ->access('view', $account, TRUE);
    return $access
      ->isAllowed();
  }

}

Classes

Namesort descending Description
VboExportBase Base class for export actions.