YamlFile.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace RocketTheme\Toolbox\File;
  3. use Symfony\Component\Yaml\Exception\DumpException;
  4. use Symfony\Component\Yaml\Exception\ParseException;
  5. use \Symfony\Component\Yaml\Yaml as YamlParser;
  6. /**
  7. * Implements YAML File reader.
  8. *
  9. * @package RocketTheme\Toolbox\File
  10. * @author RocketTheme
  11. * @license MIT
  12. */
  13. class YamlFile extends File
  14. {
  15. /**
  16. * @var array|File[]
  17. */
  18. static protected $instances = array();
  19. /**
  20. * Constructor.
  21. */
  22. protected function __construct()
  23. {
  24. parent::__construct();
  25. $this->extension = '.yaml';
  26. }
  27. /**
  28. * Check contents and make sure it is in correct format.
  29. *
  30. * @param array $var
  31. * @return array
  32. */
  33. protected function check($var)
  34. {
  35. return (array) $var;
  36. }
  37. /**
  38. * Encode contents into RAW string.
  39. *
  40. * @param string $var
  41. * @return string
  42. * @throws DumpException
  43. */
  44. protected function encode($var)
  45. {
  46. return (string) YamlParser::dump($var, $this->setting('inline', 5), $this->setting('indent', 2), true, false);
  47. }
  48. /**
  49. * Decode RAW string into contents.
  50. *
  51. * @param string $var
  52. * @return array mixed
  53. * @throws ParseException
  54. */
  55. protected function decode($var)
  56. {
  57. $data = false;
  58. // Try native PECL YAML PHP extension first if available.
  59. if ($this->setting('native') && function_exists('yaml_parse')) {
  60. if ($this->setting('compat', true)) {
  61. // Fix illegal @ start character.
  62. $data = preg_replace('/ (@[\w\.\-]*)/', " '\${1}'", $var);
  63. } else {
  64. $data = $var;
  65. }
  66. // Safely decode YAML.
  67. $saved = @ini_get('yaml.decode_php');
  68. @ini_set('yaml.decode_php', 0);
  69. $data = @yaml_parse($data);
  70. @ini_set('yaml.decode_php', $saved);
  71. }
  72. return $data !== false ? $data : (array) YamlParser::parse($var);
  73. }
  74. }