You are here

CSVFIReader.php in Feed Import 8

File

feed_import_base/src/CSVFIReader.php
View source
<?php

namespace Drupal\feed_import_base;


/**
 * CSV Reader class, used to read csv files.
 */
class CSVFIReader extends FeedImportUniVectorReader {

  // File handle.
  protected $fh;

  // Column names.
  protected $columns = FALSE;

  /**
   * {@inheritdoc}
   */
  public function init() {

    // Require url.
    if (empty($this->options['url'])) {
      return FALSE;
    }

    // Set default options.
    $this->options += array(
      'length' => 0,
      'delimiter' => ',',
      'enclosure' => '"',
      'escape' => '\\',
      'use_column_names' => FALSE,
      'stream' => NULL,
    );

    // Check for stream options.
    if ($ctx = $this
      ->getStreamContext($this->options['stream'])) {

      // Open the file using stream options.
      $this->fh = fopen($this->options['url'], 'rb', FALSE, $ctx);
    }
    else {

      // Open the file.
      $this->fh = fopen($this->options['url'], 'rb');
    }
    if (!$this->fh) {
      return FALSE;
    }

    // Check to see if column names are used.
    if ($this->options['use_column_names']) {
      if ($this->columns = $this
        ->get()) {
        $this->columns = array_flip($this->columns);
      }
      else {
        return FALSE;
      }
    }
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function get() {
    return fgetcsv($this->fh, $this->options['length'], $this->options['delimiter'], $this->options['enclosure'], $this->options['escape']);
  }

  /**
   * {@inheritdoc}
   */
  public function formatPath($path) {
    $path = parent::formatPath($path);
    if ($this->columns) {
      foreach ($path as &$p) {
        if (isset($this->columns[$p])) {
          $p = $this->columns[$p];
        }
      }
    }
    return $path;
  }

  /**
   * {@inheritdoc}
   */
  public function __destruct() {

    // Close file handle if any.
    if ($this->fh) {
      try {
        fclose($this->fh);
      } catch (Exception $e) {
      }
    }
  }

}

Classes

Namesort descending Description
CSVFIReader CSV Reader class, used to read csv files.