Parses the conversion pattern string, converts it to a chain of pattern
converters and returns the first converter in the chain.

@return \n2n\log4php\pattern\PatternConverter
434827
public function parse() {
		
		// Skip parsing if the pattern is empty
		if (empty($this->pattern)) {
			$this->addLiteral('');
			return $this->head;
		}
		
		// Find all conversion words in the conversion pattern
		$count = preg_match_all($this->regex, $this->pattern, $matches, PREG_OFFSET_CAPTURE);
		if ($count === false) {
			$error = error_get_last();
			throw new \n2n\log4php\LoggerException("Failed parsing layotut pattern: {$error['message']}");
		}
		
		$prevEnd = 0;
		
		foreach($matches[0] as $key => $item) {
			
			// Locate where the conversion command starts and ends
			$length = strlen($item[0]);
			$start = $item[1];
			$end = $item[1] + $length;
		
			// Find any literal expressions between matched commands
			if ($start > $prevEnd) {
				$literal = substr($this->pattern, $prevEnd, $start - $prevEnd);
				$this->addLiteral($literal);
			}
			
			// Extract the data from the matched command
			$word = !empty($matches['word'][$key]) ? $matches['word'][$key][0] : null;
			$modifiers = !empty($matches['modifiers'][$key]) ? $matches['modifiers'][$key][0] : null;
			$option = !empty($matches['option'][$key]) ? $matches['option'][$key][0] : null;
			
			// Create a converter and add it to the chain
			$this->addConverter($word, $modifiers, $option);
			
			$prevEnd = $end;
		}

		// Add any trailing literals
		if ($end < strlen($this->pattern)) {
			$literal = substr($this->pattern, $end);
			$this->addLiteral($literal);
		}
		
		return $this->head;
	}
579228
protected function convert(/*# string */ $pattern)/*# : array */
    {
        $ph = sprintf("\{%s(?:%s)?\}", self::MATCH_GROUP_NAME, self::MATCH_GROUP_TYPE);

        // count placeholders
        $map = $m = [];
        if (preg_match_all('~'. $ph .'~x', $pattern, $m)) {
            $map = $m[1];
        }

        $result = preg_replace(
            [
            '~' . $ph . '(*SKIP)(*FAIL) | \[~x', '~' . $ph . '(*SKIP)(*FAIL) | \]~x',
            '~\{' . self::MATCH_GROUP_NAME . '\}~x', '~' . $ph . '~x',
            ],
            ['(?:', ')?', '{\\1:' . self::MATCH_SEGMENT . '}', '(\\2)'],
            strtr('/' . trim($pattern, '/'), $this->shortcuts)
        );

        return [$result, $map];
    }
528600
protected function getDefaultPattern()
    {
        $patternParts = [];
        if (self::NONE !== $this->datetype) {
            $patternParts[] = $this->defaultDateFormats[$this->datetype];
        }
        if (self::NONE !== $this->timetype) {
            $patternParts[] = $this->defaultTimeFormats[$this->timetype];
        }

        return implode(', ', $patternParts);
    }
1150117
public function pattern()
    {
        $patterns = func_get_args();

        foreach (func_get_args() as $pattern) {
            $this->patterns[] = $this->pattern_to_regex($pattern);
        }

        return $this;
    }
877979
public function toSixFigureString()
	{
		$hundredkmE = floor($this->easting / 100000);
		$hundredkmN = floor($this->northing / 100000);

		if ($hundredkmN < 5) {
			$firstLetter = ($hundredkmE < 5) ? 'S' : 'T';
		} else if ($hundredkmN < 10) {
			$firstLetter = ($hundredkmE < 5) ? 'N' : 'O';
		} else {
			$firstLetter = 'H';
		}

		$index = 65 + ((4 - ($hundredkmN % 5)) * 5) + ($hundredkmE % 5);
		$ti = $index;
		if ($index >= 73) {
			$index++;
		}

		$secondLetter = chr($index);

		$e = round(($this->easting - (100000 * $hundredkmE)) / 100);
		$n = round(($this->northing - (100000 * $hundredkmN)) / 100);

		return sprintf('%s%s%03d%03d', $firstLetter, $secondLetter, $e, $n);
	}
