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

1178 lines
35 KiB

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