Parse a document template

@return  object  instance of $this to allow chaining
326904
protected function _parseTemplate()
	{
		$matches = array();

		if (preg_match_all('#<jdoc:include\ type="([^"]+)" (.*)\/>#iU', $this->_template, $matches))
		{
			$template_tags_first = array();
			$template_tags_last  = array();

			// Step through the jdocs in reverse order.
			for ($i = count($matches[0]) - 1; $i >= 0; $i--)
			{
				$type = $matches[1][$i];
				$attribs = empty($matches[2][$i]) ? array() : $this->parseAttributes($matches[2][$i]);
				$name = isset($attribs['name']) ? $attribs['name'] : null;

				// Separate buffers to be executed first and last
				if ($type == 'module' || $type == 'modules')
				{
					$template_tags_first[$matches[0][$i]] = array('type' => $type, 'name' => $name, 'attribs' => $attribs);
				}
				else
				{
					$template_tags_last[$matches[0][$i]]  = array('type' => $type, 'name' => $name, 'attribs' => $attribs);
				}
			}
			// Reverse the last array so the jdocs are in forward order.
			$template_tags_last = array_reverse($template_tags_last);

			$this->_template_tags = $template_tags_first + $template_tags_last;
		}

		return $this;
	}
1181906
final public function documentTitle()
    {
        $parts = $this->documentTitleParts();
        if (array_diff_key([ 'title' => true, 'site' => true ], $parts)) {
            throw new InvalidArgumentException(
                'The document title parts requires at least a "title" and a "site"'
            );
        }

        return $this->parseDocumentTitle($parts);
    }
1191887
public function normalizeTemplate($template)
	{
		$dom = TemplateLoader::load($template);

		// Apply all the normalizations until no more change is made or we've reached the maximum
		// number of loops
		$i = 0;
		do
		{
			$old = $template;
			foreach ($this->collection as $k => $normalization)
			{
				$normalization->normalize($dom->documentElement);
			}
			$template = TemplateLoader::save($dom);
		}
		while (++$i < $this->maxIterations && $template !== $old);

		return $template;
	}
11274
protected function parseTitle() {
    if (is_object($this->file)) {
      if (isset($this->file->title)) {
        return $this->file->title;
      }
    }

    if (is_array($this->file)) {
      if (isset($this->file['title'])) {
        return $this->file['title'];
      }
    }

    return '';
  }
1234781
public function toDocument()
    {
        $doc = new Document();
        $doc->data = $this->data;
        $doc->defaults = $this->defaultData;
        return $doc;
    }
797079
public function parse(){

		$docBlockList = $this->sanitize($this->block);

		foreach($docBlockList as $line){

			if(!empty($line)){

				if(empty($case))
					$case = "command";
				
				if(!empty($case) && in_array(strtolower($line), array(

					"usage:", 
					"arguments:", 
					"options:"

				))){

					$case = trim(strtolower($line),":");
					continue;
				}

				switch($case){

					case "command":

						list($cmdName, $cmdDescr) = explode(" ", $line, 2);

						$blockList["command"] = array(

							"alias"=>$cmdName, 
							"descr"=>$cmdDescr
						);

					break;
					case "usage":

						$parts = explode(" ", $line);
						$command = array_shift($parts);

						while($part = array_shift($parts)){

							if(preg_match("/^\[[-\w]+$/", $part)){

								$part = str_replace(array("["), "", $part);
								array_shift($parts);
								$blockList["usage"][$part] = array(

									"required"=>false, 
									"input"=>true
								);
							}							
							elseif(preg_match("/^\[[-\w]+\]$/", $part)){

								$part = str_replace(array("[","]"), "", $part);
								$blockList["usage"][$part] = array(

									"required"=>false, 
									"input"=>false
								);
							}							
							elseif(preg_match("/^(-|--)\w+$/", $part)){

								array_shift($parts);
								$blockList["usage"][$part] = array(

									"required"=>true, 
									"input"=>true
								);
							}							
							elseif(preg_match("/^<\w+>$/", $part)){

								$part = str_replace(array("<",">"), "", $part);
								$blockList["usage"][$part] = array(

									"required"=>true
								);
							}							
							elseif(preg_match("/^\[<\w+>\]$/", $part)){

								$part = str_replace(array("[","]","<",">"), "", $part);
								$blockList["usage"][$part] = array(

									"required"=>false
								);
							}
						}

					break;
					case "arguments":

						list($argument, $descr) = explode(" ", $line, 2);

						$blockList["arguments"][$argument]["descr"] = $descr;
						$blockList["arguments"][$argument]["optional"] = (strpos($line, "optional") !== false);

					break;
					case "options":

						$parts = explode(" ", $line, 3);

						$hasAlias=false;
						if(count($parts) == 3){

							$hasAlias = preg_match("/^-\w$/", next($parts));
							if($hasAlias)
								list($option, $alias, $descr) = $parts;

							if(!$hasAlias)
								list($option, $input, $descr) = $parts;
						}
							
						if(count($parts) == 2)
							list($option, $input) = $parts;

						$details["descr"] = @$descr;

						if($hasAlias){

							$details["alias"] = $alias;
							$blockList["aliases"][$alias] = $option;
						}

						$blockList["options"][$option] = $details;

					break;	
				}
			}
		}

		return $blockList;
	}
