JsonBundleReader.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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($path, $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(
  34. 'The resource bundle "%s/%s.json" does not exist.',
  35. $path,
  36. $locale
  37. ));
  38. }
  39. if (!is_file($fileName)) {
  40. throw new RuntimeException(sprintf(
  41. 'The resource bundle "%s/%s.json" is not a file.',
  42. $path,
  43. $locale
  44. ));
  45. }
  46. $data = json_decode(file_get_contents($fileName), true);
  47. if (null === $data) {
  48. throw new RuntimeException(sprintf(
  49. 'The resource bundle "%s/%s.json" contains invalid JSON: %s',
  50. $path,
  51. $locale,
  52. json_last_error_msg()
  53. ));
  54. }
  55. return $data;
  56. }
  57. }