You are here

class Parser in CSV Importer 8

Parser manager.

Hierarchy

Expanded class hierarchy of Parser

1 string reference to 'Parser'
csv_importer.services.yml in ./csv_importer.services.yml
csv_importer.services.yml
1 service uses Parser
csv_importer.parser in ./csv_importer.services.yml
Drupal\csv_importer\Parser

File

src/Parser.php, line 10

Namespace

Drupal\csv_importer
View source
class Parser implements ParserInterface {

  /**
   * Entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs Parser object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function getCsvById(int $id, string $delimiter) {

    /* @var \Drupal\file\Entity\File $entity */
    $entity = $this
      ->getCsvEntity($id);
    $return = [];
    if (($csv = fopen($entity->uri
      ->getString(), 'r')) !== FALSE) {
      while (($row = fgetcsv($csv, 0, $delimiter)) !== FALSE) {
        $return[] = $row;
      }
      fclose($csv);
    }
    return $return;
  }

  /**
   * {@inheritdoc}
   */
  public function getCsvFieldsById(int $id) {
    $csv = $this
      ->getCsvById($id);
    if ($csv && is_array($csv)) {
      return $csv[0];
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getCsvEntity(int $id) {
    if ($id) {
      return $this->entityTypeManager
        ->getStorage('file')
        ->load($id);
    }
    return NULL;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Parser::$entityTypeManager protected property Entity type manager.
Parser::getCsvById public function Get CSV by id. Overrides ParserInterface::getCsvById
Parser::getCsvEntity public function Load CSV. Overrides ParserInterface::getCsvEntity
Parser::getCsvFieldsById public function Get CSV column (first row). Overrides ParserInterface::getCsvFieldsById
Parser::__construct public function Constructs Parser object.