CsvFileLoader.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 string $delimiter = ';';
  20. private string $enclosure = '"';
  21. private string $escape = '\\';
  22. protected function loadResource(string $resource): array
  23. {
  24. $messages = [];
  25. try {
  26. $file = new \SplFileObject($resource, 'rb');
  27. } catch (\RuntimeException $e) {
  28. throw new NotFoundResourceException(sprintf('Error opening file "%s".', $resource), 0, $e);
  29. }
  30. $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
  31. $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
  32. foreach ($file as $data) {
  33. if (false === $data) {
  34. continue;
  35. }
  36. if (!str_starts_with($data[0], '#') && isset($data[1]) && 2 === \count($data)) {
  37. $messages[$data[0]] = $data[1];
  38. }
  39. }
  40. return $messages;
  41. }
  42. /**
  43. * Sets the delimiter, enclosure, and escape character for CSV.
  44. *
  45. * @return void
  46. */
  47. public function setCsvControl(string $delimiter = ';', string $enclosure = '"', string $escape = '\\')
  48. {
  49. $this->delimiter = $delimiter;
  50. $this->enclosure = $enclosure;
  51. $this->escape = $escape;
  52. }
  53. }