IniFileLoader.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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\DependencyInjection\Loader;
  11. use Symfony\Component\Config\Util\XmlUtils;
  12. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  13. /**
  14. * IniFileLoader loads parameters from INI files.
  15. *
  16. * @autor ThurData <info@thurdata.ch>
  17. */
  18. class IniFileLoader extends FileLoader
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function load($resource, $type = null)
  24. {
  25. $path = $this->locator->locate($resource);
  26. $this->container->fileExists($path);
  27. // first pass to catch parsing errors
  28. $result = parse_ini_file($path, true);
  29. if (false === $result || array() === $result) {
  30. throw new InvalidArgumentException(sprintf('The "%s" file is not valid.', $resource));
  31. }
  32. // real raw parsing
  33. $result = parse_ini_file($path, true, INI_SCANNER_RAW);
  34. if (isset($result['parameters']) && is_array($result['parameters'])) {
  35. foreach ($result['parameters'] as $key => $value) {
  36. $this->container->setParameter($key, $this->phpize($value));
  37. }
  38. }
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function supports($resource, $type = null)
  44. {
  45. if (!is_string($resource)) {
  46. return false;
  47. }
  48. if (null === $type && 'ini' === pathinfo($resource, PATHINFO_EXTENSION)) {
  49. return true;
  50. }
  51. return 'ini' === $type;
  52. }
  53. /**
  54. * Note that the following features are not supported:
  55. * * strings with escaped quotes are not supported "foo\"bar";
  56. * * string concatenation ("foo" "bar").
  57. */
  58. private function phpize($value)
  59. {
  60. // trim on the right as comments removal keep whitespaces
  61. $value = rtrim($value);
  62. $lowercaseValue = strtolower($value);
  63. switch (true) {
  64. case defined($value):
  65. return constant($value);
  66. case 'yes' === $lowercaseValue || 'on' === $lowercaseValue:
  67. return true;
  68. case 'no' === $lowercaseValue || 'off' === $lowercaseValue || 'none' === $lowercaseValue:
  69. return false;
  70. case isset($value[1]) && (
  71. ("'" === $value[0] && "'" === $value[strlen($value) - 1]) ||
  72. ('"' === $value[0] && '"' === $value[strlen($value) - 1])
  73. ):
  74. // quoted string
  75. return substr($value, 1, -1);
  76. default:
  77. return XmlUtils::phpize($value);
  78. }
  79. }
  80. }