PageRenderTime 96ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/xandra.org/www/modules/xenv/classes/Spyc.php

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