CsvFileLoader.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. if (!$file = @fopen($resource, 'r')) {
  29. throw new NotFoundResourceException(\sprintf('Error opening file "%s".', $resource));
  30. }
  31. try {
  32. while (false !== $data = fgetcsv($file, null, $this->delimiter, $this->enclosure, $this->escape)) {
  33. // empty lines are read as [null]
  34. if (isset($data[1]) && 2 === \count($data) && !str_starts_with($data[0], '#')) {
  35. $messages[$data[0]] = $data[1];
  36. }
  37. }
  38. } finally {
  39. fclose($file);
  40. }
  41. return $messages;
  42. }
  43. /**
  44. * Sets the delimiter, enclosure, and escape character for CSV.
  45. */
  46. public function setCsvControl(string $delimiter = ';', string $enclosure = '"', string $escape = ''): void
  47. {
  48. $this->delimiter = $delimiter;
  49. $this->enclosure = $enclosure;
  50. if ('' !== $escape) {
  51. trigger_deprecation('symfony/translation', '7.2', 'The "escape" parameter of the "%s" method is deprecated. It will be removed in 8.0.', __METHOD__);
  52. }
  53. $this->escape = $escape;
  54. }
  55. }