Dumps a JS value to YAML.

@param	mixed	 input	The JS value
@param	integer inline The level where you switch to inline YAML
@param	integer indent The level o indentation indentation (used internally)

@return string	The YAML representation of the JS value
332504
function(input, inline, indent)
	{
		if ( inline == null ) inline = 0;
		if ( indent == null ) indent = 0;
		var output = '';
		var prefix = indent ? this.strRepeat(' ', indent) : '';
		var yaml;
		if (!this.numSpacesForIndentation) this.numSpacesForIndentation = 2;

		if ( inline <= 0 || !this.isObject(input) || this.isEmpty(input) )
		{
			yaml = new YamlInline();
			output += prefix + yaml.dump(input);
		}
		else
		{
			var isAHash = !this.arrayEquals(this.getKeys(input), this.range(0,input.length - 1));
			var willBeInlined;
			
			for ( var key in input )
			{
				if ( input.hasOwnProperty(key) )
				{
					willBeInlined = inline - 1 <= 0 || !this.isObject(input[key]) || this.isEmpty(input[key]);
					
					if ( isAHash ) yaml = new YamlInline();
					
					output += 
						prefix + '' +
						(isAHash ? yaml.dump(key)+':' : '-') + '' +
						(willBeInlined ? ' ' : "\n") + '' +
						this.dump(input[key], inline - 1, (willBeInlined ? 0 : indent + this.numSpacesForIndentation)) + '' +
						(willBeInlined ? "\n" : '');
				}
			}
		}

		return output;
	}
1370401
function serialize(value, indent) {
    "use strict";
    if (isArray(value)) {
        value = value.map(function _map(prop) {
            return isFunction(prop) ? prop.toString().replace(/\s{2,}/, '') : prop;
        });
    }
    return JSON.stringify(value, null, indent);
}
1323636
public static function varToString($input, $indent = '')
	{
		switch (gettype($input))
		{
			case 'string':
				return "'" . str_replace(array("\\", "'"), array("\\\\", "\\'"), $input) . "'";
			case 'array':
				$output = "array(\r\n";
				foreach ($input as $key => $value)
				{
					$output .= $indent . "\t" . self::varToString($key, $indent . "\t") . ' => ' . self::varToString(
						$value, $indent . "\t");
					$output .= ",\r\n";
				}
				$output .= $indent . ')';
				return $output;
			case 'boolean':
				return $input ? 'true' : 'false';
			case 'NULL':
				return 'NULL';
			case 'integer':
			case 'double':
			case 'float':
				return "'" . (string) $input . "'";
		}
		return 'NULL';
	}
1233782
protected function _jsonEncode($in, $indent = 0)
    {
        $out = '';

        foreach ($in as $key => $value) {

            $out .= str_repeat("    ", $indent + 1);
            $out .= json_encode((string)$key) . ': ';

            if (is_object($value) || is_array($value)) {
                $out .= $this->_jsonEncode($value, $indent + 1);
            } else {
                $out .= json_encode($value);
            }

            $out .= "," . PHP_EOL;
        }

        if (!empty($out)) {
            $out = substr($out, 0, -2);
        }

        $out = "{" . PHP_EOL . $out . PHP_EOL . str_repeat("    ", $indent) . "}";

        return $out;
    }
