Passed
Pull Request — master (#183)
by Luke
03:12
created

SniffLineTerminatorByCount::sniff()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 20
ccs 15
cts 15
cp 1
crap 3
rs 9.6
c 0
b 0
f 0
1
<?php
2
/**
3
 * CSVelte: Slender, elegant CSV for PHP
4
 *
5
 * Inspired by Python's CSV module and Frictionless Data and the W3C's CSV
6
 * standardization efforts, CSVelte was written in an effort to take all the
7
 * suck out of working with CSV.
8
 *
9
 * @copyright Copyright (c) 2018 Luke Visinoni
10
 * @author    Luke Visinoni <[email protected]>
11
 * @license   See LICENSE file (MIT license)
12
 */
13
namespace CSVelte\Sniffer;
14
15
class SniffLineTerminatorByCount extends AbstractSniffer
16
{
17
    /**
18
     * End-of-line constants
19
     */
20
    const EOL_WINDOWS = 0;
21
    const EOL_UNIX    = 1;
22
    const EOL_OTHER   = 2;
23
24
    /**
25
     * Guess line terminator in a string of data
26
     *
27
     * Using the number of times it occurs, guess which line terminator is most likely.
28
     *
29
     * @param string $data The data to analyze
30
     *
31
     * @return string
32
     */
33 1
    public function sniff($data)
34
    {
35
        // in this case we really only care about newlines so we pass in a comma as the delim
36 1
        $str = $this->replaceQuotedSpecialChars($data, ',');
37
        $eols = [
38 1
            static::EOL_WINDOWS => "\r\n",  // 0x0D - 0x0A - Windows, DOS OS/2
39 1
            static::EOL_UNIX    => "\n",    // 0x0A -      - Unix, OSX
40 1
            static::EOL_OTHER   => "\r",    // 0x0D -      - Other
41 1
        ];
42
43 1
        $curCount = 0;
44 1
        $curEol = PHP_EOL;
45 1
        foreach ($eols as $k => $eol) {
46 1
            if (($count = substr_count($str, $eol)) > $curCount) {
47 1
                $curCount = $count;
48 1
                $curEol   = $eol;
49 1
            }
50 1
        }
51 1
        return $curEol;
52
    }
53
}