|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the League.csv library |
|
4
|
|
|
* |
|
5
|
|
|
* @license http://opensource.org/licenses/MIT |
|
6
|
|
|
* @link https://github.com/thephpleague/csv/ |
|
7
|
|
|
* @version 9.0.0 |
|
8
|
|
|
* @package League.csv |
|
9
|
|
|
* |
|
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
11
|
|
|
* file that was distributed with this source code. |
|
12
|
|
|
*/ |
|
13
|
|
|
declare(strict_types=1); |
|
14
|
|
|
|
|
15
|
|
|
namespace League\Csv; |
|
16
|
|
|
|
|
17
|
|
|
use Iterator; |
|
18
|
|
|
use League\Csv\Exception\InvalidArgumentException; |
|
19
|
|
|
use Traversable; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* A trait to ease records conversion |
|
23
|
|
|
* |
|
24
|
|
|
* @package League.csv |
|
25
|
|
|
* @since 9.0.0 |
|
26
|
|
|
* @author Ignace Nyamagana Butera <[email protected]> |
|
27
|
|
|
*/ |
|
28
|
|
|
trait ConverterTrait |
|
29
|
|
|
{ |
|
30
|
|
|
use ValidatorTrait; |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Charset Encoding for the CSV |
|
34
|
|
|
* |
|
35
|
|
|
* This information is used when converting the CSV to XML or JSON |
|
36
|
|
|
* |
|
37
|
|
|
* @var string |
|
38
|
|
|
*/ |
|
39
|
|
|
protected $input_encoding = 'UTF-8'; |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Sets the CSV encoding charset |
|
43
|
|
|
* |
|
44
|
|
|
* @param string $input_encoding |
|
45
|
|
|
* |
|
46
|
|
|
* @throws InvalidArgumentException if the charset is empty |
|
47
|
|
|
* |
|
48
|
|
|
* @return static |
|
49
|
|
|
*/ |
|
50
|
6 |
|
public function inputEncoding(string $input_encoding): self |
|
51
|
|
|
{ |
|
52
|
6 |
|
$input_encoding = $this->filterElementName($input_encoding, 'input_encoding', __METHOD__); |
|
53
|
4 |
|
$clone = clone $this; |
|
54
|
4 |
|
$clone->input_encoding = strtoupper(str_replace('_', '-', $input_encoding)); |
|
55
|
|
|
|
|
56
|
4 |
|
return $clone; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Convert Csv file into UTF-8 |
|
61
|
|
|
* |
|
62
|
|
|
* @param array|Traversable $records the CSV records collection |
|
63
|
|
|
* |
|
64
|
|
|
* @return array|Iterator |
|
65
|
|
|
*/ |
|
66
|
8 |
|
protected function convertToUtf8($records) |
|
67
|
|
|
{ |
|
68
|
8 |
|
if (stripos($this->input_encoding, 'UTF-8') !== false) { |
|
69
|
4 |
|
return $records; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
$walker = function (&$value, &$offset) { |
|
73
|
4 |
|
$value = mb_convert_encoding((string) $value, 'UTF-8', $this->input_encoding); |
|
74
|
4 |
|
$offset = mb_convert_encoding((string) $offset, 'UTF-8', $this->input_encoding); |
|
75
|
4 |
|
}; |
|
76
|
|
|
|
|
77
|
4 |
|
$convert = function (array $record) use ($walker): array { |
|
78
|
4 |
|
array_walk($record, $walker); |
|
79
|
4 |
|
return $record; |
|
80
|
4 |
|
}; |
|
81
|
|
|
|
|
82
|
4 |
|
return is_array($records) ? array_map($convert, $records) : new MapIterator($records, $convert); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|