818329
function formatInput(val, countryCode, addSuffix, allowExtension, isAllowedKey) {
    try {
        var clean = val.replace(/\D/g, ""),
            // NOTE: we use AsYouTypeFormatter because the default format function can't handle incomplete numbers e.g. "+17024" formats to "+1 7024" as opposed to "+1 702-4"
            formatter = new i18n.phonenumbers.AsYouTypeFormatter(countryCode),
            // if clean is empty, we still need this to be a string otherwise we get errors later
            result = "",
            next,
            extSuffix = " ext. ";

        if (val.substr(0, 1) == "+") {
            clean = "+" + clean;
        }

        for (var i = 0; i < clean.length; i++) {
            // TODO: improve this so don't just pump in every digit every time - we should just cache this formatter object, and just call inputDigit once each time the user enters a new digit
            next = formatter.inputDigit(clean.charAt(i));
            // if adding this char didn't change the length, or made it smaller (and there's no longer any spaces): that means that formatting failed which means the number was no longer a potentially valid number, so if we're allowing extensions: assume the rest is the ext
            if (allowExtension && result && next.length <= result.length && next.indexOf(" ") == -1) {
                // set flag for extension
                next = -1;
                break;
            }
            result = next;
        }

        // for some reason libphonenumber formats "+44" to "+44 ", but doesn't do the same with "+1"
        if (result.charAt(result.length - 1) == " ") {
            result = result.substr(0, result.length - 1);
        }
        // check if there's a suffix to add (unless there's an ext)
        if (addSuffix && !val.split(extSuffix)[1]) {
            // hack to get formatting suffix
            var test = formatter.inputDigit('5');
            // again the "+44 " problem... (also affects "+45" apparently)
            if (test.charAt(test.length - 1) == " ") {
                test = test.substr(0, test.length - 1);
            }
            // if adding a '5' introduces a formatting char - check if the penultimate char is not-a-number
            var penultimate = test.substr(test.length - 2, 1);
            // Note: never use isNaN without parseFloat
            if (isNaN(parseFloat(penultimate))) {
                // return the new value (minus that last '5' we just added)
                return test.substr(0, test.length - 1);
            } else if (allowExtension && result && test.length <= result.length && test.indexOf(" ") == -1 && !isAllowedKey) {
                // else if the next digit would break the formating, and we're allowing extensions, AND this is not an allowed key: add the suffix
                // NOTE: we must check this is not an allowed key because if it was that means it was the last digit in a valid number and we dont want to add the "ext" suffix in that case. This whole condition is just here to catch the case that: after typing a valid number, they try to type "ext" - this will not automatically add it for them.
                return result + extSuffix;
            }
        }

        // if the clean number contains an extension we need to add it
        if (next == -1) {
            result += extSuffix + clean.substring(i, clean.length);
        }

        return result;
    } catch (e) {
        return val;
    }
}
220765
public function dump($input)
    {

        foreach ($this->lex($input) as $token) {

            $type = $token['type'];
            $line = $token['line'];
            $offset = $token['offset'];
            unset($token['type'], $token['line'], $token['offset']);

            echo "[$type($line:$offset)";
            $vals = implode(', ', array_map(function ($key, $value) {

                return "$key=$value";
            }, array_keys($token), $token));

            if (!empty($vals))
                echo " $vals";

            echo ']';

            if ($type === 'newLine')
                echo "\n";
        }
    }
962694
public static String escapeJsValue(SoyValue value) {
    // We surround values with spaces so that they can't be interpolated into identifiers
    // by accident.  We could use parentheses but those might be interpreted as a function call.
    if (NullData.INSTANCE == value || value == null) {
      // The JS counterpart of this code in soyutils.js emits " null " for both null and the special
      // JS value undefined.
      return " null ";
    } else if (value instanceof NumberData) {
      // This will emit references to NaN and Infinity.  Client code should not redefine those
      // to store sensitive data.
      return " " + value.numberValue() + " ";
    } else if (value instanceof BooleanData) {
      return " " + value.booleanValue() + " ";
    } else if (isSanitizedContentOfKind(value, SanitizedContent.ContentKind.JS)) {
      String jsCode = value.coerceToString();
      // This value may not be embeddable if it contains the substring "</script".
      // TODO(msamuel): Fixup.  We need to be careful because mucking with '<' can
      // break code like
      //    while (i</foo/.exec(str).length)
      // and mucking with / can break
      //    return untrustedHTML.replace(/</g, '&lt;');
      return jsCode;
    } else {
      return escapeJsValue(value.coerceToString());
    }
  }
