Handle a csv line

@param  array  $csvLine
@return void
@throws InvalidCsvLineException
965228
public function handleLine(array $csvLine)
    {
        $fields = $this->importer->parseLine($csvLine);
        $hash = $this->makeHash($fields);
        $item = $this->importer->getModelInstance()
            ->where($this->importer->getUniqueKey(), $fields[$this->importer->getUniqueKey()])
            ->lockForUpdate()
            ->first();

        if ($item === null) {
            // Create a new item and fill it with the fields
            $item = $this->importer->getModelInstance();
            $item->fill($fields);

            $this->added++;
        } elseif ($hash !== $item->hash) {
            // Update the fields if there is a hash mismatch
            $item->fill($fields);

            $this->updated++;
        } elseif ($hash === $item->hash) {
            $this->unchanged++;
        }

        $item->hash = $hash;

        if (!$this->dryRun) {
            $item->save();
        }
    }
1363102
protected function lineHas0VatRate(array $line)
    {
        $result = false;
        if ($this->is0VatRate($line)) {
            $result = true;
        }
        return $result;
    }
287318
public function processForm(array $input = null, $validator = null, $csv_handler = null)
	{
		if($input)
		{
			$this->form_input = $input;
		}
		else
		{
			$this->fillFormInput();
		}

		$validator = ($validator) ? $validator : new ValidatorFormInputModel($this);
		$csv_handler = ($csv_handler) ? $csv_handler : new CsvFileHandler();

		if ( $validator->validateInput() && $this->checkColumns() )
		{
			// process form
			$csv_file = $csv_handler->getTemporary();
			if($csv_file)
			{
				try
				{
					$csv_handler->updateHeaders($csv_file, $this->form_input["columns"], $this->form_input["table_name"]);
				}
				catch(UnalignedArrayException $e)
				{
					$this->appendError("No_temporary", "Invalid Column names." );
					return $this->getIsExecuted();
				}

				try
				{
					$csv_handler->saveToDb($this->form_input['types']);
					$this->is_executed = true;
				}
				catch( HeadersNotSetException $e)
				{
					$this->appendError("Save_err", "Cannot save data: check if dmbs support transaction.");
				}
				catch( PDOException $e)
				{
					$this->appendError("Save_err", $e->getMessage() );
				}
				catch( Exception $e)
				{
					$this->appendError("Save_err", $e->getMessage() );
				}
			}
			else
			{
				$this->appendError("No_temporary","No data available to save");
			}
		}
		return $this->getIsExecuted();
	}
430344
static function parse_line($line)
    {
        $line = trim($line);
        $result = array();
        $datas = explode(self::$col_sep, $line);
        if (empty(self::$data_sep))
        {
            return $datas;
        }
        foreach ($datas as $data)
        {
            $d = self::parse_data($data);
            if (empty($d[0]))
            {
                continue;
            }
            $result[trim($d[0])] = trim($d[1]);
        }
        return $result;
    }
923971
public function handleEvent(string $line)
    {
        $line = trim($line, "\0");
        if ($line === self::BATCH_END) {
            $this->handleBatch();

            return;
        }

        list($eventsString, $path) = explode(':', $line, 2);
        $events = explode(' ', $eventsString);
        $path = rtrim($path, '/');
        foreach ($events as $event) {
            $this->batchEvents[$path][$event] = true;
        }
    }
1051462
def _generate_csv_header_line(*, header_names, header_prefix='', header=True, sep=',', newline='\n'):
    
    if isinstance(header, str):  # user-provided header line
        header_line = header + newline
    else:
        if not (header is None or isinstance(header, bool)):
            raise ValueError(f"Invalid value for argument `header`: {header}")
        else:
            if header:
                header_line = header_prefix + sep.join(header_names) + newline
            else:
                header_line = ""
    return header_line
