Passed
Push — master ( 52cffa...94ac4c )
by Fabrice
02:27
created

FileExtractorAbstract::readBom()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 4
nop 0
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of YaEtl.
5
 *     (c) Fabrice de Stefanis / https://github.com/fab2s/YaEtl
6
 * This source file is licensed under the MIT license which you will
7
 * find in the LICENSE file or at https://opensource.org/licenses/MIT
8
 */
9
10
namespace fab2s\YaEtl\Extractors\File;
11
12
use fab2s\NodalFlow\NodalFlowException;
13
use fab2s\NodalFlow\YaEtlException;
14
use fab2s\OpinHelpers\Bom;
15
use fab2s\YaEtl\Extractors\ExtractorAbstract;
16
use fab2s\YaEtl\Traits\FileHandlerTrait;
17
18
/**
19
 * Class FileExtractorAbstract
20
 */
21
abstract class FileExtractorAbstract extends ExtractorAbstract
22
{
23
    use FileHandlerTrait;
24
25
    /**
26
     * @param resource|string $input
27
     *
28
     * @throws YaEtlException
29
     * @throws NodalFlowException
30
     */
31
    public function __construct($input)
32
    {
33
        $this->initHandle($input, 'rb');
34
35
        parent::__construct();
36
    }
37
38
    /**
39
     * @param mixed $param
40
     *
41
     * @return bool
42
     */
43
    public function extract($param = null)
44
    {
45
        $this->getCarrier()->getFlowMap()->incrementNode($this->getId(), 'num_extract');
46
47
        return !feof($this->handle);
48
    }
49
50
    /**
51
     * @return bool
52
     */
53
    protected function readBom()
54
    {
55
        if (false === ($buffer = $this->getNextNonEmptyChars())) {
56
            return false;
57
        }
58
59
        /* @var string $buffer */
60
        $firstCharPos = ftell($this->handle);
61
        if (false === ($chars = fread($this->handle, 3))) {
62
            return false;
63
        }
64
65
        /* @var string $chars */
66
        $buffer .= $chars;
67
        if ($bom = Bom::extract($buffer)) {
68
            $this->encoding = Bom::getBomEncoding($bom);
69
70
            return !fseek($this->handle, $firstCharPos + strlen($bom) - 1);
71
        }
72
73
        return !fseek($this->handle, $firstCharPos - 1);
74
    }
75
76
    /**
77
     * @return string|false
78
     */
79
    protected function getNextNonEmptyLine()
80
    {
81
        while (false !== ($line = fgets($this->handle))) {
82
            if ('' === ($line = trim($line))) {
83
                continue;
84
            }
85
86
            return $line;
87
        }
88
89
        return false;
90
    }
91
92
    /**
93
     * @return string|false
94
     */
95
    protected function getNextNonEmptyChars()
96
    {
97
        do {
98
            if (false === ($char = fread($this->handle, 1))) {
99
                return false;
100
            }
101
        } while (trim($char) === '');
102
103
        return $char;
104
    }
105
}
106