1043948
function stringify(js, indent, indentUnit) {
    if (typeof indent === 'undefined') indent = '';
    if (typeof indentUnit === 'undefined') indentUnit = '  ';
    var t = typeof js;
    if (t === 'string') {
        return JSON.stringify(js);
    }
    if (t === 'number') {
        return js;
    }
    if (t === 'boolean') {
        return js ? "true" : "false";
    }
    var out = '', txt, small, lastIndent;
    if (Array.isArray(js)) {
        out = '[';
        txt = JSON.stringify(js);
        small = txt.length < 40;
        if (!small) out += "\n" + indent;
        js.forEach(
            function(itm, idx) {
                if (idx > 0) {
                    out += "," + (small ? " " : "\n" + indent);
                }
                out += stringify(itm, indent + indentUnit);
            }
        );
        out += ']';
        return out;
    }
    if (t === 'object') {
        lastIndent = indent;
        indent += indentUnit;
        out = '{';
        txt = JSON.stringify(js);
        small = txt.length < 40;
        if (!small) out += "\n" + indent;
        var k, v, idx = 0;
        for (k in js) {
            v = js[k];
            if (idx > 0) {
                out += "," + (small ? " " : "\n" + indent);
            }
            out += JSON.stringify(k) + ": " + stringify(v, indent);
            idx++;
        }
        out += (small ? "" : "\n" + lastIndent) + '}';
        return out;
    }
    return '"<' + t + '>"';
}
1071647
public function Render ($indent = 0) {
		$actualGroupItems = & $this->_getScriptsGroupContainer($this->actualGroupName);
		if (count($actualGroupItems) === 0) return '';
		$minify = (bool)self::$globalOptions['jsMinify'];
		$joinTogether = (bool)self::$globalOptions['jsJoin'];
		if ($joinTogether) {
			$result = $this->_renderItemsTogether(
				$this->actualGroupName,
				$actualGroupItems,
				$indent,
				$minify
			);
		} else {
			$result = $this->_renderItemsSeparated(
				$this->actualGroupName,
				$actualGroupItems,
				$indent,
				$minify
			);
		}
		return $result;
	}
482124
private function _inlineEscape($inline) {
		// There's gotta be a cleaner way to do this...
		// While pure sequences seem to be nesting just fine,
		// pure mappings and mappings with sequences inside can't go very
		// deep.  This needs to be fixed.

		$saved_strings = array();

		// Check for strings
		$regex = '/(?:(")|(?:\'))((?(1)[^"]+|[^\']+))(?(1)"|\')/';
		if (preg_match_all($regex,$inline,$strings)) {
			$saved_strings = $strings[0];
			$inline  = preg_replace($regex,'YAMLString',$inline);
		}
		unset($regex);

		// Check for sequences
		if (preg_match_all('/\[(.+)\]/U',$inline,$seqs)) {
			$inline = preg_replace('/\[(.+)\]/U','YAMLSeq',$inline);
			$seqs   = $seqs[0];
		}

		// Check for mappings
		if (preg_match_all('/{(.+)}/U',$inline,$maps)) {
			$inline = preg_replace('/{(.+)}/U','YAMLMap',$inline);
			$maps   = $maps[0];
		}

		$explode = explode(', ',$inline);


		// Re-add the sequences
		if (!empty($seqs)) {
			$i = 0;
			foreach ($explode as $key => $value) {
				if (strpos($value,'YAMLSeq') !== FALSE) {
					$explode[$key] = str_replace('YAMLSeq',$seqs[$i],$value);
					++$i;
				}
			}
		}

		// Re-add the mappings
		if (!empty($maps)) {
			$i = 0;
			foreach ($explode as $key => $value) {
				if (strpos($value,'YAMLMap') !== FALSE) {
					$explode[$key] = str_replace('YAMLMap',$maps[$i],$value);
					++$i;
				}
			}
		}


		// Re-add the strings
		if (!empty($saved_strings)) {
			$i = 0;
			foreach ($explode as $key => $value) {
				while (strpos($value,'YAMLString') !== FALSE) {
					$explode[$key] = preg_replace('/YAMLString/',$saved_strings[$i],$value, 1);
					++$i;
					$value = $explode[$key];
				}
			}
		}

		return $explode;
	}
