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

/libs/spyc/spyc-php5.php

https://github.com/Fusion/lenses
PHP | 741 lines | 435 code | 118 blank | 188 comment | 111 complexity | bc71d2674de31bf2e8909b3789ee3085 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Spyc -- A Simple PHP YAML Class
  4. * @version 0.3
  5. * @author Chris Wanstrath <chris@ozmm.org>
  6. * @author Vlad Andersen <vlad@oneiros.ru>
  7. * @link http://spyc.sourceforge.net/
  8. * @copyright Copyright 2005-2006 Chris Wanstrath
  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. * $parser = new Spyc;
  22. * $array = $parser->load($file);
  23. * </code>
  24. * @package Spyc
  25. */
  26. class Spyc {
  27. /**#@+
  28. * @access private
  29. * @var mixed
  30. */
  31. private $_haveRefs;
  32. private $_allNodes;
  33. private $_allParent;
  34. private $_lastIndent;
  35. private $_lastNode;
  36. private $_inBlock;
  37. private $_isInline;
  38. private $_dumpIndent;
  39. private $_dumpWordWrap;
  40. private $_containsGroupAnchor = false;
  41. private $_containsGroupAlias = false;
  42. private $path;
  43. private $result;
  44. private $LiteralBlockMarkers = array ('>', '|');
  45. private $LiteralPlaceHolder = '___YAML_Literal_Block___';
  46. private $SavedGroups = array();
  47. /**#@+
  48. * @access public
  49. * @var mixed
  50. */
  51. public $_nodeId;
  52. /**
  53. * Load YAML into a PHP array statically
  54. *
  55. * The load method, when supplied with a YAML stream (string or file),
  56. * will do its best to convert YAML in a file into a PHP array. Pretty
  57. * simple.
  58. * Usage:
  59. * <code>
  60. * $array = Spyc::YAMLLoad('lucky.yaml');
  61. * print_r($array);
  62. * </code>
  63. * @access public
  64. * @return array
  65. * @param string $input Path of YAML file or string containing YAML
  66. */
  67. public static function YAMLLoad($input) {
  68. $Spyc = new Spyc;
  69. return $Spyc->load($input);
  70. }
  71. /**
  72. * Dump YAML from PHP array statically
  73. *
  74. * The dump method, when supplied with an array, will do its best
  75. * to convert the array into friendly YAML. Pretty simple. Feel free to
  76. * save the returned string as nothing.yaml and pass it around.
  77. *
  78. * Oh, and you can decide how big the indent is and what the wordwrap
  79. * for folding is. Pretty cool -- just pass in 'false' for either if
  80. * you want to use the default.
  81. *
  82. * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
  83. * you can turn off wordwrap by passing in 0.
  84. *
  85. * @access public
  86. * @return string
  87. * @param array $array PHP array
  88. * @param int $indent Pass in false to use the default, which is 2
  89. * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
  90. */
  91. public static function YAMLDump($array,$indent = false,$wordwrap = false) {
  92. $spyc = new Spyc;
  93. return $spyc->dump($array,$indent,$wordwrap);
  94. }
  95. /**
  96. * Dump PHP array to YAML
  97. *
  98. * The dump method, when supplied with an array, will do its best
  99. * to convert the array into friendly YAML. Pretty simple. Feel free to
  100. * save the returned string as tasteful.yaml and pass it around.
  101. *
  102. * Oh, and you can decide how big the indent is and what the wordwrap
  103. * for folding is. Pretty cool -- just pass in 'false' for either if
  104. * you want to use the default.
  105. *
  106. * Indent's default is 2 spaces, wordwrap's default is 40 characters. And
  107. * you can turn off wordwrap by passing in 0.
  108. *
  109. * @access public
  110. * @return string
  111. * @param array $array PHP array
  112. * @param int $indent Pass in false to use the default, which is 2
  113. * @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
  114. */
  115. public function dump($array,$indent = false,$wordwrap = false) {
  116. // Dumps to some very clean YAML. We'll have to add some more features
  117. // and options soon. And better support for folding.
  118. // New features and options.
  119. if ($indent === false or !is_numeric($indent)) {
  120. $this->_dumpIndent = 2;
  121. } else {
  122. $this->_dumpIndent = $indent;
  123. }
  124. if ($wordwrap === false or !is_numeric($wordwrap)) {
  125. $this->_dumpWordWrap = 40;
  126. } else {
  127. $this->_dumpWordWrap = $wordwrap;
  128. }
  129. // New YAML document
  130. $string = "---\n";
  131. // Start at the base of the array and move through it.
  132. foreach ($array as $key => $value) {
  133. $string .= $this->_yamlize($key,$value,0);
  134. }
  135. return $string;
  136. }
  137. /**
  138. * Attempts to convert a key / value array item to YAML
  139. * @access private
  140. * @return string
  141. * @param $key The name of the key
  142. * @param $value The value of the item
  143. * @param $indent The indent of the current node
  144. */
  145. private function _yamlize($key,$value,$indent) {
  146. if (is_array($value)) {
  147. // It has children. What to do?
  148. // Make it the right kind of item
  149. $string = $this->_dumpNode($key,NULL,$indent);
  150. // Add the indent
  151. $indent += $this->_dumpIndent;
  152. // Yamlize the array
  153. $string .= $this->_yamlizeArray($value,$indent);
  154. } elseif (!is_array($value)) {
  155. // It doesn't have children. Yip.
  156. $string = $this->_dumpNode($key,$value,$indent);
  157. }
  158. return $string;
  159. }
  160. /**
  161. * Attempts to convert an array to YAML
  162. * @access private
  163. * @return string
  164. * @param $array The array you want to convert
  165. * @param $indent The indent of the current level
  166. */
  167. private function _yamlizeArray($array,$indent) {
  168. if (is_array($array)) {
  169. $string = '';
  170. foreach ($array as $key => $value) {
  171. $string .= $this->_yamlize($key,$value,$indent);
  172. }
  173. return $string;
  174. } else {
  175. return false;
  176. }
  177. }
  178. /**
  179. * Returns YAML from a key and a value
  180. * @access private
  181. * @return string
  182. * @param $key The name of the key
  183. * @param $value The value of the item
  184. * @param $indent The indent of the current node
  185. */
  186. private function _dumpNode($key,$value,$indent) {
  187. // do some folding here, for blocks
  188. if (strpos($value,"\n") !== false || strpos($value,": ") !== false || strpos($value,"- ") !== false) {
  189. $value = $this->_doLiteralBlock($value,$indent);
  190. } else {
  191. $value = $this->_doFolding($value,$indent);
  192. }
  193. if (is_bool($value)) {
  194. $value = ($value) ? "true" : "false";
  195. }
  196. $spaces = str_repeat(' ',$indent);
  197. if (is_int($key)) {
  198. // It's a sequence
  199. $string = $spaces.'- '.$value."\n";
  200. } else {
  201. // It's mapped
  202. $string = $spaces.$key.': '.$value."\n";
  203. }
  204. return $string;
  205. }
  206. /**
  207. * Creates a literal block for dumping
  208. * @access private
  209. * @return string
  210. * @param $value
  211. * @param $indent int The value of the indent
  212. */
  213. private function _doLiteralBlock($value,$indent) {
  214. $exploded = explode("\n",$value);
  215. $newValue = '|';
  216. $indent += $this->_dumpIndent;
  217. $spaces = str_repeat(' ',$indent);
  218. foreach ($exploded as $line) {
  219. $newValue .= "\n" . $spaces . trim($line);
  220. }
  221. return $newValue;
  222. }
  223. /**
  224. * Folds a string of text, if necessary
  225. * @access private
  226. * @return string
  227. * @param $value The string you wish to fold
  228. */
  229. private function _doFolding($value,$indent) {
  230. // Don't do anything if wordwrap is set to 0
  231. if ($this->_dumpWordWrap === 0) {
  232. return $value;
  233. }
  234. if (strlen($value) > $this->_dumpWordWrap) {
  235. $indent += $this->_dumpIndent;
  236. $indent = str_repeat(' ',$indent);
  237. $wrapped = wordwrap($value,$this->_dumpWordWrap,"\n$indent");
  238. $value = ">\n".$indent.$wrapped;
  239. }
  240. return $value;
  241. }
  242. /* LOADING FUNCTIONS */
  243. private function load($input) {
  244. $Source = $this->loadFromSource($input);
  245. if (empty ($Source)) return array();
  246. $this->path = array();
  247. $this->result = array();
  248. $cnt = count($Source); # CFR
  249. for ($i = 0; $i < $cnt; $i++) { # CFR
  250. $line = $Source[$i];
  251. $lineIndent = $this->_getIndent($line);
  252. $this->path = $this->getParentPathByIndent($lineIndent);
  253. $line = $this->stripIndent($line, $lineIndent);
  254. if ($this->isComment($line)) continue;
  255. if ($literalBlockStyle = $this->startsLiteralBlock($line)) {
  256. $line = rtrim ($line, $literalBlockStyle . "\n");
  257. $literalBlock = '';
  258. $line .= $this->LiteralPlaceHolder;
  259. while ($i < $cnt && $this->literalBlockContinues($Source[++$i], $lineIndent)) {
  260. $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle);
  261. }
  262. $i--;
  263. }
  264. $lineArray = $this->_parseLine($line);
  265. if ($literalBlockStyle)
  266. $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
  267. $this->addArray($lineArray, $lineIndent);
  268. }
  269. return $this->result;
  270. }
  271. private function loadFromSource ($input) {
  272. if (!empty($input) && strpos($input, "\n") === false && file_exists($input))
  273. return file($input);
  274. $foo = explode("\n",$input);
  275. foreach ($foo as $k => $_) {
  276. $foo[$k] = trim ($_, "\r");
  277. }
  278. return $foo;
  279. }
  280. /**
  281. * Finds and returns the indentation of a YAML line
  282. * @access private
  283. * @return int
  284. * @param string $line A line from the YAML file
  285. */
  286. private function _getIndent($line) {
  287. if (!preg_match('/^ +/',$line,$match)) return 0;
  288. if (!empty($match[0])) return strlen ($match[0]);
  289. return 0;
  290. }
  291. /**
  292. * Parses YAML code and returns an array for a node
  293. * @access private
  294. * @return array
  295. * @param string $line A line from the YAML file
  296. */
  297. private function _parseLine($line) {
  298. if (!$line) return array();
  299. $line = trim($line);
  300. if (!$line) return array();
  301. $array = array();
  302. if ($group = $this->nodeContainsGroup($line)) {
  303. $this->addGroup($line, $group);
  304. $line = $this->stripGroup ($line, $group);
  305. }
  306. if ($this->startsMappedSequence($line))
  307. return $this->returnMappedSequence($line);
  308. if ($this->startsMappedValue($line))
  309. return $this->returnMappedValue($line);
  310. if ($this->isArrayElement($line))
  311. return $this->returnArrayElement($line);
  312. return $this->returnKeyValuePair($line);
  313. }
  314. /**
  315. * Finds the type of the passed value, returns the value as the new type.
  316. * @access private
  317. * @param string $value
  318. * @return mixed
  319. */
  320. private function _toType($value) {
  321. if (strpos($value, '#') !== false)
  322. $value = trim(preg_replace('/#(.+)$/','',$value));
  323. if (preg_match('/^("(.*)"|\'(.*)\')/',$value,$matches)) {
  324. $value = (string)preg_replace('/(\'\'|\\\\\')/',"'",end($matches));
  325. $value = preg_replace('/\\\\"/','"',$value);
  326. } elseif (preg_match('/^\\[(.+)\\]$/',$value,$matches)) {
  327. // Inline Sequence
  328. // Take out strings sequences and mappings
  329. $explode = $this->_inlineEscape($matches[1]);
  330. // Propogate value array
  331. $value = array();
  332. foreach ($explode as $v) {
  333. $value[] = $this->_toType($v);
  334. }
  335. } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
  336. // It's a map
  337. $array = explode(': ',$value);
  338. $key = trim($array[0]);
  339. array_shift($array);
  340. $value = trim(implode(': ',$array));
  341. $value = $this->_toType($value);
  342. $value = array($key => $value);
  343. } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
  344. // Inline Mapping
  345. // Take out strings sequences and mappings
  346. $explode = $this->_inlineEscape($matches[1]);
  347. // Propogate value array
  348. $array = array();
  349. foreach ($explode as $v) {
  350. $array = $array + $this->_toType($v);
  351. }
  352. $value = $array;
  353. } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
  354. $value = null;
  355. } elseif (preg_match ('/^[0-9]+$/', $value)) {
  356. $value = (int)$value;
  357. } elseif (in_array(strtolower($value),
  358. array('true', 'on', '+', 'yes', 'y'))) {
  359. $value = true;
  360. } elseif (in_array(strtolower($value),
  361. array('false', 'off', '-', 'no', 'n'))) {
  362. $value = false;
  363. } elseif (is_numeric($value)) {
  364. $value = (float)$value;
  365. } else {
  366. // Just a normal string, right?
  367. // $value = trim(preg_replace('/#(.+)$/','',$value));
  368. }
  369. // print_r ($value);
  370. return $value;
  371. }
  372. /**
  373. * Used in inlines to check for more inlines or quoted strings
  374. * @access private
  375. * @return array
  376. */
  377. private function _inlineEscape($inline) {
  378. // There's gotta be a cleaner way to do this...
  379. // While pure sequences seem to be nesting just fine,
  380. // pure mappings and mappings with sequences inside can't go very
  381. // deep. This needs to be fixed.
  382. $saved_strings = array();
  383. // Check for strings
  384. $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
  385. if (preg_match_all($regex,$inline,$strings)) {
  386. $saved_strings = $strings[0];
  387. $inline = preg_replace($regex,'YAMLString',$inline);
  388. }
  389. unset($regex);
  390. // Check for sequences
  391. if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
  392. $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
  393. $seqs = $seqs[0];
  394. }
  395. // Check for mappings
  396. if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
  397. $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
  398. $maps = $maps[0];
  399. }
  400. $explode = explode(', ',$inline);
  401. // Re-add the sequences
  402. if (!empty($seqs)) {
  403. $i = 0;
  404. foreach ($explode as $key => $value) {
  405. if (strpos($value,'YAMLSeq') !== false) {
  406. $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
  407. ++$i;
  408. }
  409. }
  410. }
  411. // Re-add the mappings
  412. if (!empty($maps)) {
  413. $i = 0;
  414. foreach ($explode as $key => $value) {
  415. if (strpos($value,'YAMLMap') !== false) {
  416. $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
  417. ++$i;
  418. }
  419. }
  420. }
  421. // Re-add the strings
  422. if (!empty($saved_strings)) {
  423. $i = 0;
  424. foreach ($explode as $key => $value) {
  425. while (strpos($value,'YAMLString') !== false) {
  426. $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$i],$value, 1);
  427. ++$i;
  428. $value = $explode[$key];
  429. }
  430. }
  431. }
  432. return $explode;
  433. }
  434. private function literalBlockContinues ($line, $lineIndent) {
  435. if (!trim($line)) return true;
  436. if ($this->_getIndent($line) > $lineIndent) return true;
  437. return false;
  438. }
  439. private function addArray ($array, $indent) {
  440. $key = key ($array);
  441. if (!isset ($array[$key])) return false;
  442. if ($array[$key] === array()) { $array[$key] = ''; };
  443. $value = $array[$key];
  444. // Unfolding inner array tree as defined in $this->_arrpath.
  445. //$_arr = $this->result; $_tree[0] = $_arr; $i = 1;
  446. $tempPath = Spyc::flatten ($this->path);
  447. eval ('$_arr = $this->result' . $tempPath . ';');
  448. if ($this->_containsGroupAlias) {
  449. do {
  450. if (!isset($this->SavedGroups[$this->_containsGroupAlias])) { echo "Bad group name: $this->_containsGroupAlias."; break; }
  451. $groupPath = $this->SavedGroups[$this->_containsGroupAlias];
  452. eval ('$value = $this->result' . Spyc::flatten ($groupPath) . ';');
  453. } while (false);
  454. $this->_containsGroupAlias = false;
  455. }
  456. // Adding string or numeric key to the innermost level or $this->arr.
  457. if ($key)
  458. $_arr[$key] = $value;
  459. else {
  460. if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; }
  461. else { $_arr[] = $value; end ($_arr); $key = key ($_arr); }
  462. }
  463. $this->path[$indent] = $key;
  464. eval ('$this->result' . $tempPath . ' = $_arr;');
  465. if ($this->_containsGroupAnchor) {
  466. $this->SavedGroups[$this->_containsGroupAnchor] = $this->path;
  467. $this->_containsGroupAnchor = false;
  468. }
  469. }
  470. private function flatten ($array) {
  471. $tempPath = array();
  472. if (!empty ($array)) {
  473. foreach ($array as $_) {
  474. if (!is_int($_)) $_ = "'$_'";
  475. $tempPath[] = "[$_]";
  476. }
  477. }
  478. //end ($tempPath); $latestKey = key($tempPath);
  479. $tempPath = implode ('', $tempPath);
  480. return $tempPath;
  481. }
  482. private function startsLiteralBlock ($line) {
  483. $lastChar = substr (trim($line), -1);
  484. if (in_array ($lastChar, $this->LiteralBlockMarkers))
  485. return $lastChar;
  486. return false;
  487. }
  488. private function addLiteralLine ($literalBlock, $line, $literalBlockStyle) {
  489. $line = $this->stripIndent($line);
  490. $line = str_replace ("\r\n", "\n", $line);
  491. if ($literalBlockStyle == '|') {
  492. return $literalBlock . $line;
  493. }
  494. if (strlen($line) == 0) return $literalBlock . "\n";
  495. // echo "|$line|";
  496. if ($line != "\n")
  497. $line = trim ($line, "\r\n ") . " ";
  498. return $literalBlock . $line;
  499. }
  500. private function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
  501. foreach ($lineArray as $k => $_) {
  502. if (substr($_, -1 * strlen ($this->LiteralPlaceHolder)) == $this->LiteralPlaceHolder)
  503. $lineArray[$k] = rtrim ($literalBlock, " \r\n");
  504. }
  505. return $lineArray;
  506. }
  507. private function stripIndent ($line, $indent = -1) {
  508. if ($indent == -1) $indent = $this->_getIndent($line);
  509. return substr ($line, $indent);
  510. }
  511. private function getParentPathByIndent ($indent) {
  512. if ($indent == 0) return array();
  513. $linePath = $this->path;
  514. do {
  515. end($linePath); $lastIndentInParentPath = key($linePath);
  516. if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
  517. } while ($indent <= $lastIndentInParentPath);
  518. return $linePath;
  519. }
  520. private function clearBiggerPathValues ($indent) {
  521. if ($indent == 0) $this->path = array();
  522. if (empty ($this->path)) return true;
  523. foreach ($this->path as $k => $_) {
  524. if ($k > $indent) unset ($this->path[$k]);
  525. }
  526. return true;
  527. }
  528. private function isComment ($line) {
  529. if (preg_match('/^#/', $line)) return true;
  530. return false;
  531. }
  532. private function isArrayElement ($line) {
  533. if (!$line) return false;
  534. if ($line[0] != '-') return false;
  535. if (strlen ($line) > 3)
  536. if (substr($line,0,3) == '---') return false;
  537. return true;
  538. }
  539. private function isHashElement ($line) {
  540. if (!preg_match('/^(.+?):/', $line, $matches)) return false;
  541. $allegedKey = $matches[1];
  542. if ($allegedKey) return true;
  543. //if (substr_count($allegedKey, )
  544. return false;
  545. }
  546. private function isLiteral ($line) {
  547. if ($this->isArrayElement($line)) return false;
  548. if ($this->isHashElement($line)) return false;
  549. return true;
  550. }
  551. private function startsMappedSequence ($line) {
  552. if (preg_match('/^-(.*):$/',$line)) return true;
  553. }
  554. private function returnMappedSequence ($line) {
  555. $array = array();
  556. $key = trim(substr(substr($line,1),0,-1));
  557. $array[$key] = '';
  558. return $array;
  559. }
  560. private function returnMappedValue ($line) {
  561. $array = array();
  562. $key = trim(substr($line,0,-1));
  563. $array[$key] = '';
  564. return $array;
  565. }
  566. private function startsMappedValue ($line) {
  567. if (preg_match('/^(.*):$/',$line)) return true;
  568. }
  569. private function returnKeyValuePair ($line) {
  570. $array = array();
  571. if (preg_match('/^(.+):/',$line,$key)) {
  572. // It's a key/value pair most likely
  573. // If the key is in double quotes pull it out
  574. if (preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
  575. $value = trim(str_replace($matches[1],'',$line));
  576. $key = $matches[2];
  577. } else {
  578. // Do some guesswork as to the key and the value
  579. $explode = explode(':',$line);
  580. $key = trim($explode[0]);
  581. array_shift($explode);
  582. $value = trim(implode(':',$explode));
  583. }
  584. // Set the type of the value. Int, string, etc
  585. $value = $this->_toType($value);
  586. if (empty($key)) {
  587. $array[] = $value;
  588. } else {
  589. $array[$key] = $value;
  590. }
  591. }
  592. return $array;
  593. }
  594. private function returnArrayElement ($line) {
  595. if (strlen($line) <= 1) return array(array()); // Weird %)
  596. $array = array();
  597. $value = trim(substr($line,1));
  598. $value = $this->_toType($value);
  599. $array[] = $value;
  600. return $array;
  601. }
  602. private function nodeContainsGroup ($line) {
  603. if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
  604. if (preg_match('/^(&[^ ]+)/', $line, $matches)) return $matches[1];
  605. if (preg_match('/^(\*[^ ]+)/', $line, $matches)) return $matches[1];
  606. if (preg_match('/(&[^" ]+$)/', $line, $matches)) return $matches[1];
  607. if (preg_match('/(\*[^" ]+$)/', $line, $matches)) return $matches[1];
  608. return false;
  609. }
  610. private function addGroup ($line, $group) {
  611. if (substr ($group, 0, 1) == '&') $this->_containsGroupAnchor = substr ($group, 1);
  612. if (substr ($group, 0, 1) == '*') $this->_containsGroupAlias = substr ($group, 1);
  613. //print_r ($this->path);
  614. }
  615. private function stripGroup ($line, $group) {
  616. $line = trim(str_replace($group, '', $line));
  617. return $line;
  618. }
  619. }
  620. ?>