You are here

public function CsvEncoder::encode in CSV Serialization 8

Same name and namespace in other branches
  1. 8.2 src/Encoder/CsvEncoder.php \Drupal\csv_serialization\Encoder\CsvEncoder::encode()

Uses HTML-safe strings, with several characters escaped.

File

src/Encoder/CsvEncoder.php, line 119

Class

CsvEncoder
Adds CSV encoder support for the Serialization API.

Namespace

Drupal\csv_serialization\Encoder

Code

public function encode($data, $format, array $context = []) {
  switch (gettype($data)) {
    case "array":
      break;
    case 'object':
      $data = (array) $data;
      break;

    // May be bool, integer, double, string, resource, NULL, or unknown.
    default:
      $data = [
        $data,
      ];
      break;
  }
  if (!empty($context['views_style_plugin']->options['csv_settings'])) {
    $this
      ->setSettings($context['views_style_plugin']->options['csv_settings']);
  }
  try {

    // Instantiate CSV writer with options.
    $csv = Writer::createFromFileObject(new SplTempFileObject());
    $csv
      ->setDelimiter($this->delimiter);
    $csv
      ->setEnclosure($this->enclosure);
    $csv
      ->setEscape($this->escapeChar);

    // Set data.
    if ($this->useUtf8Bom) {
      $csv
        ->setOutputBOM(Writer::BOM_UTF8);
    }

    // Set headers.
    if ($this->outputHeader) {
      $headers = $this
        ->extractHeaders($data, $context);
      $csv
        ->insertOne($headers);
    }
    $csv
      ->addFormatter([
      $this,
      'formatRow',
    ]);
    foreach ($data as $row) {
      $csv
        ->insertOne($row);
    }
    $output = $csv
      ->__toString();
    return trim($output);
  } catch (\Exception $e) {
    throw new InvalidDataTypeException($e
      ->getMessage(), $e
      ->getCode(), $e);
  }
}