snom-provisioning

SNOM Phone provisioning
git clone http://git.code.weiherhei.de/snom-provisioning.git
Log | Files | Refs | README

Spyc.php (42680B)


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