765441
public function import()
    {
        DB::beginTransaction();

        try {
            $iteration = 0;

            while (! feof($this->file)) {
                $iteration++;

                $csvLine = str_getcsv(fgets($this->file), ';');
                $columnCount = count($csvLine);

                if ($columnCount === 1 && !$this->importer->validateLine($csvLine)) {
                    continue;
                } elseif ($this->importer->validateLine($csvLine)) {
                    $this->handleLine($csvLine);
                } else {
                    throw new InvalidCsvLineException($iteration);
                }
            }

            $this->lines = $this->importer->getModelInstance()->count();

            $this->removeStale();

            if (!$this->dryRun) {
                DB::commit();
            }

            event(new ImportSuccess($this, $this->importer));
        } catch (\Exception $e) {
            DB::rollBack();

            event(new ImportFailed($this, $this->importer, $e));

            // Re-throw the exception to catch it from outside
            throw $e;
        }
    }
877678
private function fixMuchLinesAfterDescription(int $startLine, int $endLine): void
    {
        $this->file->getFixer()->beginChangeset();

        (new LineHelper($this->file))->removeLines($startLine, $endLine);

        $this->file->getFixer()->endChangeset();
    }
160916
protected function initLines(array $lines)
    {
        $lines = $this->unfold($lines);

        if (stristr($lines[0], 'BEGIN:VCALENDAR') !== false) {
            $component = '';
            foreach ($lines as $line) {
                $line = rtrim($line); // Trim trailing whitespace
                $line = $this->removeUnprintableChars($line);

                if (!$this->disableCharacterReplacement) {
                    $line = $this->cleanData($line);
                }

                if ($this->replaceWindowsTimeZoneIds && strpos($line, 'TZID') !== false) {
                    $line = $this->replaceWindowsTimeZoneId($line);
                }

                $add = $this->keyValueFromString($line);

                $keyword = $add[0];
                $values  = $add[1]; // May be an array containing multiple values

                if (!is_array($values)) {
                    if (!empty($values)) {
                        $values = array($values); // Make an array as not already
                        $blankArray = array(); // Empty placeholder array
                        array_push($values, $blankArray);
                    } else {
                        $values = array(); // Use blank array to ignore this line
                    }
                } elseif (empty($values[0])) {
                    $values = array(); // Use blank array to ignore this line
                }

                // Reverse so that our array of properties is processed first
                $values = array_reverse($values);

                foreach ($values as $value) {
                    switch ($line) {
                        // https://www.kanzaki.com/docs/ical/vtodo.html
                        case 'BEGIN:VTODO':
                            if (!is_array($value)) {
                                $this->todoCount++;
                            }

                            $component = 'VTODO';
                            break;

                        // https://www.kanzaki.com/docs/ical/vevent.html
                        case 'BEGIN:VEVENT':
                            if (!is_array($value)) {
                                $this->eventCount++;
                            }

                            $component = 'VEVENT';
                            break;

                        // https://www.kanzaki.com/docs/ical/vfreebusy.html
                        case 'BEGIN:VFREEBUSY':
                            if (!is_array($value)) {
                                $this->freeBusyIndex++;
                            }

                            $component = 'VFREEBUSY';
                            break;

                        case 'BEGIN:VALARM':
                            if (!is_array($value)) {
                                $this->alarmCount++;
                            }

                            $component = 'VALARM';
                            break;

                        case 'END:VALARM':
                            $component = 'VEVENT';
                            break;

                        case 'BEGIN:DAYLIGHT':
                        case 'BEGIN:STANDARD':
                        case 'BEGIN:VCALENDAR':
                        case 'BEGIN:VTIMEZONE':
                            $component = $value;
                            break;

                        case 'END:DAYLIGHT':
                        case 'END:STANDARD':
                        case 'END:VCALENDAR':
                        case 'END:VFREEBUSY':
                        case 'END:VTIMEZONE':
                        case 'END:VTODO':
                            $component = 'VCALENDAR';
                            break;

                        case 'END:VEVENT':
                            if ($this->shouldFilterByWindow) {
                                $this->removeLastEventIfOutsideWindowAndNonRecurring();
                            }

                            $component = 'VCALENDAR';
                            break;

                        default:
                            $this->addCalendarComponentWithKeyAndValue($component, $keyword, $value);
                            break;
                    }
                }
            }

            $this->processEvents();

            if (!$this->skipRecurrence) {
                $this->processRecurrences();

                // Apply changes to altered recurrence instances
                if (!empty($this->alteredRecurrenceInstances)) {
                    $events = $this->cal['VEVENT'];

                    foreach ($this->alteredRecurrenceInstances as $alteredRecurrenceInstance) {
                        if (isset($alteredRecurrenceInstance['altered-event'])) {
                            $alteredEvent = $alteredRecurrenceInstance['altered-event'];
                            $key          = key($alteredEvent);
                            $events[$key] = $alteredEvent[$key];
                        }
                    }

                    $this->cal['VEVENT'] = $events;
                }
            }

            if ($this->shouldFilterByWindow) {
                $this->reduceEventsToMinMaxRange();
            }

            $this->processDateConversions();
        }
    }
