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
|
|
View Code Duplication |
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
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.