You are here

class CsvParser in Feeds 8.3

Same name in this branch
  1. 8.3 src/Component/CsvParser.php \Drupal\feeds\Component\CsvParser
  2. 8.3 src/Feeds/Parser/CsvParser.php \Drupal\feeds\Feeds\Parser\CsvParser

Defines a CSV feed parser.

Plugin annotation


@FeedsParser(
  id = "csv",
  title = "CSV",
  description = @Translation("Parse CSV files."),
  form = {
    "configuration" = "Drupal\feeds\Feeds\Parser\Form\CsvParserForm",
    "feed" = "Drupal\feeds\Feeds\Parser\Form\CsvParserFeedForm",
  },
)

Hierarchy

Expanded class hierarchy of CsvParser

1 file declares its use of CsvParser
CsvParserTest.php in tests/src/Unit/Feeds/Parser/CsvParserTest.php

File

src/Feeds/Parser/CsvParser.php, line 26

Namespace

Drupal\feeds\Feeds\Parser
View source
class CsvParser extends ParserBase {

  /**
   * {@inheritdoc}
   */
  public function parse(FeedInterface $feed, FetcherResultInterface $fetcher_result, StateInterface $state) {

    // Get sources.
    $sources = [];
    foreach ($feed
      ->getType()
      ->getMappingSources() as $key => $info) {
      if (isset($info['value']) && trim(strval($info['value'])) !== '') {
        $sources[$info['value']] = $key;
      }
    }
    $feed_config = $feed
      ->getConfigurationFor($this);
    if (!filesize($fetcher_result
      ->getFilePath())) {
      throw new EmptyFeedException();
    }

    // Load and configure parser.
    $parser = CsvFileParser::createFromFilePath($fetcher_result
      ->getFilePath())
      ->setDelimiter($feed_config['delimiter'] === 'TAB' ? "\t" : $feed_config['delimiter'])
      ->setHasHeader(!$feed_config['no_headers'])
      ->setStartByte((int) $state->pointer);

    // Wrap parser in a limit iterator.
    $parser = new \LimitIterator($parser, 0, $this->configuration['line_limit']);
    $header = !$feed_config['no_headers'] ? $parser
      ->getHeader() : [];
    $result = new ParserResult();
    foreach ($parser as $row) {
      $item = new DynamicItem();
      foreach ($row as $delta => $cell) {
        $key = isset($header[$delta]) ? $header[$delta] : $delta;

        // Pick machine name of source, if one is found.
        if (isset($sources[$key])) {
          $key = $sources[$key];
        }
        $item
          ->set($key, $cell);
      }
      $result
        ->addItem($item);
    }

    // Report progress.
    $state->total = filesize($fetcher_result
      ->getFilePath());
    $state->pointer = $parser
      ->lastLinePos();
    $state
      ->progress($state->total, $state->pointer);

    // Set progress to complete if no more results are parsed. Can happen with
    // empty lines in CSV.
    if (!$result
      ->count()) {
      $state
        ->setCompleted();
    }
    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getMappingSources() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  protected function configSourceLabel() {
    return $this
      ->t('CSV source');
  }

  /**
   * {@inheritdoc}
   */
  protected function configSourceDescription() {
    if ($this
      ->getConfiguration('no_headers')) {
      return $this
        ->t('Enter which column number of the CSV file to use: 0, 1, 2, etc.');
    }
    return $this
      ->t('Enter the exact CSV column name. This is case-sensitive.');
  }

  /**
   * {@inheritdoc}
   */
  public function defaultFeedConfiguration() {
    return [
      'delimiter' => $this->configuration['delimiter'],
      'no_headers' => $this->configuration['no_headers'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'delimiter' => ',',
      'no_headers' => 0,
      'line_limit' => 100,
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CsvParser::configSourceDescription protected function Returns the description for single source. Overrides ParserBase::configSourceDescription
CsvParser::configSourceLabel protected function Returns the label for single source. Overrides ParserBase::configSourceLabel
CsvParser::defaultConfiguration public function Gets default configuration for this plugin. Overrides PluginBase::defaultConfiguration
CsvParser::defaultFeedConfiguration public function Returns default feed configuration. Overrides PluginBase::defaultFeedConfiguration
CsvParser::getMappingSources public function Declare the possible mapping sources that this parser produces. Overrides ParserInterface::getMappingSources
CsvParser::parse public function Parses content returned by fetcher. Overrides ParserInterface::parse
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
ParserBase::mappingFormAlter public function Alter mapping form. Overrides MappingPluginFormInterface::mappingFormAlter
ParserBase::mappingFormSubmit public function Submit handler for the mapping form. Overrides MappingPluginFormInterface::mappingFormSubmit
ParserBase::mappingFormValidate public function Validate handler for the mapping form. Overrides MappingPluginFormInterface::mappingFormValidate
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$feedType protected property The importer this plugin is working for.
PluginBase::$linkGenerator protected property The link generator.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$urlGenerator protected property The url generator.
PluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 2
PluginBase::container private function Returns the service container.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::l protected function Renders a link to a route given a route name and its parameters.
PluginBase::linkGenerator protected function Returns the link generator service.
PluginBase::onFeedDeleteMultiple public function A feed is being deleted. 3
PluginBase::onFeedSave public function A feed is being saved.
PluginBase::onFeedTypeDelete public function The feed type is being deleted. 1
PluginBase::onFeedTypeSave public function The feed type is being saved. 1
PluginBase::pluginType public function Returns the type of plugin. Overrides FeedsPluginInterface::pluginType
PluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
PluginBase::url protected function Generates a URL or path for a specific route based on the given parameters.
PluginBase::urlGenerator protected function Returns the URL generator service.
PluginBase::__construct public function Constructs a PluginBase object. Overrides PluginBase::__construct 4
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.