697747
protected function _put($s, $newLine = true)
    {
        if ($newLine) {
            $this->setBuffer($s . "\n");
        } else {
            $this->setBuffer($s);
        }
    }
1122883
protected function splitLine($line)
    {
        $chunks = explode(';', $line);
        if (count($chunks) !== 6) {
            throw new InvalidValueException('Line "' . $line . '" is malformed');
        }

        return array_map('trim', $chunks);
    }
1271103
def handle_lines(self):
        """"""
        while "\r\n" in self.buffer:
            line, self.buffer = self.buffer.split("\r\n", 1)
            if valid_packet(line):
                self.handle_raw_packet(line)
            else:
                log.warning('dropping invalid data: %s', line)
1143333
function parseCSV ($input = null, $offset = null, $limit = null, $conditions = null) {
		if ( $offset !== null ) $this->offset = $offset;
		if ( $limit !== null ) $this->limit = $limit;
		if ( count($conditions) > 0 ) $this->conditions = $conditions;
		if ( !empty($input) ) $this->parse($input);
	}
1027399
public function openFile($mode = 'r')
    {
        if (!$this->handle) {
            $this->handle = fopen($this->file, $mode);
            if ($this->handle === false) {
                throw new Exception(['Can not open CSV file.', 'file' => $this->file, 'mode' => $mode]);
            }
        }
    }
202826
public function parseBody( $line )
    {
        $line = rtrim( $line, "\r\n" );
        if ( $this->text === null )
        {
            $this->text = $line;
        }
        else
        {
            $this->text .= "\n" . $line;
        }
    }
1366869
public function execute(array $input)
    {
        $text = $this->textSanitizer->sanitize($input);
        $location = $this->locationSanitizer->sanitize($input);

        if (!is_callable($input['replacement'])) {
            throw new InvalidArgumentException('Invalid replacement');
        }

        $line = $text->getLine($location);
        $replacement = $input['replacement']($line);

        $text->setLine($replacement, $location);
        $text->setCurrentLineNumber($location);
    }
1014839
function splitCsvLine(line) {
  if (!line.trim().length) {
    return [];
  }
  var fields = [];
  var inQuotes = false;
  var separator = 0;
  for (var i = 0; i < line.length; i++) {
    switch(line[i]) {
      case "\"":
        if (i>0 && line[i-1] != "\\") {
          inQuotes = !inQuotes;
        }
        break;
      case ",":
        if (!inQuotes) {
          if (separator < i) {
            var field = line.substring(separator, i).trim();
            if (field.length) {
              fields.push(field);
            }
          }
          separator = i + 1;
        }
        break;
    }
  }
  fields.push(line.substring(separator).trim());
  return fields;
}