sfYaml.class.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * sfYaml class.
  11. *
  12. * @package symfony
  13. * @subpackage util
  14. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  15. * @version SVN: $Id: sfYaml.class.php 8988 2008-05-15 20:24:26Z fabien $
  16. */
  17. class sfYaml
  18. {
  19. /**
  20. * Load YAML into a PHP array statically
  21. *
  22. * The load method, when supplied with a YAML stream (string or file),
  23. * will do its best to convert YAML in a file into a PHP array.
  24. *
  25. * Usage:
  26. * <code>
  27. * $array = sfYAML::Load('config.yml');
  28. * print_r($array);
  29. * </code>
  30. *
  31. * @param string $input Path of YAML file or string containing YAML
  32. *
  33. * @return array
  34. */
  35. public static function load($input)
  36. {
  37. $file = '';
  38. // if input is a file, process it
  39. if (strpos($input, "\n") === false && is_file($input))
  40. {
  41. $file = $input;
  42. ob_start();
  43. $retval = include($input);
  44. $content = ob_get_clean();
  45. // if an array is returned by the config file assume it's in plain php form else in yaml
  46. $input = is_array($retval) ? $retval : $content;
  47. }
  48. // if an array is returned by the config file assume it's in plain php form else in yaml
  49. if (is_array($input))
  50. {
  51. return $input;
  52. }
  53. require_once dirname(__FILE__).'/sfYamlParser.class.php';
  54. $yaml = new sfYamlParser();
  55. try
  56. {
  57. $ret = $yaml->parse($input);
  58. }
  59. catch (Exception $e)
  60. {
  61. throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage()));
  62. }
  63. return $ret;
  64. }
  65. /**
  66. * Dump YAML from PHP array statically
  67. *
  68. * The dump method, when supplied with an array, will do its best
  69. * to convert the array into friendly YAML.
  70. *
  71. * @param array $array PHP array
  72. *
  73. * @return string
  74. */
  75. public static function dump($array, $inline = 2)
  76. {
  77. require_once dirname(__FILE__).'/sfYamlDumper.class.php';
  78. $yaml = new sfYamlDumper();
  79. return $yaml->dump($array, $inline);
  80. }
  81. }
  82. /**
  83. * Wraps echo to automatically provide a newline.
  84. *
  85. * @param string The string to echo with new line
  86. */
  87. function echoln($string)
  88. {
  89. echo $string."\n";
  90. }