spyc.php4 29 KB

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