Automatically migrated from Gitolite
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1146 lines
34 KiB

7 years ago
  1. <?php
  2. /**
  3. * Spyc -- A Simple PHP YAML Class
  4. * @version 0.5.1
  5. * @author Vlad Andersen <vlad.andersen@gmail.com>
  6. * @author Chris Wanstrath <chris@ozmm.org>
  7. * @link http://code.google.com/p/spyc/
  8. * @copyright Copyright 2005-2006 Chris Wanstrath, 2006-2011 Vlad Andersen
  9. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  10. * @package Spyc
  11. */
  12. if (!function_exists('spyc_load')) {
  13. /**
  14. * Parses YAML to array.
  15. * @param string $string YAML string.
  16. * @return array
  17. */
  18. function spyc_load ($string) {
  19. return Spyc::YAMLLoadString($string);
  20. }
  21. }
  22. if (!function_exists('spyc_load_file')) {
  23. /**
  24. * Parses YAML to array.
  25. * @param string $file Path to YAML file.
  26. * @return array
  27. */
  28. function spyc_load_file ($file) {
  29. return Spyc::YAMLLoad($file);
  30. }
  31. }
  32. if (!function_exists('spyc_dump')) {
  33. /**
  34. * Dumps array to YAML.
  35. * @param array $data Array.
  36. * @return string
  37. */
  38. function spyc_dump ($data) {
  39. return Spyc::YAMLDump($data, false, false, true);
  40. }
  41. }
  42. /**
  43. * The Simple PHP YAML Class.
  44. *
  45. * This class can be used to read a YAML file and convert its contents
  46. * into a PHP array. It currently supports a very limited subsection of
  47. * the YAML spec.
  48. *
  49. * Usage:
  50. * <code>
  51. * $Spyc = new Spyc;
  52. * $array = $Spyc->load($file);
  53. * </code>
  54. * or:
  55. * <code>
  56. * $array = Spyc::YAMLLoad($file);
  57. * </code>
  58. * or:
  59. * <code>
  60. * $array = spyc_load_file($file);
  61. * </code>
  62. * @package Spyc
  63. */
  64. class Spyc {
  65. // SETTINGS
  66. const REMPTY = "\0\0\0\0\0";
  67. /**
  68. * Setting this to true will force YAMLDump to enclose any string value in
  69. * quotes. False by default.
  70. *
  71. * @var bool
  72. */
  73. public $setting_dump_force_quotes = false;
  74. /**
  75. * Setting this to true will forse YAMLLoad to use syck_load function when
  76. * possible. False by default.
  77. * @var bool
  78. */
  79. public $setting_use_syck_is_possible = false;
  80. /**#@+
  81. * @access private
  82. * @var mixed
  83. */
  84. private $_dumpIndent;
  85. private $_dumpWordWrap;
  86. private $_containsGroupAnchor = false;
  87. private $_containsGroupAlias = false;
  88. private $path;
  89. private $result;
  90. private $LiteralPlaceHolder = '___YAML_Literal_Block___';
  91. private $SavedGroups = array();
  92. private $indent;
  93. /**
  94. * Path modifier that should be applied after adding current element.
  95. * @var array
  96. */
  97. private $delayedPath = array();
  98. /**#@+
  99. * @access public
  100. * @var mixed
  101. */
  102. public $_nodeId;
  103. /**
  104. * Load a valid YAML string to Spyc.
  105. * @param string $input
  106. * @return array
  107. */
  108. public function load ($input) {
  109. return $this->__loadString($input);
  110. }
  111. /**
  112. * Load a valid YAML file to Spyc.
  113. * @param string $file
  114. * @return array
  115. */
  116. public function loadFile ($file) {
  117. return $this->__load($file);
  118. }
  119. /**
  120. * Load YAML into a PHP array statically
  121. *
  122. * The load method, when supplied with a YAML stream (string or file),
  123. * will do its best to convert YAML in a file into a PHP array. Pretty
  124. * simple.
  125. * Usage:
  126. * <code>
  127. * $array = Spyc::YAMLLoad('lucky.yaml');
  128. * print_r($array);
  129. * </code>
  130. * @access public
  131. * @return array
  132. * @param string $input Path of YAML file or string containing YAML
  133. */
  134. public static function YAMLLoad($input) {
  135. $Spyc = new Spyc;
  136. return $Spyc->__load($input);
  137. }
  138. /**
  139. * Load a string of YAML into a PHP array statically
  140. *
  141. * The load method, when supplied with a YAML string, will do its best
  142. * to convert YAML in a string into a PHP array. Pretty simple.
  143. *
  144. * Note: use this function if you don't want files from the file system
  145. * loaded and processed as YAML. This is of interest to people concerned
  146. * about security whose input is from a string.
  147. *
  148. * Usage:
  149. * <code>
  150. * $array = Spyc::YAMLLoadString("---\n0: hello world\n");
  151. * print_r($array);
  152. * </code>
  153. * @access public
  154. * @return array
  155. * @param string $input String containing YAML
  156. */
  157. public static function YAMLLoadString($input) {
  158. $Spyc = new Spyc;
  159. return $Spyc->__loadString($input);
  160. }
  161. /**
  162. * Dump YAML from PHP array statically
  163. *
  164. * The dump method, when supplied with an array, will do its best
  165. * to convert the array into friendly YAML. Pretty simple. Feel free to
  166. * save the returned string as nothing.yaml and pass it around.
  167. *
  168. * Oh, and you can decide how big the indent is and what the wordwrap
  169. * for folding is. Pretty cool -- just pass in 'false' for either if
  170. * you want to use the default.
  171. *
  172. * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
  173. * you can turn off wordwrap by passing in 0.
  174. *
  175. * @access public
  176. * @return string
  177. * @param array $array PHP array
  178. * @param int $indent Pass in false to use the default, which is 2
  179. * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
  180. * @param int $no_opening_dashes Do not start YAML file with "---\n"
  181. */
  182. public static function YAMLDump($array, $indent = false, $wordwrap = false, $no_opening_dashes = false) {
  183. $spyc = new Spyc;
  184. return $spyc->dump($array, $indent, $wordwrap, $no_opening_dashes);
  185. }
  186. /**
  187. * Dump PHP array to YAML
  188. *
  189. * The dump method, when supplied with an array, will do its best
  190. * to convert the array into friendly YAML. Pretty simple. Feel free to
  191. * save the returned string as tasteful.yaml and pass it around.
  192. *
  193. * Oh, and you can decide how big the indent is and what the wordwrap
  194. * for folding is. Pretty cool -- just pass in 'false' for either if
  195. * you want to use the default.
  196. *
  197. * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
  198. * you can turn off wordwrap by passing in 0.
  199. *
  200. * @access public
  201. * @return string
  202. * @param array $array PHP array
  203. * @param int $indent Pass in false to use the default, which is 2
  204. * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
  205. */
  206. public function dump($array,$indent = false,$wordwrap = false, $no_opening_dashes = false) {
  207. // Dumps to some very clean YAML. We'll have to add some more features
  208. // and options soon. And better support for folding.
  209. // New features and options.
  210. if ($indent === false or !is_numeric($indent)) {
  211. $this->_dumpIndent = 2;
  212. } else {
  213. $this->_dumpIndent = $indent;
  214. }
  215. if ($wordwrap === false or !is_numeric($wordwrap)) {
  216. $this->_dumpWordWrap = 40;
  217. } else {
  218. $this->_dumpWordWrap = $wordwrap;
  219. }
  220. // New YAML document
  221. $string = "";
  222. if (!$no_opening_dashes) $string = "---\n";
  223. // Start at the base of the array and move through it.
  224. if ($array) {
  225. $array = (array)$array;
  226. $previous_key = -1;
  227. foreach ($array as $key => $value) {
  228. if (!isset($first_key)) $first_key = $key;
  229. $string .= $this->_yamlize($key,$value,0,$previous_key, $first_key, $array);
  230. $previous_key = $key;
  231. }
  232. }
  233. return $string;
  234. }
  235. /**
  236. * Attempts to convert a key / value array item to YAML
  237. * @access private
  238. * @return string
  239. * @param $key The name of the key
  240. * @param $value The value of the item
  241. * @param $indent The indent of the current node
  242. */
  243. private function _yamlize($key,$value,$indent, $previous_key = -1, $first_key = 0, $source_array = null) {
  244. if (is_array($value)) {
  245. if (empty ($value))
  246. return $this->_dumpNode($key, array(), $indent, $previous_key, $first_key, $source_array);
  247. // It has children. What to do?
  248. // Make it the right kind of item
  249. $string = $this->_dumpNode($key, self::REMPTY, $indent, $previous_key, $first_key, $source_array);
  250. // Add the indent
  251. $indent += $this->_dumpIndent;
  252. // Yamlize the array
  253. $string .= $this->_yamlizeArray($value,$indent);
  254. } elseif (!is_array($value)) {
  255. // It doesn't have children. Yip.
  256. $string = $this->_dumpNode($key, $value, $indent, $previous_key, $first_key, $source_array);
  257. }
  258. return $string;
  259. }
  260. /**
  261. * Attempts to convert an array to YAML
  262. * @access private
  263. * @return string
  264. * @param $array The array you want to convert
  265. * @param $indent The indent of the current level
  266. */
  267. private function _yamlizeArray($array,$indent) {
  268. if (is_array($array)) {
  269. $string = '';
  270. $previous_key = -1;
  271. foreach ($array as $key => $value) {
  272. if (!isset($first_key)) $first_key = $key;
  273. $string .= $this->_yamlize($key, $value, $indent, $previous_key, $first_key, $array);
  274. $previous_key = $key;
  275. }
  276. return $string;
  277. } else {
  278. return false;
  279. }
  280. }
  281. /**
  282. * Returns YAML from a key and a value
  283. * @access private
  284. * @return string
  285. * @param $key The name of the key
  286. * @param $value The value of the item
  287. * @param $indent The indent of the current node
  288. */
  289. private function _dumpNode($key, $value, $indent, $previous_key = -1, $first_key = 0, $source_array = null) {
  290. // do some folding here, for blocks
  291. if (is_string ($value) && ((strpos($value,"\n") !== false || strpos($value,": ") !== false || strpos($value,"- ") !== false ||
  292. strpos($value,"*") !== false || strpos($value,"#") !== false || strpos($value,"<") !== false || strpos($value,">") !== false || strpos ($value, ' ') !== false ||
  293. strpos($value,"[") !== false || strpos($value,"]") !== false || strpos($value,"{") !== false || strpos($value,"}") !== false) || strpos($value,"&") !== false || strpos($value, "'") !== false || strpos($value, "!") === 0 ||
  294. substr ($value, -1, 1) == ':')
  295. ) {
  296. $value = $this->_doLiteralBlock($value,$indent);
  297. } else {
  298. $value = $this->_doFolding($value,$indent);
  299. }
  300. if ($value === array()) $value = '[ ]';
  301. if ($value === "") $value = '""';
  302. if (self::isTranslationWord($value)) {
  303. $value = $this->_doLiteralBlock($value, $indent);
  304. }
  305. if (trim ($value) != $value)
  306. $value = $this->_doLiteralBlock($value,$indent);
  307. if (is_bool($value)) {
  308. $value = $value ? "true" : "false";
  309. }
  310. if ($value === null) $value = 'null';
  311. if ($value === "'" . self::REMPTY . "'") $value = null;
  312. $spaces = str_repeat(' ',$indent);
  313. //if (is_int($key) && $key - 1 == $previous_key && $first_key===0) {
  314. if (is_array ($source_array) && array_keys($source_array) === range(0, count($source_array) - 1)) {
  315. // It's a sequence
  316. $string = $spaces.'- '.$value."\n";
  317. } else {
  318. // if ($first_key===0) throw new Exception('Keys are all screwy. The first one was zero, now it\'s "'. $key .'"');
  319. // It's mapped
  320. if (strpos($key, ":") !== false || strpos($key, "#") !== false) { $key = '"' . $key . '"'; }
  321. $string = rtrim ($spaces.$key.': '.$value)."\n";
  322. }
  323. return $string;
  324. }
  325. /**
  326. * Creates a literal block for dumping
  327. * @access private
  328. * @return string
  329. * @param $value
  330. * @param $indent int The value of the indent
  331. */
  332. private function _doLiteralBlock($value,$indent) {
  333. if ($value === "\n") return '\n';
  334. if (strpos($value, "\n") === false && strpos($value, "'") === false) {
  335. return sprintf ("'%s'", $value);
  336. }
  337. if (strpos($value, "\n") === false && strpos($value, '"') === false) {
  338. return sprintf ('"%s"', $value);
  339. }
  340. $exploded = explode("\n",$value);
  341. $newValue = '|';
  342. $indent += $this->_dumpIndent;
  343. $spaces = str_repeat(' ',$indent);
  344. foreach ($exploded as $line) {
  345. $newValue .= "\n" . $spaces . ($line);
  346. }
  347. return $newValue;
  348. }
  349. /**
  350. * Folds a string of text, if necessary
  351. * @access private
  352. * @return string
  353. * @param $value The string you wish to fold
  354. */
  355. private function _doFolding($value,$indent) {
  356. // Don't do anything if wordwrap is set to 0
  357. if ($this->_dumpWordWrap !== 0 && is_string ($value) && strlen($value) > $this->_dumpWordWrap) {
  358. $indent += $this->_dumpIndent;
  359. $indent = str_repeat(' ',$indent);
  360. $wrapped = wordwrap($value,$this->_dumpWordWrap,"\n$indent");
  361. $value = ">\n".$indent.$wrapped;
  362. } else {
  363. if ($this->setting_dump_force_quotes && is_string ($value) && $value !== self::REMPTY)
  364. $value = '"' . $value . '"';
  365. if (is_numeric($value) && is_string($value))
  366. $value = '"' . $value . '"';
  367. }
  368. return $value;
  369. }
  370. private function isTrueWord($value) {
  371. $words = self::getTranslations(array('true', 'on', 'yes', 'y'));
  372. return in_array($value, $words, true);
  373. }
  374. private function isFalseWord($value) {
  375. $words = self::getTranslations(array('false', 'off', 'no', 'n'));
  376. return in_array($value, $words, true);
  377. }
  378. private function isNullWord($value) {
  379. $words = self::getTranslations(array('null', '~'));
  380. return in_array($value, $words, true);
  381. }
  382. private function isTranslationWord($value) {
  383. return (
  384. self::isTrueWord($value) ||
  385. self::isFalseWord($value) ||
  386. self::isNullWord($value)
  387. );
  388. }
  389. /**
  390. * Coerce a string into a native type
  391. * Reference: http://yaml.org/type/bool.html
  392. * TODO: Use only words from the YAML spec.
  393. * @access private
  394. * @param $value The value to coerce
  395. */
  396. private function coerceValue(&$value) {
  397. if (self::isTrueWord($value)) {
  398. $value = true;
  399. } else if (self::isFalseWord($value)) {
  400. $value = false;
  401. } else if (self::isNullWord($value)) {
  402. $value = null;
  403. }
  404. }
  405. /**
  406. * Given a set of words, perform the appropriate translations on them to
  407. * match the YAML 1.1 specification for type coercing.
  408. * @param $words The words to translate
  409. * @access private
  410. */
  411. private static function getTranslations(array $words) {
  412. $result = array();
  413. foreach ($words as $i) {
  414. $result = array_merge($result, array(ucfirst($i), strtoupper($i), strtolower($i)));
  415. }
  416. return $result;
  417. }
  418. // LOADING FUNCTIONS
  419. private function __load($input) {
  420. $Source = $this->loadFromSource($input);
  421. return $this->loadWithSource($Source);
  422. }
  423. private function __loadString($input) {
  424. $Source = $this->loadFromString($input);
  425. return $this->loadWithSource($Source);
  426. }
  427. private function loadWithSource($Source) {
  428. if (empty ($Source)) return array();
  429. if ($this->setting_use_syck_is_possible && function_exists ('syck_load')) {
  430. $array = syck_load (implode ("\n", $Source));
  431. return is_array($array) ? $array : array();
  432. }
  433. $this->path = array();
  434. $this->result = array();
  435. $cnt = count($Source);
  436. for ($i = 0; $i < $cnt; $i++) {
  437. $line = $Source[$i];
  438. $this->indent = strlen($line) - strlen(ltrim($line));
  439. $tempPath = $this->getParentPathByIndent($this->indent);
  440. $line = self::stripIndent($line, $this->indent);
  441. if (self::isComment($line)) continue;
  442. if (self::isEmpty($line)) continue;
  443. $this->path = $tempPath;
  444. $literalBlockStyle = self::startsLiteralBlock($line);
  445. if ($literalBlockStyle) {
  446. $line = rtrim ($line, $literalBlockStyle . " \n");
  447. $literalBlock = '';
  448. $line .= ' '.$this->LiteralPlaceHolder;
  449. $literal_block_indent = strlen($Source[$i+1]) - strlen(ltrim($Source[$i+1]));
  450. while (++$i < $cnt && $this->literalBlockContinues($Source[$i], $this->indent)) {
  451. $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle, $literal_block_indent);
  452. }
  453. $i--;
  454. }
  455. // Strip out comments
  456. if (strpos ($line, '#')) {
  457. $line = preg_replace('/\s*#([^"\']+)$/','',$line);
  458. }
  459. while (++$i < $cnt && self::greedilyNeedNextLine($line)) {
  460. $line = rtrim ($line, " \n\t\r") . ' ' . ltrim ($Source[$i], " \t");
  461. }
  462. $i--;
  463. $lineArray = $this->_parseLine($line);
  464. if ($literalBlockStyle)
  465. $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
  466. $this->addArray($lineArray, $this->indent);
  467. foreach ($this->delayedPath as $indent => $delayedPath)
  468. $this->path[$indent] = $delayedPath;
  469. $this->delayedPath = array();
  470. }
  471. return $this->result;
  472. }
  473. private function loadFromSource ($input) {
  474. if (!empty($input) && strpos($input, "\n") === false && file_exists($input))
  475. $input = file_get_contents($input);
  476. return $this->loadFromString($input);
  477. }
  478. private function loadFromString ($input) {
  479. $lines = explode("\n",$input);
  480. foreach ($lines as $k => $_) {
  481. $lines[$k] = rtrim ($_, "\r");
  482. }
  483. return $lines;
  484. }
  485. /**
  486. * Parses YAML code and returns an array for a node
  487. * @access private
  488. * @return array
  489. * @param string $line A line from the YAML file
  490. */
  491. private function _parseLine($line) {
  492. if (!$line) return array();
  493. $line = trim($line);
  494. if (!$line) return array();
  495. $array = array();
  496. $group = $this->nodeContainsGroup($line);
  497. if ($group) {
  498. $this->addGroup($line, $group);
  499. $line = $this->stripGroup ($line, $group);
  500. }
  501. if ($this->startsMappedSequence($line))
  502. return $this->returnMappedSequence($line);
  503. if ($this->startsMappedValue($line))
  504. return $this->returnMappedValue($line);
  505. if ($this->isArrayElement($line))
  506. return $this->returnArrayElement($line);
  507. if ($this->isPlainArray($line))
  508. return $this->returnPlainArray($line);
  509. return $this->returnKeyValuePair($line);
  510. }
  511. /**
  512. * Finds the type of the passed value, returns the value as the new type.
  513. * @access private
  514. * @param string $value
  515. * @return mixed
  516. */
  517. private function _toType($value) {
  518. if ($value === '') return "";
  519. $first_character = $value[0];
  520. $last_character = substr($value, -1, 1);
  521. $is_quoted = false;
  522. do {
  523. if (!$value) break;
  524. if ($first_character != '"' && $first_character != "'") break;
  525. if ($last_character != '"' && $last_character != "'") break;
  526. $is_quoted = true;
  527. } while (0);
  528. if ($is_quoted) {
  529. $value = str_replace('\n', "\n", $value);
  530. return strtr(substr ($value, 1, -1), array ('\\"' => '"', '\'\'' => '\'', '\\\'' => '\''));
  531. }
  532. if (strpos($value, ' #') !== false && !$is_quoted)
  533. $value = preg_replace('/\s+#(.+)$/','',$value);
  534. if ($first_character == '[' && $last_character == ']') {
  535. // Take out strings sequences and mappings
  536. $innerValue = trim(substr ($value, 1, -1));
  537. if ($innerValue === '') return array();
  538. $explode = $this->_inlineEscape($innerValue);
  539. // Propagate value array
  540. $value = array();
  541. foreach ($explode as $v) {
  542. $value[] = $this->_toType($v);
  543. }
  544. return $value;
  545. }
  546. if (strpos($value,': ')!==false && $first_character != '{') {
  547. $array = explode(': ',$value);
  548. $key = trim($array[0]);
  549. array_shift($array);
  550. $value = trim(implode(': ',$array));
  551. $value = $this->_toType($value);
  552. return array($key => $value);
  553. }
  554. if ($first_character == '{' && $last_character == '}') {
  555. $innerValue = trim(substr ($value, 1, -1));
  556. if ($innerValue === '') return array();
  557. // Inline Mapping
  558. // Take out strings sequences and mappings
  559. $explode = $this->_inlineEscape($innerValue);
  560. // Propagate value array
  561. $array = array();
  562. foreach ($explode as $v) {
  563. $SubArr = $this->_toType($v);
  564. if (empty($SubArr)) continue;
  565. if (is_array ($SubArr)) {
  566. $array[key($SubArr)] = $SubArr[key($SubArr)]; continue;
  567. }
  568. $array[] = $SubArr;
  569. }
  570. return $array;
  571. }
  572. if ($value == 'null' || $value == 'NULL' || $value == 'Null' || $value == '' || $value == '~') {
  573. return null;
  574. }
  575. if ( is_numeric($value) && preg_match ('/^(-|)[1-9]+[0-9]*$/', $value) ){
  576. $intvalue = (int)$value;
  577. if ($intvalue != PHP_INT_MAX)
  578. $value = $intvalue;
  579. return $value;
  580. }
  581. if (is_numeric($value) && preg_match('/^0[xX][0-9a-fA-F]+$/', $value)) {
  582. // Hexadecimal value.
  583. return hexdec($value);
  584. }
  585. $this->coerceValue($value);
  586. if (is_numeric($value)) {
  587. if ($value === '0') return 0;
  588. if (rtrim ($value, 0) === $value)
  589. $value = (float)$value;
  590. return $value;
  591. }
  592. return $value;
  593. }
  594. /**
  595. * Used in inlines to check for more inlines or quoted strings
  596. * @access private
  597. * @return array
  598. */
  599. private function _inlineEscape($inline) {
  600. // There's gotta be a cleaner way to do this...
  601. // While pure sequences seem to be nesting just fine,
  602. // pure mappings and mappings with sequences inside can't go very
  603. // deep. This needs to be fixed.
  604. $seqs = array();
  605. $maps = array();
  606. $saved_strings = array();
  607. $saved_empties = array();
  608. // Check for empty strings
  609. $regex = '/("")|(\'\')/';
  610. if (preg_match_all($regex,$inline,$strings)) {
  611. $saved_empties = $strings[0];
  612. $inline = preg_replace($regex,'YAMLEmpty',$inline);
  613. }
  614. unset($regex);
  615. // Check for strings
  616. $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
  617. if (preg_match_all($regex,$inline,$strings)) {
  618. $saved_strings = $strings[0];
  619. $inline = preg_replace($regex,'YAMLString',$inline);
  620. }
  621. unset($regex);
  622. // echo $inline;
  623. $i = 0;
  624. do {
  625. // Check for sequences
  626. while (preg_match('/\[([^{}\[\]]+)\]/U',$inline,$matchseqs)) {
  627. $seqs[] = $matchseqs[0];
  628. $inline = preg_replace('/\[([^{}\[\]]+)\]/U', ('YAMLSeq' . (count($seqs) - 1) . 's'), $inline, 1);
  629. }
  630. // Check for mappings
  631. while (preg_match('/{([^\[\]{}]+)}/U',$inline,$matchmaps)) {
  632. $maps[] = $matchmaps[0];
  633. $inline = preg_replace('/{([^\[\]{}]+)}/U', ('YAMLMap' . (count($maps) - 1) . 's'), $inline, 1);
  634. }
  635. if ($i++ >= 10) break;
  636. } while (strpos ($inline, '[') !== false || strpos ($inline, '{') !== false);
  637. $explode = explode(',',$inline);
  638. $explode = array_map('trim', $explode);
  639. $stringi = 0; $i = 0;
  640. while (1) {
  641. // Re-add the sequences
  642. if (!empty($seqs)) {
  643. foreach ($explode as $key => $value) {
  644. if (strpos($value,'YAMLSeq') !== false) {
  645. foreach ($seqs as $seqk => $seq) {
  646. $explode[$key] = str_replace(('YAMLSeq'.$seqk.'s'),$seq,$value);
  647. $value = $explode[$key];
  648. }
  649. }
  650. }
  651. }
  652. // Re-add the mappings
  653. if (!empty($maps)) {
  654. foreach ($explode as $key => $value) {
  655. if (strpos($value,'YAMLMap') !== false) {
  656. foreach ($maps as $mapk => $map) {
  657. $explode[$key] = str_replace(('YAMLMap'.$mapk.'s'), $map, $value);
  658. $value = $explode[$key];
  659. }
  660. }
  661. }
  662. }
  663. // Re-add the strings
  664. if (!empty($saved_strings)) {
  665. foreach ($explode as $key => $value) {
  666. while (strpos($value,'YAMLString') !== false) {
  667. $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$stringi],$value, 1);
  668. unset($saved_strings[$stringi]);
  669. ++$stringi;
  670. $value = $explode[$key];
  671. }
  672. }
  673. }
  674. // Re-add the empties
  675. if (!empty($saved_empties)) {
  676. foreach ($explode as $key => $value) {
  677. while (strpos($value,'YAMLEmpty') !== false) {
  678. $explode[$key] = preg_replace('/YAMLEmpty/', '', $value, 1);
  679. $value = $explode[$key];
  680. }
  681. }
  682. }
  683. $finished = true;
  684. foreach ($explode as $key => $value) {
  685. if (strpos($value,'YAMLSeq') !== false) {
  686. $finished = false; break;
  687. }
  688. if (strpos($value,'YAMLMap') !== false) {
  689. $finished = false; break;
  690. }
  691. if (strpos($value,'YAMLString') !== false) {
  692. $finished = false; break;
  693. }
  694. if (strpos($value,'YAMLEmpty') !== false) {
  695. $finished = false; break;
  696. }
  697. }
  698. if ($finished) break;
  699. $i++;
  700. if ($i > 10)
  701. break; // Prevent infinite loops.
  702. }
  703. return $explode;
  704. }
  705. private function literalBlockContinues ($line, $lineIndent) {
  706. if (!trim($line)) return true;
  707. if (strlen($line) - strlen(ltrim($line)) > $lineIndent) return true;
  708. return false;
  709. }
  710. private function referenceContentsByAlias ($alias) {
  711. do {
  712. if (!isset($this->SavedGroups[$alias])) { echo "Bad group name: $alias."; break; }
  713. $groupPath = $this->SavedGroups[$alias];
  714. $value = $this->result;
  715. foreach ($groupPath as $k) {
  716. $value = $value[$k];
  717. }
  718. } while (false);
  719. return $value;
  720. }
  721. private function addArrayInline ($array, $indent) {
  722. $CommonGroupPath = $this->path;
  723. if (empty ($array)) return false;
  724. foreach ($array as $k => $_) {
  725. $this->addArray(array($k => $_), $indent);
  726. $this->path = $CommonGroupPath;
  727. }
  728. return true;
  729. }
  730. private function addArray ($incoming_data, $incoming_indent) {
  731. // print_r ($incoming_data);
  732. if (count ($incoming_data) > 1)
  733. return $this->addArrayInline ($incoming_data, $incoming_indent);
  734. $key = key ($incoming_data);
  735. $value = isset($incoming_data[$key]) ? $incoming_data[$key] : null;
  736. if ($key === '__!YAMLZero') $key = '0';
  737. if ($incoming_indent == 0 && !$this->_containsGroupAlias && !$this->_containsGroupAnchor) { // Shortcut for root-level values.
  738. if ($key || $key === '' || $key === '0') {
  739. $this->result[$key] = $value;
  740. } else {
  741. $this->result[] = $value; end ($this->result); $key = key ($this->result);
  742. }
  743. $this->path[$incoming_indent] = $key;
  744. return;
  745. }
  746. $history = array();
  747. // Unfolding inner array tree.
  748. $history[] = $_arr = $this->result;
  749. foreach ($this->path as $k) {
  750. $history[] = $_arr = $_arr[$k];
  751. }
  752. if ($this->_containsGroupAlias) {
  753. $value = $this->referenceContentsByAlias($this->_containsGroupAlias);
  754. $this->_containsGroupAlias = false;
  755. }
  756. // Adding string or numeric key to the innermost level or $this->arr.
  757. if (is_string($key) && $key == '<<') {
  758. if (!is_array ($_arr)) { $_arr = array (); }
  759. $_arr = array_merge ($_arr, $value);
  760. } else if ($key || $key === '' || $key === '0') {
  761. if (!is_array ($_arr))
  762. $_arr = array ($key=>$value);
  763. else
  764. $_arr[$key] = $value;
  765. } else {
  766. if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; }
  767. else { $_arr[] = $value; end ($_arr); $key = key ($_arr); }
  768. }
  769. $reverse_path = array_reverse($this->path);
  770. $reverse_history = array_reverse ($history);
  771. $reverse_history[0] = $_arr;
  772. $cnt = count($reverse_history) - 1;
  773. for ($i = 0; $i < $cnt; $i++) {
  774. $reverse_history[$i+1][$reverse_path[$i]] = $reverse_history[$i];
  775. }
  776. $this->result = $reverse_history[$cnt];
  777. $this->path[$incoming_indent] = $key;
  778. if ($this->_containsGroupAnchor) {
  779. $this->SavedGroups[$this->_containsGroupAnchor] = $this->path;
  780. if (is_array ($value)) {
  781. $k = key ($value);
  782. if (!is_int ($k)) {
  783. $this->SavedGroups[$this->_containsGroupAnchor][$incoming_indent + 2] = $k;
  784. }
  785. }
  786. $this->_containsGroupAnchor = false;
  787. }
  788. }
  789. private static function startsLiteralBlock ($line) {
  790. $lastChar = substr (trim($line), -1);
  791. if ($lastChar != '>' && $lastChar != '|') return false;
  792. if ($lastChar == '|') return $lastChar;
  793. // HTML tags should not be counted as literal blocks.
  794. if (preg_match ('#<.*?>$#', $line)) return false;
  795. return $lastChar;
  796. }
  797. private static function greedilyNeedNextLine($line) {
  798. $line = trim ($line);
  799. if (!strlen($line)) return false;
  800. if (substr ($line, -1, 1) == ']') return false;
  801. if ($line[0] == '[') return true;
  802. if (preg_match ('#^[^:]+?:\s*\[#', $line)) return true;
  803. return false;
  804. }
  805. private function addLiteralLine ($literalBlock, $line, $literalBlockStyle, $indent = -1) {
  806. $line = self::stripIndent($line, $indent);
  807. if ($literalBlockStyle !== '|') {
  808. $line = self::stripIndent($line);
  809. }
  810. $line = rtrim ($line, "\r\n\t ") . "\n";
  811. if ($literalBlockStyle == '|') {
  812. return $literalBlock . $line;
  813. }
  814. if (strlen($line) == 0)
  815. return rtrim($literalBlock, ' ') . "\n";
  816. if ($line == "\n" && $literalBlockStyle == '>') {
  817. return rtrim ($literalBlock, " \t") . "\n";
  818. }
  819. if ($line != "\n")
  820. $line = trim ($line, "\r\n ") . " ";
  821. return $literalBlock . $line;
  822. }
  823. function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
  824. foreach ($lineArray as $k => $_) {
  825. if (is_array($_))
  826. $lineArray[$k] = $this->revertLiteralPlaceHolder ($_, $literalBlock);
  827. else if (substr($_, -1 * strlen ($this->LiteralPlaceHolder)) == $this->LiteralPlaceHolder)
  828. $lineArray[$k] = rtrim ($literalBlock, " \r\n");
  829. }
  830. return $lineArray;
  831. }
  832. private static function stripIndent ($line, $indent = -1) {
  833. if ($indent == -1) $indent = strlen($line) - strlen(ltrim($line));
  834. return substr ($line, $indent);
  835. }
  836. private function getParentPathByIndent ($indent) {
  837. if ($indent == 0) return array();
  838. $linePath = $this->path;
  839. do {
  840. end($linePath); $lastIndentInParentPath = key($linePath);
  841. if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
  842. } while ($indent <= $lastIndentInParentPath);
  843. return $linePath;
  844. }
  845. private function clearBiggerPathValues ($indent) {
  846. if ($indent == 0) $this->path = array();
  847. if (empty ($this->path)) return true;
  848. foreach ($this->path as $k => $_) {
  849. if ($k > $indent) unset ($this->path[$k]);
  850. }
  851. return true;
  852. }
  853. private static function isComment ($line) {
  854. if (!$line) return false;
  855. if ($line[0] == '#') return true;
  856. if (trim($line, " \r\n\t") == '---') return true;
  857. return false;
  858. }
  859. private static function isEmpty ($line) {
  860. return (trim ($line) === '');
  861. }
  862. private function isArrayElement ($line) {
  863. if (!$line || !is_scalar($line)) return false;
  864. if (substr($line, 0, 2) != '- ') return false;
  865. if (strlen ($line) > 3)
  866. if (substr($line,0,3) == '---') return false;
  867. return true;
  868. }
  869. private function isHashElement ($line) {
  870. return strpos($line, ':');
  871. }
  872. private function isLiteral ($line) {
  873. if ($this->isArrayElement($line)) return false;
  874. if ($this->isHashElement($line)) return false;
  875. return true;
  876. }
  877. private static function unquote ($value) {
  878. if (!$value) return $value;
  879. if (!is_string($value)) return $value;
  880. if ($value[0] == '\'') return trim ($value, '\'');
  881. if ($value[0] == '"') return trim ($value, '"');
  882. return $value;
  883. }
  884. private function startsMappedSequence ($line) {
  885. return (substr($line, 0, 2) == '- ' && substr ($line, -1, 1) == ':');
  886. }
  887. private function returnMappedSequence ($line) {
  888. $array = array();
  889. $key = self::unquote(trim(substr($line,1,-1)));
  890. $array[$key] = array();
  891. $this->delayedPath = array(strpos ($line, $key) + $this->indent => $key);
  892. return array($array);
  893. }
  894. private function checkKeysInValue($value) {
  895. if (strchr('[{"\'', $value[0]) === false) {
  896. if (strchr($value, ': ') !== false) {
  897. throw new Exception('Too many keys: '.$value);
  898. }
  899. }
  900. }
  901. private function returnMappedValue ($line) {
  902. $this->checkKeysInValue($line);
  903. $array = array();
  904. $key = self::unquote (trim(substr($line,0,-1)));
  905. $array[$key] = '';
  906. return $array;
  907. }
  908. private function startsMappedValue ($line) {
  909. return (substr ($line, -1, 1) == ':');
  910. }
  911. private function isPlainArray ($line) {
  912. return ($line[0] == '[' && substr ($line, -1, 1) == ']');
  913. }
  914. private function returnPlainArray ($line) {
  915. return $this->_toType($line);
  916. }
  917. private function returnKeyValuePair ($line) {
  918. $array = array();
  919. $key = '';
  920. if (strpos ($line, ': ')) {
  921. // It's a key/value pair most likely
  922. // If the key is in double quotes pull it out
  923. if (($line[0] == '"' || $line[0] == "'") && preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
  924. $value = trim(str_replace($matches[1],'',$line));
  925. $key = $matches[2];
  926. } else {
  927. // Do some guesswork as to the key and the value
  928. $explode = explode(': ', $line);
  929. $key = trim(array_shift($explode));
  930. $value = trim(implode(': ', $explode));
  931. $this->checkKeysInValue($value);
  932. }
  933. // Set the type of the value. Int, string, etc
  934. $value = $this->_toType($value);
  935. if ($key === '0') $key = '__!YAMLZero';
  936. $array[$key] = $value;
  937. } else {
  938. $array = array ($line);
  939. }
  940. return $array;
  941. }
  942. private function returnArrayElement ($line) {
  943. if (strlen($line) <= 1) return array(array()); // Weird %)
  944. $array = array();
  945. $value = trim(substr($line,1));
  946. $value = $this->_toType($value);
  947. if ($this->isArrayElement($value)) {
  948. $value = $this->returnArrayElement($value);
  949. }
  950. $array[] = $value;
  951. return $array;
  952. }
  953. private function nodeContainsGroup ($line) {
  954. $symbolsForReference = 'A-z0-9_\-';
  955. if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
  956. if ($line[0] == '&' && preg_match('/^(&['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
  957. if ($line[0] == '*' && preg_match('/^(\*['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];
  958. if (preg_match('/(&['.$symbolsForReference.']+)$/', $line, $matches)) return $matches[1];
  959. if (preg_match('/(\*['.$symbolsForReference.']+$)/', $line, $matches)) return $matches[1];
  960. if (preg_match ('#^\s*<<\s*:\s*(\*[^\s]+).*$#', $line, $matches)) return $matches[1];
  961. return false;
  962. }
  963. private function addGroup ($line, $group) {
  964. if ($group[0] == '&') $this->_containsGroupAnchor = substr ($group, 1);
  965. if ($group[0] == '*') $this->_containsGroupAlias = substr ($group, 1);
  966. //print_r ($this->path);
  967. }
  968. private function stripGroup ($line, $group) {
  969. $line = trim(str_replace($group, '', $line));
  970. return $line;
  971. }
  972. }
  973. // Enable use of Spyc from command line
  974. // The syntax is the following: php Spyc.php spyc.yaml
  975. do {
  976. if (PHP_SAPI != 'cli') break;
  977. if (empty ($_SERVER['argc']) || $_SERVER['argc'] < 2) break;
  978. if (empty ($_SERVER['PHP_SELF']) || FALSE === strpos ($_SERVER['PHP_SELF'], 'Spyc.php') ) break;
  979. $file = $argv[1];
  980. echo json_encode (spyc_load_file ($file));
  981. } while (0);