CsvFileLoader.php 2.5 KB

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