33687
public function parseType()
    {
        if ( ! $this->type ) {
            $this->stream->resetPointer();

            switch ( $this->stream->read(2) ) {
                case "BM":
                    return $this->type = 'bmp';
                case "GI":
                    return $this->type = 'gif';
                case chr(0xFF) . chr(0xd8):
                    return $this->type = 'jpeg';
                case "\0\0":
                    switch ( $this->readByte($this->stream->peek(1)) ) {
                        case 1:
                            return $this->type = 'ico';
                        case 2:
                            return $this->type = 'cur';
                    }

                    return false;

                case chr(0x89) . 'P':
                    return $this->type = 'png';
                case "RI":
                    if ( substr($this->stream->read(10), 6, 4) == 'WEBP' ) {
                        return $this->type = 'webp';
                    }

                    return false;
                case'8B':
                    return $this->type = 'psd';
                case "II":
                case "MM":
                    return $this->type = 'tiff';
                default:
                    $this->stream->resetPointer();

                    // Keep reading bytes until we find '<svg'.
                    while ( true ) {
                        $byte = $this->stream->read( 1 );
                        if ( '<' === $byte && 'svg' === $this->stream->peek( 3 ) ) {
                            $this->type = 'svg';
                            return $this->type;
                        }
                    }
                    return false;
            }
        }

        return $this->type;
    }
88125
public function parse()
	{
		$strBuffer = parent::parse();

		if (TL_MODE == 'BE')
		{
			$strBuffer = '<div class="tl_ce ' . $this->strTemplate . '">' . $strBuffer . '</div>';
		}
		
		return $strBuffer;
	}
341626
public function toString()
    {
        $one = $this->one->toString();
        $other = $this->other->toString();

        if ($this->one instanceof AbstractTypeConstraint) {
            $one = $this->one->isUnion() ? sprintf('(%s)', $one) : $one;
        }

        if ($this->other instanceof AbstractTypeConstraint) {
            $other = $this->other->isUnion() ? sprintf('(%s)', $other) : $other;
        }

        return sprintf('%s|%s', $one, $other);
    }
964521
public function parse() {
		$annotations = [];
		preg_match_all(self::ANNOTATION_PATTERN, $this->rawDocComment, $found);
		foreach ($found[1] as $key => $value) {
			$arg = null;
			if (!empty($found[2][$key])) {
				$arg = substr(trim($found[2][$key]), 1, -1);
			}
			$annotations[] = new Annotation($value, $this->parseValue($found[3][$key]), $arg);
		}
		return $annotations;
	}
289268
protected function parsePyString()
    {
        $token = $this->expectTokenType('PyStringOp');

        $line = $token['line'];

        $strings = array();
        while ('PyStringOp' !== ($predicted = $this->predictTokenType()) && 'Text' === $predicted) {
            $token = $this->expectTokenType('Text');

            $strings[] = $token['value'];
        }

        $this->expectTokenType('PyStringOp');

        return new PyStringNode($strings, $line);
    }
970268
protected function compile()
	{
		if ($this->compiled !== false)
		{
			return $this->compiled;
		}

		if ($this->isStatic())
		{
			$this->compiled = '~^'.$this->pattern.'$~';
			return $this->compiled;
		}

		$compiled = $this->pattern;
		foreach ($this->getSegments($compiled) as $segment)
		{
			$compiled = \str_replace($segment['token'], $segment['regex'], $compiled);
		}

		$this->compiled = "~^{$compiled}$~";
		return $this->compiled;
	}
