Testable PHP CSV Streamreader Class inklusive Shunks


class CsvReader implements ReaderInterface
{

    /**
     * shunk size for file import
     */
    private $shunkSize;

    /**
     * @param int $shunkSize
     */
    public function __construct(int $shunkSize)
    {
        $this->shunkSize = $shunkSize;
    }

    /**
     * @param string $file
     * @param callable $callback
     *
     * @return array
     * @throws StorageException
     */
    public function shunkCsvFile(string $file, callable $callback): array
    {
        $file = $this->getFileObject($file);
        $file->setFlags(
            SplFileObject::READ_CSV |
            SplFileObject::SKIP_EMPTY |
            SplFileObject::READ_AHEAD
        );

        $row = 0;
        $data = [];
        if ($file->isFile()) {
            while (!$file->eof()) {
                $line = $file->fgetcsv(';');
                $row++;
                if ($row === 1) {
                    //skip header
                    continue;
                }

                $data[] = $line;

                if (($row % $this->shunkSize) == 0) {
                    $callback($data);
                    $data = [];
                }
            }
        }

        $callback($data);
            
    }

    /**
     * @param string $file
     *
     * @return SplFileObject
     *
     * @codeCoverageIgnore
     */
    protected function getFileObject(string $file): SplFileObject
    {
        return new SplFileObject($file);
    }

Hinterlasse eine Antwort

Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>