1112725
function(mapping, i)
	{
		if ( i == undefined ) i = 0;
		var output = {};
		var len = mapping.length;
		i += 1;
		var done = false;
		var doContinue = false;

		// {foo: bar, bar:foo, ...}
		while ( i < len )
		{
			doContinue = false;
			
			switch ( mapping.charAt(i) )
			{
				case ' ':
				case ',':
					i++;
					doContinue = true;
					break;
				case '}':
					this.i = i;
					return output;
			}
			
			if ( doContinue ) continue;

			// key
			var key = this.parseScalar(mapping, [':', ' '], ['"', "'"], i, false);
			i = this.i;

			// value
			done = false;
			while ( i < len )
			{
				switch ( mapping.charAt(i) )
				{
					case '[':
						// nested sequence
						output[key] = this.parseSequence(mapping, i);
						i = this.i;
						done = true;
						break;
					case '{':
						// nested mapping
						output[key] = this.parseMapping(mapping, i);
						i = this.i;
						done = true;
						break;
					case ':':
					case ' ':
						break;
					default:
						output[key] = this.parseScalar(mapping, [',', '}'], ['"', "'"], i);
						i = this.i;
						done = true;
						i--;
				}

				++i;

				if ( done )
				{
					doContinue = true;
					break;
				}
			}
			
			if ( doContinue ) continue;
		}

		throw new YamlParseException('Malformed inline YAML string "'+mapping+'"');
	}