792968
protected function parse()
    {
        $data = $this->_source->getData();

        $prefilters = $this->getPreFilterInstances();
        foreach($prefilters as $prefilter) {
            $data = $prefilter->filter($data);
        }

        $realpath = $this->_source->getRealPath();
        $parser = new PHPTAL_Dom_SaxXmlParser($this->_encoding);

        $builder = new PHPTAL_Dom_PHPTALDocumentBuilder();
        $tree = $parser->parseString($builder, $data, $realpath)->getResult();

        foreach($prefilters as $prefilter) {
            if ($prefilter instanceof PHPTAL_PreFilter) {
                if ($prefilter->filterDOM($tree) !== NULL) {
                    throw new PHPTAL_ConfigurationException("Don't return value from filterDOM()");
                }
            }
        }

        $state = new PHPTAL_Php_State($this);

        $codewriter = new PHPTAL_Php_CodeWriter($state);
        $codewriter->doTemplateFile($this->getFunctionName(), $tree);

        return $codewriter->getResult();
    }
1229927
public function parseDocument(\DOMDocument $document)
    {
        $doc = $this->extensions->parseDocument($document);
        if ($doc) {
            return $doc;
        }

        throw new \InvalidArgumentException(
            sprintf('Unexpected root element "%s"', $document->documentElement->localName)
        );
    }
