insertOne($row); } return $this; } /** * Adds a single line to a CSV document * * @param string[]|string $row a string, an array or an object implementing to '__toString' method * * @return static */ public function insertOne($row) { if (!is_array($row)) { $row = str_getcsv($row, $this->delimiter, $this->enclosure, $this->escape); } $row = $this->formatRow($row); $this->validateRow($row); $this->addRow($row); return $this; } /** * Add new record to the CSV document * * @param array $row record to add */ protected function addRow(array $row) { $this->initCsv(); if (!$this->fputcsv->invokeArgs($this->csv, $this->getFputcsvParameters($row))) { throw new RuntimeException('Unable to write record to the CSV document.'); } if ("\n" !== $this->newline) { $this->csv->fseek(-1, SEEK_CUR); $this->csv->fwrite($this->newline, strlen($this->newline)); } } /** * Initialize the CSV object and settings */ protected function initCsv() { if (null !== $this->csv) { return; } $this->csv = $this->getIterator(); $this->fputcsv = new ReflectionMethod(get_class($this->csv), 'fputcsv'); $this->fputcsv_param_count = $this->fputcsv->getNumberOfParameters(); } /** * returns the parameters for SplFileObject::fputcsv * * @param array $fields The fields to be add * * @return array */ protected function getFputcsvParameters(array $fields) { $parameters = [$fields, $this->delimiter, $this->enclosure]; if (4 == $this->fputcsv_param_count) { $parameters[] = $this->escape; } return $parameters; } /** * {@inheritdoc} */ public function isActiveStreamFilter() { return parent::isActiveStreamFilter() && null === $this->csv; } /** * {@inheritdoc} */ public function __destruct() { $this->csv = null; parent::__destruct(); } }