324185
private function dumpValue($value, $interpolate = true)
    {
        if (is_array($value)) {
            if ($value && $interpolate && false !== $param = array_search($value, $this->container->getParameterBag()->all(), true)) {
                return $this->dumpValue("%$param%");
            }
            $code = array();
            foreach ($value as $k => $v) {
                $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate));
            }

            return sprintf('array(%s)', implode(', ', $code));
        } elseif ($value instanceof ArgumentInterface) {
            $scope = array($this->definitionVariables, $this->referenceVariables, $this->variableCount);
            $this->definitionVariables = $this->referenceVariables = null;

            try {
                if ($value instanceof ServiceClosureArgument) {
                    $value = $value->getValues()[0];
                    $code = $this->dumpValue($value, $interpolate);

                    if ($value instanceof TypedReference) {
                        $code = sprintf('$f = function (\\%s $v%s) { return $v; }; return $f(%s);', $value->getType(), ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $value->getInvalidBehavior() ? ' = null' : '', $code);
                    } else {
                        $code = sprintf('return %s;', $code);
                    }

                    return sprintf("function () {\n            %s\n        }", $code);
                }

                if ($value instanceof IteratorArgument) {
                    $operands = array(0);
                    $code = array();
                    $code[] = 'new RewindableGenerator(function () {';

                    if (!$values = $value->getValues()) {
                        $code[] = '            return new \EmptyIterator();';
                    } else {
                        $countCode = array();
                        $countCode[] = 'function () {';

                        foreach ($values as $k => $v) {
                            ($c = $this->getServiceConditionals($v)) ? $operands[] = "(int) ($c)" : ++$operands[0];
                            $v = $this->wrapServiceConditionals($v, sprintf("        yield %s => %s;\n", $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)));
                            foreach (explode("\n", $v) as $v) {
                                if ($v) {
                                    $code[] = '    '.$v;
                                }
                            }
                        }

                        $countCode[] = sprintf('            return %s;', implode(' + ', $operands));
                        $countCode[] = '        }';
                    }

                    $code[] = sprintf('        }, %s)', count($operands) > 1 ? implode("\n", $countCode) : $operands[0]);

                    return implode("\n", $code);
                }
            } finally {
                list($this->definitionVariables, $this->referenceVariables, $this->variableCount) = $scope;
            }
        } elseif ($value instanceof Definition) {
            if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) {
                return $this->dumpValue($this->definitionVariables[$value], $interpolate);
            }
            if ($value->getMethodCalls()) {
                throw new RuntimeException('Cannot dump definitions which have method calls.');
            }
            if ($value->getProperties()) {
                throw new RuntimeException('Cannot dump definitions which have properties.');
            }
            if (null !== $value->getConfigurator()) {
                throw new RuntimeException('Cannot dump definitions which have a configurator.');
            }

            $arguments = array();
            foreach ($value->getArguments() as $argument) {
                $arguments[] = $this->dumpValue($argument);
            }

            if (null !== $value->getFactory()) {
                $factory = $value->getFactory();

                if (is_string($factory)) {
                    return sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory)), implode(', ', $arguments));
                }

                if (is_array($factory)) {
                    if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $factory[1])) {
                        throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $factory[1] ?: 'n/a'));
                    }

                    $class = $this->dumpValue($factory[0]);
                    if (is_string($factory[0])) {
                        return sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $factory[1], implode(', ', $arguments));
                    }

                    if ($factory[0] instanceof Definition) {
                        if (0 === strpos($class, 'new ')) {
                            return sprintf('(%s)->%s(%s)', $class, $factory[1], implode(', ', $arguments));
                        }

                        return sprintf("\\call_user_func(array(%s, '%s')%s)", $class, $factory[1], count($arguments) > 0 ? ', '.implode(', ', $arguments) : '');
                    }

                    if ($factory[0] instanceof Reference) {
                        return sprintf('%s->%s(%s)', $class, $factory[1], implode(', ', $arguments));
                    }
                }

                throw new RuntimeException('Cannot dump definition because of invalid factory');
            }

            $class = $value->getClass();
            if (null === $class) {
                throw new RuntimeException('Cannot dump definitions which have no class nor factory.');
            }

            return sprintf('new %s(%s)', $this->dumpLiteralClass($this->dumpValue($class)), implode(', ', $arguments));
        } elseif ($value instanceof Variable) {
            return '$'.$value;
        } elseif ($value instanceof Reference) {
            $id = $this->container->normalizeId($value);
            if (null !== $this->referenceVariables && isset($this->referenceVariables[$id])) {
                return $this->dumpValue($this->referenceVariables[$id], $interpolate);
            }

            return $this->getServiceCall($id, $value);
        } elseif ($value instanceof Expression) {
            return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container'));
        } elseif ($value instanceof Parameter) {
            return $this->dumpParameter($value);
        } elseif (true === $interpolate && is_string($value)) {
            if (preg_match('/^%([^%]+)%$/', $value, $match)) {
                // we do this to deal with non string values (Boolean, integer, ...)
                // the preg_replace_callback converts them to strings
                return $this->dumpParameter($match[1]);
            } else {
                $replaceParameters = function ($match) {
                    return "'.".$this->dumpParameter($match[2]).".'";
                };

                $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, $this->export($value)));

                return $code;
            }
        } elseif (is_object($value) || is_resource($value)) {
            throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
        }

        return $this->export($value);
    }
103871
function(value)
	{
		if ( undefined == value || null == value )
			return 'null';	
		if ( value instanceof Date)
			return value.toISOString();
		if ( typeof(value) == 'object')
			return this.dumpObject(value);
		if ( typeof(value) == 'boolean' )
			return value ? 'true' : 'false';
		if ( /^\d+$/.test(value) )
			return typeof(value) == 'string' ? "'"+value+"'" : parseInt(value);
		if ( this.isNumeric(value) )
			return typeof(value) == 'string' ? "'"+value+"'" : parseFloat(value);
		if ( typeof(value) == 'number' )
			return value == Infinity ? '.Inf' : ( value == -Infinity ? '-.Inf' : ( isNaN(value) ? '.NAN' : value ) );
		var yaml = new YamlEscaper();
		if ( yaml.requiresDoubleQuoting(value) )
			return yaml.escapeWithDoubleQuotes(value);
		if ( yaml.requiresSingleQuoting(value) )
			return yaml.escapeWithSingleQuotes(value);
		if ( '' == value )
			return '""';
		if ( this.getTimestampRegex().test(value) )
			return "'"+value+"'";
		if ( this.inArray(value.toLowerCase(), ['null','~','true','false']) )
			return "'"+value+"'";
		// default
			return value;
	}
