CsvFileLoader.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. /**
  22. * @deprecated since Symfony 7.2, to be removed in 8.0
  23. */
  24. private string $escape = '';
  25. protected function loadResource(string $resource): array
  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 (!str_starts_with($data[0], '#') && 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. public function setCsvControl(string $delimiter = ';', string $enclosure = '"', string $escape = ''): void
  49. {
  50. $this->delimiter = $delimiter;
  51. $this->enclosure = $enclosure;
  52. if ('' !== $escape) {
  53. trigger_deprecation('symfony/translation', '7.2', 'The "escape" parameter of the "%s" method is deprecated. It will be removed in 8.0.', __METHOD__);
  54. }
  55. $this->escape = $escape;
  56. }
  57. }