|
1 <?php |
|
2 |
|
3 /* |
|
4 * This file is part of the Symfony package. |
|
5 * |
|
6 * (c) Fabien Potencier <fabien@symfony.com> |
|
7 * |
|
8 * For the full copyright and license information, please view the LICENSE |
|
9 * file that was distributed with this source code. |
|
10 */ |
|
11 |
|
12 namespace Symfony\Component\Translation\Loader; |
|
13 |
|
14 use Symfony\Component\Config\Resource\FileResource; |
|
15 |
|
16 /** |
|
17 * CsvFileLoader loads translations from CSV files. |
|
18 * |
|
19 * @author Saša Stamenković <umpirsky@gmail.com> |
|
20 * |
|
21 * @api |
|
22 */ |
|
23 class CsvFileLoader extends ArrayLoader implements LoaderInterface |
|
24 { |
|
25 private $delimiter = ';'; |
|
26 private $enclosure = '"'; |
|
27 private $escape = '\\'; |
|
28 |
|
29 /** |
|
30 * {@inheritdoc} |
|
31 * |
|
32 * @api |
|
33 */ |
|
34 public function load($resource, $locale, $domain = 'messages') |
|
35 { |
|
36 $messages = array(); |
|
37 |
|
38 try { |
|
39 $file = new \SplFileObject($resource, 'rb'); |
|
40 } catch(\RuntimeException $e) { |
|
41 throw new \InvalidArgumentException(sprintf('Error opening file "%s".', $resource)); |
|
42 } |
|
43 |
|
44 $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY); |
|
45 $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape); |
|
46 |
|
47 foreach($file as $data) { |
|
48 if (substr($data[0], 0, 1) === '#') { |
|
49 continue; |
|
50 } |
|
51 |
|
52 if (!isset($data[1])) { |
|
53 continue; |
|
54 } |
|
55 |
|
56 if (count($data) == 2) { |
|
57 $messages[$data[0]] = $data[1]; |
|
58 } else { |
|
59 continue; |
|
60 } |
|
61 } |
|
62 |
|
63 $catalogue = parent::load($messages, $locale, $domain); |
|
64 $catalogue->addResource(new FileResource($resource)); |
|
65 |
|
66 return $catalogue; |
|
67 } |
|
68 |
|
69 /** |
|
70 * Sets the delimiter, enclosure, and escape character for CSV. |
|
71 * |
|
72 * @param string $delimiter delimiter character |
|
73 * @param string $enclosure enclosure character |
|
74 * @param string $escape escape character |
|
75 */ |
|
76 public function setCsvControl($delimiter = ';', $enclosure = '"', $escape = '\\') |
|
77 { |
|
78 $this->delimiter = $delimiter; |
|
79 $this->enclosure = $enclosure; |
|
80 $this->escape = $escape; |
|
81 } |
|
82 } |