70 lines
1.4 KiB
PHP
70 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace Deblan\Csv;
|
|
|
|
/**
|
|
* class Csv.
|
|
*
|
|
* @author Simon Vieille <simon@deblan.fr>
|
|
*/
|
|
class CsvStreamParser extends CsvParser
|
|
{
|
|
/**
|
|
* @var resource
|
|
*/
|
|
protected $resource;
|
|
|
|
/**
|
|
* @var int
|
|
*/
|
|
protected $length;
|
|
|
|
/**
|
|
* Parse a stream.
|
|
*
|
|
* @param resource $resource
|
|
* @param int $length
|
|
*/
|
|
public function parseStream($resource, ? int $length = 0): void
|
|
{
|
|
if (!is_resource($resource)) {
|
|
throw new \InvalidArgumentException('First argument must be a valid resource.');
|
|
}
|
|
|
|
$this->resource = $resource;
|
|
$this->length = $length;
|
|
}
|
|
|
|
/**
|
|
* Get data of the stream parsing.
|
|
*
|
|
* @return null|array
|
|
*/
|
|
public function getData(): ? array
|
|
{
|
|
$csv = fgetcsv($this->resource, $this->length, $this->delimiter, $this->enclosure);
|
|
|
|
if ($csv === false) {
|
|
return null;
|
|
}
|
|
|
|
$isHeaders = $this->hasHeaders && empty($this->headers);
|
|
|
|
if ($isHeaders) {
|
|
$this->headers = $csv;
|
|
|
|
return $csv;
|
|
}
|
|
|
|
if (!$isHeaders && $this->hasHeaders && !empty($this->headers)) {
|
|
foreach ($this->headers as $key => $header) {
|
|
$csv[$header] = isset($csv[$key]) ? $csv[$key] : null;
|
|
}
|
|
}
|
|
|
|
$this->datas[] = $csv;
|
|
|
|
return $csv;
|
|
}
|
|
}
|