Completed
Pull Request — master (#145)
by
unknown
04:12
created

Csv::getcsv()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Gettext\Extractors;
4
5
use Gettext\Translations;
6
use Gettext\Utils\HeadersExtractorTrait;
7
8
/**
9
 * Class to get gettext strings from csv.
10
 */
11
class Csv extends Extractor implements ExtractorInterface
12
{
13
    use HeadersExtractorTrait;
14
15
    public static $options = [
16
        'delimiter' => ",",
17
        'enclosure' => '"',
18
        'escape_char' => "\\"
19
    ];
20
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public static function fromString($string, Translations $translations, array $options = [])
25
    {
26
        $options += static::$options;
27
        $handle = fopen('php://memory', 'w');
28
29
        fputs($handle, $string);
30
        rewind($handle);
31
32
        while ($row = self::getcsv($handle, $options)) {
33
            $context = array_shift($row);
34
            $original = array_shift($row);
35
36
            if ($context === '' && $original === '') {
37
                self::extractHeaders(array_shift($row), $translations);
38
                continue;
39
            }
40
41
            $translation = $translations->insert($context, $original);
42
43
            if (!empty($row)) {
44
                $translation->setTranslation(array_shift($row));
45
                $translation->setPluralTranslations($row);
46
            }
47
        }
48
49
        fclose($handle);
50
    }
51
52
    /**
53
     * @param resource $handle
54
     * @param array $options
55
     *
56
     * @return array
57
     */
58
    private static function getcsv($handle, $options)
59
    {
60
        if (version_compare(PHP_VERSION, '5.3.0') >= 0) { // >= 5.3
61
            return fgetcsv($handle, null, $options['delimiter'], $options['enclosure'], $options['escape_char']);
62
        }
63
64
        return fgetcsv($handle, null, $options['delimiter'], $options['enclosure']);
65
    }
66
}
67