src/Extractors/File/FileExtractorAbstract.php

Summary

Maintainability
A
0 mins
Test Coverage
<?php

/*
 * This file is part of YaEtl
 *     (c) Fabrice de Stefanis / https://github.com/fab2s/YaEtl
 * This source file is licensed under the MIT license which you will
 * find in the LICENSE file or at https://opensource.org/licenses/MIT
 */

namespace fab2s\YaEtl\Extractors\File;

use fab2s\Bom\Bom;
use fab2s\NodalFlow\NodalFlowException;
use fab2s\YaEtl\Extractors\ExtractorAbstract;
use fab2s\YaEtl\Traits\FileHandlerTrait;
use fab2s\YaEtl\YaEtlException;

/**
 * Class FileExtractorAbstract
 */
abstract class FileExtractorAbstract extends ExtractorAbstract
{
    use FileHandlerTrait;

    /**
     * @param resource|string $input
     *
     * @throws YaEtlException
     * @throws NodalFlowException
     */
    public function __construct($input)
    {
        $this->initHandle($input, 'rb');

        parent::__construct();
    }

    /**
     * @param mixed $param
     *
     * @return bool
     */
    public function extract($param = null): bool
    {
        return !feof($this->handle);
    }

    /**
     * @return bool
     */
    protected function readBom(): bool
    {
        if (false === ($bomCandidate = fread($this->handle, 4))) {
            return false;
        }

        /* @var string $bomCandidate */
        if ($bom = Bom::extract($bomCandidate)) {
            $this->encoding = Bom::getBomEncoding($bom);

            return !fseek($this->handle, strlen($bom));
        }

        return rewind($this->handle);
    }

    /**
     * @return string|null
     */
    protected function getNextNonEmptyLine(): ?string
    {
        do {
            if (false === ($line = fgets($this->handle))) {
                return null;
            }

            if ('' === ($line = trim($line))) {
                continue;
            }

            return $line;
        } while (!feof($this->handle));

        return null;
    }

    /**
     * @return string|null
     */
    protected function getNextNonEmptyChars(): ? string
    {
        do {
            if (false === ($char = fread($this->handle, 1))) {
                return null;
            }

            if ('' === ($char = trim($char))) {
                continue;
            }

            return $char;
        } while (!feof($this->handle));

        return null;
    }
}