]>
Commit | Line | Data |
---|---|---|
4f5b44bd NL |
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\Translation\Exception\InvalidResourceException; | |
15 | use Symfony\Component\Translation\Exception\NotFoundResourceException; | |
16 | use Symfony\Component\Config\Resource\FileResource; | |
17 | ||
18 | /** | |
19 | * CsvFileLoader loads translations from CSV files. | |
20 | * | |
21 | * @author Saša Stamenković <umpirsky@gmail.com> | |
22 | * | |
23 | * @api | |
24 | */ | |
25 | class CsvFileLoader extends ArrayLoader implements LoaderInterface | |
26 | { | |
27 | private $delimiter = ';'; | |
28 | private $enclosure = '"'; | |
29 | private $escape = '\\'; | |
30 | ||
31 | /** | |
32 | * {@inheritdoc} | |
33 | * | |
34 | * @api | |
35 | */ | |
36 | public function load($resource, $locale, $domain = 'messages') | |
37 | { | |
38 | if (!stream_is_local($resource)) { | |
39 | throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); | |
40 | } | |
41 | ||
42 | if (!file_exists($resource)) { | |
43 | throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); | |
44 | } | |
45 | ||
46 | $messages = array(); | |
47 | ||
48 | try { | |
49 | $file = new \SplFileObject($resource, 'rb'); | |
50 | } catch (\RuntimeException $e) { | |
51 | throw new NotFoundResourceException(sprintf('Error opening file "%s".', $resource), 0, $e); | |
52 | } | |
53 | ||
54 | $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY); | |
55 | $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape); | |
56 | ||
57 | foreach ($file as $data) { | |
58 | if (substr($data[0], 0, 1) === '#') { | |
59 | continue; | |
60 | } | |
61 | ||
62 | if (!isset($data[1])) { | |
63 | continue; | |
64 | } | |
65 | ||
66 | if (count($data) == 2) { | |
67 | $messages[$data[0]] = $data[1]; | |
68 | } else { | |
69 | continue; | |
70 | } | |
71 | } | |
72 | ||
73 | $catalogue = parent::load($messages, $locale, $domain); | |
74 | $catalogue->addResource(new FileResource($resource)); | |
75 | ||
76 | return $catalogue; | |
77 | } | |
78 | ||
79 | /** | |
80 | * Sets the delimiter, enclosure, and escape character for CSV. | |
81 | * | |
82 | * @param string $delimiter delimiter character | |
83 | * @param string $enclosure enclosure character | |
84 | * @param string $escape escape character | |
85 | */ | |
86 | public function setCsvControl($delimiter = ';', $enclosure = '"', $escape = '\\') | |
87 | { | |
88 | $this->delimiter = $delimiter; | |
89 | $this->enclosure = $enclosure; | |
90 | $this->escape = $escape; | |
91 | } | |
92 | } |