JsonBundleReader.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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\Intl\Data\Bundle\Reader;
  11. use Symfony\Component\Intl\Exception\ResourceBundleNotFoundException;
  12. use Symfony\Component\Intl\Exception\RuntimeException;
  13. /**
  14. * Reads .json resource bundles.
  15. *
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. *
  18. * @internal
  19. */
  20. class JsonBundleReader implements BundleReaderInterface
  21. {
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function read(string $path, string $locale)
  26. {
  27. $fileName = $path.'/'.$locale.'.json';
  28. // prevent directory traversal attacks
  29. if (\dirname($fileName) !== $path) {
  30. throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName));
  31. }
  32. if (!file_exists($fileName)) {
  33. throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName));
  34. }
  35. if (!is_file($fileName)) {
  36. throw new RuntimeException(sprintf('The resource bundle "%s" is not a file.', $fileName));
  37. }
  38. $data = json_decode(file_get_contents($fileName), true);
  39. if (null === $data) {
  40. throw new RuntimeException(sprintf('The resource bundle "%s" contains invalid JSON: ', $fileName).json_last_error_msg());
  41. }
  42. return $data;
  43. }
  44. }