1270046
public function parse()
    {
        // Validate user based regex
        try {
            preg_match(
                config("{$this->configBase}.parser.file_regex"),
                '',
                $matches
            );

        } catch (\Exception $e) {
            $this->warningCount++;

            return $this->failed('Configuration error in the regular expression');
        }

        foreach ($this->parsedMail->getAttachments() as $attachment) {
            if (strpos($attachment->filename, '.zip') !== false
                && ($attachment->contentType == 'application/octet-stream'
                        || $attachment->contentType == 'application/zip'
                )
            ) {
                $zip = new Zipper;

                if (!$this->createWorkingDir()) {
                    return $this->failed(
                        "Unable to create working directory"
                    );
                }

                file_put_contents($this->tempPath . $attachment->filename, $attachment->getContent());

                $zip->zip($this->tempPath . $attachment->filename);
                $zip->extractTo($this->tempPath);

                foreach ($zip->listFiles() as $index => $compressedFile) {
                    if (strpos($compressedFile, '.csv') !== false) {
                        // For each CSV file we find, we are going to do magic (however they usually only send 1 zip)
                        if (preg_match(
                            config("{$this->configBase}.parser.file_regex"),
                            $compressedFile,
                            $matches
                        )) {
                            $this->feedName = $matches[1];

                            // If feed is known and enabled, validate data and save report
                            if ($this->isKnownFeed() && $this->isEnabledFeed()) {
                                $csvReports = new Reader\CsvReader(
                                    new SplFileObject($this->tempPath . $compressedFile)
                                );
                                $csvReports->setHeaderRowNumber(0);

                                foreach ($csvReports as $report) {

                                    // Handle field mappings first
                                    $aliasses = config("{$this->configBase}.feeds.{$this->feedName}.aliasses");
                                    if (is_array($aliasses)) {
                                        foreach ($aliasses as
                                                 $alias => $real) {
                                            if (array_key_exists($alias, $report)) {
                                                $report[$real] = $report[$alias];
                                                unset($report[$alias]);
                                            }
                                        }
                                    }
                                    /*
                                     * Emergency fix for major false positives from shadowserver feed
                                     * This only happens under very specific conditions and will be filtered out
                                     * as specific as possible.
                                     */
                                    if ($this->feedName == 'spam_url') {
                                        $urlFilter = '/([a-zA-Z]{3,5}.[a-zA-Z]{3,5}.com)/';
                                        if( $report['src_geo'] == 'RU' &&
                                            $report['url'] == "http://{$report['host']}" &&
                                            $report['src_asn'] == "8402" &&
                                            preg_match($urlFilter, $report['host'], $filterMatches)
                                        ) {
                                            continue;
                                        }
                                    }

                                    /*
                                     * Legacy 3.x fix for migrations.
                                     *
                                     * This resolves shadowserver errors where the CSV was send in duplicate resulting
                                     * in the header fields being used as data. If the header is detected the row can
                                     * be skipped safely
                                     */
                                    if ($report['ip'] === 'ip') {
                                        continue;
                                    }

                                    // Sanity check
                                    if ($this->hasRequiredFields($report) === true) {
                                        // incident has all requirements met, filter and add!
                                        $report = $this->applyFilters($report);

                                        $incident = new Incident();
                                        $incident->source      = config("{$this->configBase}.parser.name");
                                        $incident->source_id   = false;
                                        $incident->ip          = $report['ip'];
                                        $incident->domain      = false;
                                        $incident->class       =
                                            config("{$this->configBase}.feeds.{$this->feedName}.class");
                                        $incident->type        =
                                            config("{$this->configBase}.feeds.{$this->feedName}.type");
                                        $incident->timestamp   = strtotime($report['timestamp']);
                                        $incident->information = json_encode($report);

                                        // some rows have a domain, which is an optional column we want to register
                                        switch ($this->feedName) {
                                            case "spam_url":
                                                if (isset($report['url'])) {
                                                    $incident->domain = getDomain($report['url']);
                                                }
                                                break;
                                            case "ssl_scan":
                                                if (isset($report['subject_common_name'])) {

                                                    /*
                                                     * Common name does not add http://, but that is required for
                                                     * the domain helper check so lets add it manually
                                                     */
                                                    $testurl = "http://{$report['subject_common_name']}";

                                                    $incident->domain = getDomain($testurl);
                                                }
                                                break;
                                            case "compromised_website":
                                                if (isset($report['http_host'])) {
                                                    $incident->domain = getDomain($report['http_host']);
                                                }
                                                break;
                                        }

                                        $this->incidents[] = $incident;

                                    } //End hasRequired fields
                                } // End foreach report loop
                            } // End isKnown & isEnabled
                        } else { // Pregmatch failed to get feedName from attachment
                            $this->warningCount++;
                        }
                    } else { // Attached file is not a CSV within a ZIP file
                        $this->warningCount++;
                    }
                } // End each file in ZIP attachment loop
            } // End if not a ZIP attachment
        } // End foreach attachment loop

        return $this->success();
    }
316296
protected function parseStringLiteral()
    {
        switch ($this->type) {
            case 'T_DOUBLE_QUOTED_STRING':
                return new AST\StringLiteral(\str_replace('\\"', '\\', \substr($this->consume(), 1, -1)));
            case 'T_SINGLE_QUOTED_STRING':
                return new AST\StringLiteral(\str_replace("\\'", '\\', \substr($this->consume(), 1, -1)));
        }
        
        return $this;
    }
873954
private function parse()
    {
        $this->parameters   = [];
        $this->pathSegments = [];
        $parsedUrl          = parse_url($this->returnValue);
        foreach ($parsedUrl as $key => $value) {
            if ($key == 'query') {
                parse_str($value, $this->parameters);
            } elseif ($key == 'path') {
                $this->pathSegments = ($value) ? explode('/', ltrim($value, '/')) : [];
            } else {
                $this->{$key} = $value;
            }
        }
        return $this;
    }
1211493
public function parse() {
    $value = $this->getRawValue();
    $matches = [];
    if (is_array($value)) {
      return $value;
    }

    if (preg_match(self::NESTED_CONFIGURATION_REGEX, $value, $matches) === 1) {
      return $this->parseNestedValue($value, $matches);
    } else {
      return $this->parser->parseIntelligent($value);
    }
  }