409746
function(scalar, i)
	{
		var matches = null;
		//var item = /^(.*?)['"]\s*(?:[,:]|[}\]]\s*,)/.exec((scalar+'').substring(i))[1];
		
		if ( !(matches = new RegExp('^'+YamlInline.REGEX_QUOTED_STRING).exec((scalar+'').substring(i))) )
		{
			throw new YamlParseException('Malformed inline YAML string ('+(scalar+'').substring(i)+').');
		}

		var output = matches[0].substr(1, matches[0].length - 2);
		
		var unescaper = new YamlUnescaper();

		if ( '"' == (scalar+'').charAt(i) )
		{
			output = unescaper.unescapeDoubleQuotedString(output);
		}
		else
		{
			output = unescaper.unescapeSingleQuotedString(output);
		}

		i += matches[0].length;

		this.i = i;
		return output;
	}
799497
protected function _outputXML($input) {
		$attributes = '';
		$output = '';
		
		// get attributes
		foreach ($input as $key => $value) {
			$attribute = [];

			if ($key[0] == $this->attribute_tag) {
				$newkey = substr($key, 1);
				foreach ($value as $pkey => $pvalue) {
					$attribute[] = $pkey.'="'.htmlspecialchars($pvalue).'"';
				}
				$attributes[$newkey] = implode(' ', $attribute);
				unset($input[$key]);
			}
		}

		// run through all keys
		foreach ($input as $key => $value) {
			// set attribs
			if (isset($attributes[$key])) $attr = ' '.$attributes[$key]; else $attr = '';

			// process numeric indices
			if (is_numeric($key)) $key = $this->numeric_prefix.$key;

			if (is_array($value) && count($value) > 0) {
				$body = $this -> _outputXML($value);
			} else {
				// process value
				if (is_array($value)) $value = '';
				elseif ($value === true) $value = 'true';
				elseif ($value === false) $value = 'false';
				elseif ($value === null) $value = 'null';
				else {
					$value = trim(stripslashes($value));

					if (strpos($value, '<') !== false OR strpos($value, '>') !== false OR strpos($value, '&') !== false) {
						$value = '<![CDATA['.$value.']]>';
					}
				}

				$body = $value;
			}

			// process equal named tags
			$key = explode($this->strip_tag, $key);
			$key = $key[0];

			// Start-Tag setzen
			if (!isset($output)) $output = '';
			$output .= '<'.$key.$attr.'>';
			$output .= $body;
			// End-Tag setzen
			$output .= '</'.$key.'>';
		}
		return $output;
	}
346131
public static function toHtmlEntity($input)
    {
        if(is_array($input)){
            foreach ($input as $key=>$value){
                $input[$key]=self::toHtmlEntity($value);
            }
        }else if(is_object($input)){
            $array=get_object_vars($input);
            foreach ($array as $key=>$value){
                $input->$key=self::toHtmlEntity($value);
            }
        }else{
            $input=htmlspecialchars($input);
        }

        return $input;
    }
405923
private function yamlize($key, $value, $indent, $previous_key = -1, $first_key = 0, $source_array = null)
    {
        if (is_array($value)) {
            if (empty ($value)) {
                return $this->dumpNode($key, array(), $indent, $previous_key, $first_key, $source_array);
            }
            // It has children.  What to do?
            // Make it the right kind of item
            $string = $this->dumpNode($key, self::REMPTY, $indent, $previous_key, $first_key, $source_array);
            // Add the indent
            $indent += $this->dumpIndent;
            // Yamlize the array
            $string .= $this->yamlizeArray($value,$indent);
        } elseif (!is_array($value)) {
            // It doesn't have children.  Yip.
            $string = $this->dumpNode($key, $value, $indent, $previous_key, $first_key, $source_array);
        }

        return $string;
    }