CsvFileLoader.php 1.6 KB

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