186002
public function parse()
    {
        if (!is_file($this->file)) {
            throw new \Exception(sprintf(
                'Template "%s" file doesn\'t exist!', $this->file
            ));
        }

        $fp = fopen($this->file, 'r');

        $lineCount       = 0;
        $nextToken       = '';
        $block           = '';
        $currentValue    = '';
        $stringComposing = false;
        $skipMultilineComment = false;

        while (($line = fgets($fp)) !== false) {
            $lineCount++;

            if ($stringComposing) {
                if (substr(ltrim($line), 0, 3) === '>>>') {
                    $this->blocks[$block][$name] = trim($value);
                    //$block = '';
                    $value = '';
                    $stringComposing = false;
                } else {
                    // $line = trim($line);
//                     if (substr($value, -1) != '>' && ! empty($line)) {
//                         $line = " " . $line;
//                     }

                    //$value .= substr($value, -1) == '>' ? trim($line) : " " . trim($line);
                    $value .= $line;
                }

                continue;
            }

            $line = trim($line);

            if (substr($line, 0, 1) === '#' || $line === '' || substr($line, 0, 2) === '//') {
                continue; // skip single comments or empty lines
            } elseif (substr($line, 0, 2) === '/*') { // start multiline comment
                if (strpos($line, '*/') === false) {
                    $skipMultilineComment = true; // activate multiline comments skipping
                } else {
                    continue; // just skip this line, it has the form: /* ... */
                }
            } elseif (strpos($line, '*/') !== false) { // end multiline comment
                $skipMultilineComment = false;
                continue; // just skip the end multiline comment
            }

            if ($skipMultilineComment) {
                continue; //skip multiline comments segment
            }

            $kwPattern = '^@(?<keyword>\w+)';

            if (! preg_match('/'.$kwPattern.'.*/', $line, $matches)) {
                throw new \Exception(sprintf(
                    'Parse Error: Unknow keyword, lines must starts with a valid keyword, near: %s, on line %s',
                    $line, $lineCount
                ));
            }
            //var_dump($matches);
            $keyword = $matches['keyword'];

            switch ($keyword) {
                case Parser::T_DEF:
                    $pattern = '/'.$kwPattern.'\s+(?<type>[\w]+)\s+(?<name>[\w.]+)\s+(?<value>.+)/';

                    if (!preg_match($pattern, $line, $matches)) {
                        throw new \Exception(sprintf(
                            "Syntax Error: near: '%s', on line %s.\n" .
                            "Syntax should be: @def <type> <name> <value>",
                            $line, $lineCount
                        ));
                    }

                    $keyword = $matches['keyword'];
                    $type    = $matches['type'];
                    $name    = $matches['name'];
                    $value   = $matches['value'];

                    $tmp     = explode('.', $name);
                    $defName = $tmp[0];
                    $defProp = isset($tmp[1]) ? $tmp[1] : '';

                    switch ($type) {
                        case Parser::T_GLOBAL:
                        case Parser::T_ITERATOR:
                        case Parser::T_SETCONF:
                            if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                                $value = trim($value, '"');
                            } elseif (substr($value, 0, 1) == "'" && substr($value, -1) == "'") {
                                $value = trim($value, "'");
                            }

                            if ($value === '\n' || $value === '\r\n') {
                                $value = "\n";
                            }

                            $value = self::castValue($value);

                            if (empty($defProp)) {
                                $this->defs[$type][$defName] = $value;
                            } else {
                                $this->defs[$type][$defName][$defProp] = $value;
                            }
                            break;
                        default:
                            throw new \Exception(sprintf(
                                'Parse Error: unknow definition type: "%s" on line %s.', $type, $lineCount
                            ));
                    }
                    break;
                case Parser::T_BLOCK:
                    $pattern = '/'.$kwPattern.'\s+(?<block>[\w]+)/';

                    if (!preg_match($pattern, $line, $matches)) {
                        throw new Exception(sprintf(
                            "Parse Error: Syntax error near: %s, on line %s.\n." .
                            "Syntax should be: @def <type> <name> <value>",
                            substr($line, 0, 20).'...', $lineCount
                        ));
                    }
                    //var_dump($matches);

                    $block = $matches['block'];

                    if (!empty($nextToken)) {
                        throw new \Exception(sprintf(
                            'Parse Error: expected: @"%s", given: @"%s"', $nextToken, Parser::T_BLOCK
                        ));
                    }

                    $nextToken = Parser::T_END;
                    break;
                case Parser::T_END:
                    if (empty($nextToken)) {
                        throw new \Exception(sprintf(
                            'Parse Error: close keyword: @"%s" given, but any block was started.', Parser::T_BLOCK
                        ));
                    }

                    if ($nextToken !== Parser::T_END) {
                        throw new \Exception(sprintf(
                            'Parse Error: expected: @"%s", given: @"%s"', $nextToken, Parser::T_END
                        ));
                    }

                    $nextToken = '';
                    break;
                case Parser::T_VAR:
                    $pattern = '/'.$kwPattern.'\s+(?<name>[\w]+)\s+(?<value>.+)/';

                    if (!preg_match($pattern, $line, $matches)) {
                        throw new Exception(sprintf(
                            "Parse Error: Syntax error near: %s, on line %s.\n." .
                            "Syntax should be: @var <name> <value>\n or \n" .
                            "@var <name> <<<\nsome large string\nmultiline...\n>>>\n\n",
                            substr($line, 0, 20).'...', $lineCount
                        ));
                    }
                    //print_r($matches);
                    $keyword = $matches['keyword'];
                    $name    = $matches['name'];
                    $value   = $matches['value'];

                    if (substr($value, 0, 3) === '<<<' && $value !== '<<<') {
                        throw new \Exception(sprintf(
                            "Syntax Error: multiline string must starts on new line after open braces <<<\n" .
                            "near: '%s', on line %s", $line, $lineCount
                        ));
                    }

                    if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
                        $value = trim($value, '"');
                    } elseif (substr($value, 0, 1) == "'" && substr($value, -1) == "'") {
                        $value = trim($value, "'");
                    }

                    if ($value !== '<<<') {
                        $this->blocks[$block][$name] = self::castValue($value);
                    } else {
                        $value = '';
                        $stringComposing = true;
                    }
                    break;
                default:
                    throw new \Exception(sprintf(
                        'Parse Error: Unknown definition type: %s, on line %s', $type, $lineCount
                    ));
            }

        }

        if ($stringComposing) {
            throw new \Exception(sprintf(
                "Parse Error: Multiline string closing braces are missing '>>>',\nfor @block: '%s', @var: '%s' " .
                "until end of file.", $block, $name
            ));
        }
    }
