PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/addons/_defensio/libraries/spyc.php

https://github.com/aravindc/pixelpost
PHP | 739 lines | 433 code | 119 blank | 187 comment | 110 complexity | e4a70ea9b868232d5afe6e17d55e9b15 MD5 | raw file
Possible License(s): GPL-2.0
  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. var $_haveRefs;
  32. var $_allNodes;
  33. var $_allParent;
  34. var $_lastIndent;
  35. var $_lastNode;
  36. var $_inBlock;
  37. var $_isInline;
  38. var $_dumpIndent;
  39. var $_dumpWordWrap;
  40. var $_containsGroupAnchor = false;
  41. var $_containsGroupAlias = false;
  42. var $path;
  43. var $result;
  44. var $LiteralBlockMarkers = array ('>', '|');
  45. var $LiteralPlaceHolder = '___YAML_Literal_Block___';
  46. var $SavedGroups = array();
  47. /**#@+
  48. * @access public
  49. * @var mixed
  50. */
  51. var $_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. 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. 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. 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. 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. 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. 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. 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. 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. function load($input) {
  244. $Source = $this->loadFromSource($input);
  245. if (empty ($Source)) return array();
  246. $this->path = array();
  247. $this->result = array();
  248. for ($i = 0; $i < count($Source); $i++) {
  249. $line = $Source[$i];
  250. $lineIndent = $this->_getIndent($line);
  251. $this->path = $this->getParentPathByIndent($lineIndent);
  252. $line = $this->stripIndent($line, $lineIndent);
  253. if ($this->isComment($line)) continue;
  254. if ($literalBlockStyle = $this->startsLiteralBlock($line)) {
  255. $line = rtrim ($line, $literalBlockStyle . "\n");
  256. $literalBlock = '';
  257. $line .= $this->LiteralPlaceHolder;
  258. while ($this->literalBlockContinues($Source[++$i], $lineIndent)) {
  259. $literalBlock = $this->addLiteralLine($literalBlock, $Source[$i], $literalBlockStyle);
  260. }
  261. $i--;
  262. }
  263. $lineArray = $this->_parseLine($line);
  264. if ($literalBlockStyle)
  265. $lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
  266. $this->addArray($lineArray, $lineIndent);
  267. }
  268. return $this->result;
  269. }
  270. function loadFromSource ($input) {
  271. if (!empty($input) && strpos($input, "\n") === false && file_exists($input))
  272. return file($input);
  273. $foo = explode("\n",$input);
  274. foreach ($foo as $k => $_) {
  275. $foo[$k] = trim ($_, "\r");
  276. }
  277. return $foo;
  278. }
  279. /**
  280. * Finds and returns the indentation of a YAML line
  281. * @access private
  282. * @return int
  283. * @param string $line A line from the YAML file
  284. */
  285. function _getIndent($line) {
  286. if (!preg_match('/^ +/',$line,$match)) return 0;
  287. if (!empty($match[0])) return strlen ($match[0]);
  288. return 0;
  289. }
  290. /**
  291. * Parses YAML code and returns an array for a node
  292. * @access private
  293. * @return array
  294. * @param string $line A line from the YAML file
  295. */
  296. function _parseLine($line) {
  297. if (!$line) return array();
  298. $line = trim($line);
  299. if (!$line) return array();
  300. $array = array();
  301. if ($group = $this->nodeContainsGroup($line)) {
  302. $this->addGroup($line, $group);
  303. $line = $this->stripGroup ($line, $group);
  304. }
  305. if ($this->startsMappedSequence($line))
  306. return $this->returnMappedSequence($line);
  307. if ($this->startsMappedValue($line))
  308. return $this->returnMappedValue($line);
  309. if ($this->isArrayElement($line))
  310. return $this->returnArrayElement($line);
  311. return $this->returnKeyValuePair($line);
  312. }
  313. /**
  314. * Finds the type of the passed value, returns the value as the new type.
  315. * @access private
  316. * @param string $value
  317. * @return mixed
  318. */
  319. function _toType($value) {
  320. if (strpos($value, '#') !== false)
  321. $value = trim(preg_replace('/#(.+)$/','',$value));
  322. if (preg_match('/^("(.*)"|\'(.*)\')/',$value,$matches)) {
  323. $value = (string)preg_replace('/(\'\'|\\\\\')/',"'",end($matches));
  324. $value = preg_replace('/\\\\"/','"',$value);
  325. } elseif (preg_match('/^\\[(.+)\\]$/',$value,$matches)) {
  326. // Inline Sequence
  327. // Take out strings sequences and mappings
  328. $explode = $this->_inlineEscape($matches[1]);
  329. // Propogate value array
  330. $value = array();
  331. foreach ($explode as $v) {
  332. $value[] = $this->_toType($v);
  333. }
  334. } elseif (strpos($value,': ')!==false && !preg_match('/^{(.+)/',$value)) {
  335. // It's a map
  336. $array = explode(': ',$value);
  337. $key = trim($array[0]);
  338. array_shift($array);
  339. $value = trim(implode(': ',$array));
  340. $value = $this->_toType($value);
  341. $value = array($key => $value);
  342. } elseif (preg_match("/{(.+)}$/",$value,$matches)) {
  343. // Inline Mapping
  344. // Take out strings sequences and mappings
  345. $explode = $this->_inlineEscape($matches[1]);
  346. // Propogate value array
  347. $array = array();
  348. foreach ($explode as $v) {
  349. $array = $array + $this->_toType($v);
  350. }
  351. $value = $array;
  352. } elseif (strtolower($value) == 'null' or $value == '' or $value == '~') {
  353. $value = null;
  354. } elseif (preg_match ('/^[0-9]+$/', $value)) {
  355. $value = (int)$value;
  356. } elseif (in_array(strtolower($value),
  357. array('true', 'on', '+', 'yes', 'y'))) {
  358. $value = true;
  359. } elseif (in_array(strtolower($value),
  360. array('false', 'off', '-', 'no', 'n'))) {
  361. $value = false;
  362. } elseif (is_numeric($value)) {
  363. $value = (float)$value;
  364. } else {
  365. // Just a normal string, right?
  366. }
  367. // print_r ($value);
  368. return $value;
  369. }
  370. /**
  371. * Used in inlines to check for more inlines or quoted strings
  372. * @access private
  373. * @return array
  374. */
  375. function _inlineEscape($inline) {
  376. // There's gotta be a cleaner way to do this...
  377. // While pure sequences seem to be nesting just fine,
  378. // pure mappings and mappings with sequences inside can't go very
  379. // deep. This needs to be fixed.
  380. $saved_strings = array();
  381. // Check for strings
  382. $regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
  383. if (preg_match_all($regex,$inline,$strings)) {
  384. $saved_strings = $strings[0];
  385. $inline = preg_replace($regex,'YAMLString',$inline);
  386. }
  387. unset($regex);
  388. // Check for sequences
  389. if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
  390. $inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
  391. $seqs = $seqs[0];
  392. }
  393. // Check for mappings
  394. if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
  395. $inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
  396. $maps = $maps[0];
  397. }
  398. $explode = explode(', ',$inline);
  399. // Re-add the sequences
  400. if (!empty($seqs)) {
  401. $i = 0;
  402. foreach ($explode as $key => $value) {
  403. if (strpos($value,'YAMLSeq') !== false) {
  404. $explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
  405. ++$i;
  406. }
  407. }
  408. }
  409. // Re-add the mappings
  410. if (!empty($maps)) {
  411. $i = 0;
  412. foreach ($explode as $key => $value) {
  413. if (strpos($value,'YAMLMap') !== false) {
  414. $explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
  415. ++$i;
  416. }
  417. }
  418. }
  419. // Re-add the strings
  420. if (!empty($saved_strings)) {
  421. $i = 0;
  422. foreach ($explode as $key => $value) {
  423. while (strpos($value,'YAMLString') !== false) {
  424. $explode[$key] = preg_replace('/YAMLString/',$saved_strings[$i],$value, 1);
  425. ++$i;
  426. $value = $explode[$key];
  427. }
  428. }
  429. }
  430. return $explode;
  431. }
  432. function literalBlockContinues ($line, $lineIndent) {
  433. if (!trim($line)) return true;
  434. if ($this->_getIndent($line) > $lineIndent) return true;
  435. return false;
  436. }
  437. function addArray ($array, $indent) {
  438. $key = key ($array);
  439. if (!isset ($array[$key])) return false;
  440. if ($array[$key] === array()) { $array[$key] = ''; };
  441. $value = $array[$key];
  442. // Unfolding inner array tree as defined in $this->_arrpath.
  443. //$_arr = $this->result; $_tree[0] = $_arr; $i = 1;
  444. $tempPath = Spyc::flatten ($this->path);
  445. eval ('$_arr = $this->result' . $tempPath . ';');
  446. if ($this->_containsGroupAlias) {
  447. do {
  448. if (!isset($this->SavedGroups[$this->_containsGroupAlias])) { echo "Bad group name: $this->_containsGroupAlias."; break; }
  449. $groupPath = $this->SavedGroups[$this->_containsGroupAlias];
  450. eval ('$value = $this->result' . Spyc::flatten ($groupPath) . ';');
  451. } while (false);
  452. $this->_containsGroupAlias = false;
  453. }
  454. // Adding string or numeric key to the innermost level or $this->arr.
  455. if ($key)
  456. $_arr[$key] = $value;
  457. else {
  458. if (!is_array ($_arr)) { $_arr = array ($value); $key = 0; }
  459. else { $_arr[] = $value; end ($_arr); $key = key ($_arr); }
  460. }
  461. $this->path[$indent] = $key;
  462. eval ('$this->result' . $tempPath . ' = $_arr;');
  463. if ($this->_containsGroupAnchor) {
  464. $this->SavedGroups[$this->_containsGroupAnchor] = $this->path;
  465. $this->_containsGroupAnchor = false;
  466. }
  467. }
  468. function flatten ($array) {
  469. $tempPath = array();
  470. if (!empty ($array)) {
  471. foreach ($array as $_) {
  472. if (!is_int($_)) $_ = "'$_'";
  473. $tempPath[] = "[$_]";
  474. }
  475. }
  476. //end ($tempPath); $latestKey = key($tempPath);
  477. $tempPath = implode ('', $tempPath);
  478. return $tempPath;
  479. }
  480. function startsLiteralBlock ($line) {
  481. $lastChar = substr (trim($line), -1);
  482. if (in_array ($lastChar, $this->LiteralBlockMarkers))
  483. return $lastChar;
  484. return false;
  485. }
  486. function addLiteralLine ($literalBlock, $line, $literalBlockStyle) {
  487. $line = $this->stripIndent($line);
  488. $line = str_replace ("\r\n", "\n", $line);
  489. if ($literalBlockStyle == '|') {
  490. return $literalBlock . $line;
  491. }
  492. if (strlen($line) == 0) return $literalBlock . "\n";
  493. // echo "|$line|";
  494. if ($line != "\n")
  495. $line = trim ($line, "\r\n ") . " ";
  496. return $literalBlock . $line;
  497. }
  498. function revertLiteralPlaceHolder ($lineArray, $literalBlock) {
  499. foreach ($lineArray as $k => $_) {
  500. if (substr($_, -1 * strlen ($this->LiteralPlaceHolder)) == $this->LiteralPlaceHolder)
  501. $lineArray[$k] = rtrim ($literalBlock, " \r\n");
  502. }
  503. return $lineArray;
  504. }
  505. function stripIndent ($line, $indent = -1) {
  506. if ($indent == -1) $indent = $this->_getIndent($line);
  507. return substr ($line, $indent);
  508. }
  509. function getParentPathByIndent ($indent) {
  510. if ($indent == 0) return array();
  511. $linePath = $this->path;
  512. do {
  513. end($linePath); $lastIndentInParentPath = key($linePath);
  514. if ($indent <= $lastIndentInParentPath) array_pop ($linePath);
  515. } while ($indent <= $lastIndentInParentPath);
  516. return $linePath;
  517. }
  518. function clearBiggerPathValues ($indent) {
  519. if ($indent == 0) $this->path = array();
  520. if (empty ($this->path)) return true;
  521. foreach ($this->path as $k => $_) {
  522. if ($k > $indent) unset ($this->path[$k]);
  523. }
  524. return true;
  525. }
  526. function isComment ($line) {
  527. if (preg_match('/^#/', $line)) return true;
  528. return false;
  529. }
  530. function isArrayElement ($line) {
  531. if (!$line) return false;
  532. if ($line[0] != '-') return false;
  533. if (strlen ($line) > 3)
  534. if (substr($line,0,3) == '---') return false;
  535. return true;
  536. }
  537. function isHashElement ($line) {
  538. if (!preg_match('/^(.+?):/', $line, $matches)) return false;
  539. $allegedKey = $matches[1];
  540. if ($allegedKey) return true;
  541. //if (substr_count($allegedKey, )
  542. return false;
  543. }
  544. function isLiteral ($line) {
  545. if ($this->isArrayElement($line)) return false;
  546. if ($this->isHashElement($line)) return false;
  547. return true;
  548. }
  549. function startsMappedSequence ($line) {
  550. if (preg_match('/^-(.*):$/',$line)) return true;
  551. }
  552. function returnMappedSequence ($line) {
  553. $array = array();
  554. $key = trim(substr(substr($line,1),0,-1));
  555. $array[$key] = '';
  556. return $array;
  557. }
  558. function returnMappedValue ($line) {
  559. $array = array();
  560. $key = trim(substr($line,0,-1));
  561. $array[$key] = '';
  562. return $array;
  563. }
  564. function startsMappedValue ($line) {
  565. if (preg_match('/^(.*):$/',$line)) return true;
  566. }
  567. function returnKeyValuePair ($line) {
  568. $array = array();
  569. if (preg_match('/^(.+):/',$line,$key)) {
  570. // It's a key/value pair most likely
  571. // If the key is in double quotes pull it out
  572. if (preg_match('/^(["\'](.*)["\'](\s)*:)/',$line,$matches)) {
  573. $value = trim(str_replace($matches[1],'',$line));
  574. $key = $matches[2];
  575. } else {
  576. // Do some guesswork as to the key and the value
  577. $explode = explode(':',$line);
  578. $key = trim($explode[0]);
  579. array_shift($explode);
  580. $value = trim(implode(':',$explode));
  581. }
  582. // Set the type of the value. Int, string, etc
  583. $value = $this->_toType($value);
  584. if (empty($key)) {
  585. $array[] = $value;
  586. } else {
  587. $array[$key] = $value;
  588. }
  589. }
  590. return $array;
  591. }
  592. function returnArrayElement ($line) {
  593. if (strlen($line) <= 1) return array(array()); // Weird %)
  594. $array = array();
  595. $value = trim(substr($line,1));
  596. $value = $this->_toType($value);
  597. $array[] = $value;
  598. return $array;
  599. }
  600. function nodeContainsGroup ($line) {
  601. if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
  602. if (preg_match('/^(&[^ ]+)/', $line, $matches)) return $matches[1];
  603. if (preg_match('/^(\*[^ ]+)/', $line, $matches)) return $matches[1];
  604. if (preg_match('/(&[^" ]+$)/', $line, $matches)) return $matches[1];
  605. if (preg_match('/(\*[^" ]+$)/', $line, $matches)) return $matches[1];
  606. return false;
  607. }
  608. function addGroup ($line, $group) {
  609. if (substr ($group, 0, 1) == '&') $this->_containsGroupAnchor = substr ($group, 1);
  610. if (substr ($group, 0, 1) == '*') $this->_containsGroupAlias = substr ($group, 1);
  611. //print_r ($this->path);
  612. }
  613. function stripGroup ($line, $group) {
  614. $line = trim(str_replace($group, '', $line));
  615. return $line;
  616. }
  617. }
  618. ?>