Spyc.php 35 KB

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