1130357
protected function _parseExtend() {
        foreach (Template::$_extends as $extend) {
            $this->_content = $extend['class']::$extend['method']($this->_content);
        }

        foreach (Config::instance()->config['user']['template'] as $extend) {
            $this->_content = $extend['class']::$extend['method']($this->_content);
        }
    }
665090
public function parse(){
		if($this->hasCircularReferences($this))
			throw new RuntimeException('Circular reference found in the query tree, cannot parse the query.');

		$this->connection->connect();

		$parser = $this->connection->getParser();
		$instance = new $parser($this);
		return $instance->parse();
	}
87742
protected function parseContent()
    {
        $flatContent = implode($this->content);

        try {
            $parser = $this->getParser();
            $this->syntaxTree = $parser->parse($flatContent);
        } catch (Error $e) {
            throw new Exception('Error on parsing '.$this->classShortName." class\n".$e->getMessage());
        }

        return $this;
    }
874630
protected function parse()
	{
		if (($s = $this->copy_until_char('<'))==='')
		{
			return $this->read_tag();
		}

		// text
		$node = new Node($this);
		++$this->cursor;
		$node->_[self::HDOM_INFO_TEXT] = $s;
		$this->link_nodes($node, false);
		return true;
	}
599291
protected function parseArguments()
    {
        $stream = $this->parser->getStream();

        $data = null;
        $only = false;

        if ($stream->test(Twig_Token::BLOCK_END_TYPE)) {
            $stream->expect(Twig_Token::BLOCK_END_TYPE);

            return [$data, $only];
        }

        if ($stream->test(Twig_Token::NAME_TYPE, 'only')) {
            $only = true;
            $stream->next();
            $stream->expect(Twig_Token::BLOCK_END_TYPE);

            return [$data, $only];
        }

        $data = $this->parser->getExpressionParser()->parseExpression();

        if ($stream->test(Twig_Token::NAME_TYPE, 'only')) {
            $only = true;
            $stream->next();
        }

        $stream->expect(Twig_Token::BLOCK_END_TYPE);

        return [$data, $only];
    }
