Sen descrición

CsvFileLoader.php 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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\NotFoundResourceException;
  12. /**
  13. * CsvFileLoader loads translations from CSV files.
  14. *
  15. * @author Saša Stamenković <umpirsky@gmail.com>
  16. */
  17. class CsvFileLoader extends FileLoader
  18. {
  19. private $delimiter = ';';
  20. private $enclosure = '"';
  21. private $escape = '\\';
  22. /**
  23. * {@inheritdoc}
  24. */
  25. protected function loadResource($resource)
  26. {
  27. $messages = [];
  28. try {
  29. $file = new \SplFileObject($resource, 'rb');
  30. } catch (\RuntimeException $e) {
  31. throw new NotFoundResourceException(sprintf('Error opening file "%s".', $resource), 0, $e);
  32. }
  33. $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
  34. $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
  35. foreach ($file as $data) {
  36. if (false === $data) {
  37. continue;
  38. }
  39. if ('#' !== substr($data[0], 0, 1) && isset($data[1]) && 2 === \count($data)) {
  40. $messages[$data[0]] = $data[1];
  41. }
  42. }
  43. return $messages;
  44. }
  45. /**
  46. * Sets the delimiter, enclosure, and escape character for CSV.
  47. *
  48. * @param string $delimiter Delimiter character
  49. * @param string $enclosure Enclosure character
  50. * @param string $escape Escape character
  51. */
  52. public function setCsvControl($delimiter = ';', $enclosure = '"', $escape = '\\')
  53. {
  54. $this->delimiter = $delimiter;
  55. $this->enclosure = $enclosure;
  56. $this->escape = $escape;
  57. }
  58. }