1288909
protected function generateNumeric()
    {
        if (is_null($this->size) && $this->pattern == static::DEFAULT_PATTERN) {
            return $this->generateInteger();
        }

        return $this->generateString($this->getNumericGenerator());
    }
425762
public function parse()
	{
		if ($this->compressed_size >= $this->min_compressed_size)
		{
			// Check ID1, ID2, and CM
			if (substr($this->compressed_data, 0, 3) !== "\x1F\x8B\x08")
			{
				return false;
			}

			// Get the FLG (FLaGs)
			$this->flags = ord($this->compressed_data[3]);

			// FLG bits above (1 << 4) are reserved
			if ($this->flags > 0x1F)
			{
				return false;
			}

			// Advance the pointer after the above
			$this->position += 4;

			// MTIME
			$mtime = substr($this->compressed_data, $this->position, 4);
			// Reverse the string if we're on a big-endian arch because l is the only signed long and is machine endianness
			if (current(unpack('S', "\x00\x01")) === 1)
			{
				$mtime = strrev($mtime);
			}
			$this->MTIME = current(unpack('l', $mtime));
			$this->position += 4;

			// Get the XFL (eXtra FLags)
			$this->XFL = ord($this->compressed_data[$this->position++]);

			// Get the OS (Operating System)
			$this->OS = ord($this->compressed_data[$this->position++]);

			// Parse the FEXTRA
			if ($this->flags & 4)
			{
				// Read subfield IDs
				$this->SI1 = $this->compressed_data[$this->position++];
				$this->SI2 = $this->compressed_data[$this->position++];

				// SI2 set to zero is reserved for future use
				if ($this->SI2 === "\x00")
				{
					return false;
				}

				// Get the length of the extra field
				$len = current(unpack('v', substr($this->compressed_data, $this->position, 2)));
				$this->position += 2;

				// Check the length of the string is still valid
				$this->min_compressed_size += $len + 4;
				if ($this->compressed_size >= $this->min_compressed_size)
				{
					// Set the extra field to the given data
					$this->extra_field = substr($this->compressed_data, $this->position, $len);
					$this->position += $len;
				}
				else
				{
					return false;
				}
			}

			// Parse the FNAME
			if ($this->flags & 8)
			{
				// Get the length of the filename
				$len = strcspn($this->compressed_data, "\x00", $this->position);

				// Check the length of the string is still valid
				$this->min_compressed_size += $len + 1;
				if ($this->compressed_size >= $this->min_compressed_size)
				{
					// Set the original filename to the given string
					$this->filename = substr($this->compressed_data, $this->position, $len);
					$this->position += $len + 1;
				}
				else
				{
					return false;
				}
			}

			// Parse the FCOMMENT
			if ($this->flags & 16)
			{
				// Get the length of the comment
				$len = strcspn($this->compressed_data, "\x00", $this->position);

				// Check the length of the string is still valid
				$this->min_compressed_size += $len + 1;
				if ($this->compressed_size >= $this->min_compressed_size)
				{
					// Set the original comment to the given string
					$this->comment = substr($this->compressed_data, $this->position, $len);
					$this->position += $len + 1;
				}
				else
				{
					return false;
				}
			}

			// Parse the FHCRC
			if ($this->flags & 2)
			{
				// Check the length of the string is still valid
				$this->min_compressed_size += $len + 2;
				if ($this->compressed_size >= $this->min_compressed_size)
				{
					// Read the CRC
					$crc = current(unpack('v', substr($this->compressed_data, $this->position, 2)));

					// Check the CRC matches
					if ((crc32(substr($this->compressed_data, 0, $this->position)) & 0xFFFF) === $crc)
					{
						$this->position += 2;
					}
					else
					{
						return false;
					}
				}
				else
				{
					return false;
				}
			}

			// Decompress the actual data
			if (($this->data = gzinflate(substr($this->compressed_data, $this->position, -8))) === false)
			{
				return false;
			}
			else
			{
				$this->position = $this->compressed_size - 8;
			}

			// Check CRC of data
			$crc = current(unpack('V', substr($this->compressed_data, $this->position, 4)));
			$this->position += 4;
			/*if (extension_loaded('hash') && sprintf('%u', current(unpack('V', hash('crc32b', $this->data)))) !== sprintf('%u', $crc))
			{
				return false;
			}*/

			// Check ISIZE of data
			$isize = current(unpack('V', substr($this->compressed_data, $this->position, 4)));
			$this->position += 4;
			if (sprintf('%u', strlen($this->data) & 0xFFFFFFFF) !== sprintf('%u', $isize))
			{
				return false;
			}

			// Wow, against all odds, we've actually got a valid gzip string
			return true;
		}
		else
		{
			return false;
		}
	}