1189764
protected function parse()
	{
		$inside = false;
		$doc_open	= false;
		$func_data	= array();

		$f = new FS_File_Reader( $this->fileName );
		$lines = $f->readArray();
		array_pop( $lines );
		array_shift( $lines ); 
		foreach( $lines as $line )
		{
			$line = trim( $line );
			$line = str_replace( array( "*", "\t\t", "\t\t" ), array( "#", "\t", "\t" ), $line );
			if( $inside )
			{
				if( !$doc_open )
				{
					if( ereg( $this->patterns['doc_start'], $line ) )
						$doc_open = true;
					else if( ereg( $this->patterns["method"], $line ) )
					{
						$parts = explode( "function", $line );
						$method = substr( $parts[1], 0, strpos($parts[1], "(" ) );
						$method = str_replace( "&", "", $method );
						$method = trim( $method );
						$this->methods[$method] = $func_data;
						$func_data = array();
					}
				}
				if( $doc_open )
				{
					$found_pattern = false;
					if( ereg( $this->patterns["doc_data"], $line ) )
					{
						foreach( $this->methodProperties as $prop => $pattern )
						{
							if( ereg( $this->patterns[$pattern], $line ) )
							{
								$found_pattern = true;
								$func_data[$prop] = $this->getValueOfDocLine( $line, $pattern );
							}
						}
						if( ereg( $this->patterns["d_param"], $line ) )
						{
							$parts = explode( $this->patterns["d_param"], $line );
							$parts = explode( "\t", trim($parts[1] ) );
							$func_data["param"][$parts[1]]['type'] = $parts[0];
							if( isset( $parts[2] ) )
								$func_data["param"][$parts[1]]['desc'] = $parts[2];
						}
						else if( !$found_pattern && !ereg( $this->patterns['doc_end'], $line ) )
						{
							$desc = ereg_replace( $this->patterns["doc_data"], "", $line );
							$desc = trim( $desc );
							if( $desc )
								$func_data["desc"][] = $desc;
						}
					}
					else	if( ereg( $this->patterns["d_var"], $line ) )
					{
						$parts = explode( $this->patterns["d_var"], $line );
						$parts = preg_split( "@\t+@", trim($parts[1] ) );
						$this->vars[$parts[1]]['type'] = $parts[0];
						$access = ( substr($parts[1], 0, 1) == "_" ) ? "private" : "public";
							$this->vars[$parts[1]]['access'] = $access;
						$this->vars[$parts[1]]['desc'][] = str_replace( array( "#", "/" ), "", $parts[2] );
					}
					if( ereg( $this->patterns['doc_end'], $line ) )
						$doc_open = false;
				}
			}
			else
			{
				if( eregi( $this->patterns["import"], $line ) )
				{
					$import = str_replace( array( "import", " ", "(", ")", ";", "'", '"' ), "", $line );
					$parts = explode( ".", $import );
					$this->imports[$parts[count( $parts )-1]] = implode( "/", $parts );
				}
				else if( eregi( $this->patterns["class"], $line ) )
				{
					$line	= preg_replace( "@".$this->patterns["class"]."@i", "", $line );
					$parts = explode( " extends ", $line );
					$class = explode( " implements ", $parts[0] );
					$class = $class[0];
					
//					$class = str_replace( array( "class", " " ), "", $class );
					$this->classData["class"] = $class;
					if( isset( $parts[1] ) )
						$this->classData["extends"] = $parts[1];
					$inside = true;
				}
				else if( !$doc_open )
				{
					if( ereg( $this->patterns['doc_start'], $line ) )
						$doc_open = true;
				}
				else if( $doc_open )
				{
					if( ereg( $this->patterns['doc_end'], $line ) )
						$doc_open = false;
					else
					{
						if( ereg( $this->patterns["doc_data"], $line ) )
						{
							$found_pattern = false;
							foreach( $this->classProperties as $prop => $pattern )
							{
								if( ereg( $this->patterns[$pattern], $line ) )
								{
									$found_pattern = true;
									$this->classData[$prop][] = $this->getValueOfDocLine( $line, $pattern );
								}
							}
							if( !$found_pattern && !ereg( $this->patterns['doc_end'], $line ) )
							{
								if( ereg( $this->patterns['d_uses'], $line ) )
								{
									$parts = explode( $this->patterns["d_uses"], $line );
									$uses = trim( $parts[1] );
									if( !in_array ( $uses, $this->classData["uses"] ) )
										$this->classData["uses"][] = $uses; 
								}
								else if( ereg( $this->patterns['d_todo'], $line ) )
								{
									$parts = explode( $this->patterns["d_todo"], $line );
									$todo = trim( $parts[1] );
									if( !in_array( $todo, $this->classData["todo"] ) )
										$this->classData["todo"][] = $todo; 
								}
								else
								{
									$desc = ereg_replace( $this->patterns["doc_data"], "", $line );
									$desc = trim( $desc );
									if( $desc && !in_array( $desc, $this->classData["desc"] ) )
										$this->classData["desc"][] = $desc;
								}
							}
						}
					}	
				}
			}
		}
		foreach( $this->classProperties as $prop => $pattern )
			if( isset( $this->classData[$prop] ) && is_array( $this->classData[$prop] ) )
				$this->classData[$prop]	= array_unique( $this->classData[$prop] );
	}
278211
public function template() {

		if ( is_null( $this->template ) ) {
			$this->template = $this->locate();
		}

		return $this->template;
	}
562341
public function parse()
    {
        $this->docblockObj = new Docblock();

        $this->ignoreSpaces = false;
        $this->ignoreStar = true;
        $this->commentOpen = false;
        $this->annotationNameOpen = false;
        $this->annotationOpen = false;
        $this->summaryOpen = true;
        $this->descriptionOpen = false;

        $this->currentAnnotationStr = null;
        $this->currentAnnotationContentStr = null;

        $this->summaryStr = '';
        $this->descriptionStr = '';

        $this->currentLine = 0;
        $this->currentCharIndex = 0;
        $this->annotationLen = \strlen($this->annotation);
        $this->currentChar = $this->annotation[0];

        while (null !== $this->currentChar) {
            $currentChar = $this->currentChar;

            if ($this->ignoreSpaces && ctype_space($currentChar)) {
            } else {
                if (!$this->commentOpen) {
                    if ('/' == $currentChar) {
                        if ('*' == $this->nextCharacter() && '*' == $this->nextCharacter()) {
                            $this->commentOpen = true;
                        } else {
                            continue;
                        }
                    }
                } else {
                    if ('*' == $currentChar) {
                        $nextCharacter = $this->nextCharacter();
                        if ('/' == $nextCharacter) {
                            // stop annotation parsing on end of comment
                            $this->__tryRegisterAnnotation();
                            break;
                        } elseif ($this->ignoreStar) {
                            if (' ' == $nextCharacter) {
                                $this->nextCharacter();
                            }
                            continue;
                        }
                    }

                    if ('@' == $currentChar) {
                        $this->descriptionStr = trim($this->descriptionStr);
                        if ($this->descriptionOpen && \strlen($this->descriptionStr) > 0) {
                            $this->descriptionOpen = false;
                        }

                        $this->currentAnnotationStr = '';
                        $this->currentAnnotationContentStr = '';

                        $this->ignoreSpaces = false;
                        $this->annotationNameOpen = true;
                    } elseif ($this->annotationNameOpen || $this->annotationOpen) {
                        // stop annotation parsing on new line
                        if ("\n" == $currentChar || "\r" == $currentChar) {
                            $this->__tryRegisterAnnotation();

                            $this->ignoreSpaces = false;
                            $this->ignoreStar = true;
                        } elseif ($this->annotationNameOpen) {
                            if (ctype_space($currentChar)) {
                                $this->annotationNameOpen = false;
                                $this->annotationOpen = true;
                            } else {
                                $this->currentAnnotationStr .= $currentChar;
                            }
                        } elseif ($this->annotationOpen) {
                            $this->currentAnnotationContentStr .= $currentChar;
                        }
                    } elseif ($this->summaryOpen) {
                        // stop summary on new line
                        if (\strlen($this->summaryStr) > 0 && ("\n" == $currentChar || "\r" == $currentChar)) {
                            $this->summaryOpen = false;
                            $this->descriptionOpen = true;
                            $this->ignoreStar = true;
                        } else {
                            $this->summaryStr .= $currentChar;
                        }
                    } elseif ($this->descriptionOpen) {
                        // stop description on new line
                        if ("\n" == $currentChar || "\r" == $currentChar) {
                            $this->descriptionStr .= PHP_EOL;
                        } else {
                            $this->descriptionStr .= $currentChar;
                        }
                    }
                }
            }

            $this->nextCharacter();
        }

        $this->docblockObj->setSummary(trim($this->summaryStr));
        $this->docblockObj->setDescription(trim($this->descriptionStr));

        return $this->docblockObj;
    }