Checks if the set file starts with the correct character sequence, which
helps to stop any rouge whitespace making it in before the first php tag.

@link http://stackoverflow.com/a/2440685
499104
public function review(ReporterInterface $reporter, ReviewableInterface $file)
    {
        $cmd = sprintf('read -r LINE < %s && echo $LINE', $file->getFullPath());

        $process = $this->getProcess($cmd);
        $process->run();

        if (! in_array(trim($process->getOutput()), ['<?php', '#!/usr/bin/env php'])) {
            $message = 'File must begin with `<?php` or `#!/usr/bin/env php`';
            $reporter->error($message, $this, $file);
        }
    }
1263524
protected function createInitialDefinition()
    {
        return [
            /*
             * Match against non-special characters. To explain the components of this:
             *
             * [^\\\\*\[?]+(?:\\\\.[^\\\\*\[?]*)*
             *  - This matches non-special (\*[?) characters. If it matches one, it'll permit it to be an escape
             *    (i.e. \) if a character exists after it (which may be "special"). This then returns to the previous
             *    matching pattern, repeating the same rules until a non-escaped "special" character is hit.
             *
             * (?:\\\\.[^\\\\*\[?]*)+
             *  - This immediately looks for escape characters, as the previous component of this regex requires for the
             *    initial character to be non-special. This then returns to the standard rules the previous regex.
             */
            '[^\\\\*\[?]+(?:\\\\.[^\\\\*\[?]*)*|(?:\\\\.[^\\\\*\[?]*)+' => self::T_WORD,
            // Simple match of "*"
            '\*' => self::T_WILDCARD_MULTI,
            // Simple match of "?"
            '\?' => self::T_WILDCARD_SINGLE,
            /*
             * Matches against [. This also optionally matches "!" or "^" as the first character to provide negation
             * context. The positive lookahead provides a means to check for "]" as the first character. This is a
             * slightly nasty hack to deal with a rule that "]" can be permitted as a standard character in a character,
             * grouping so long as it's the first character. Once we move into the IN_GROUP state we have no such
             * context, so it must be checked at this level. To achieve this we lookahead for the character, and ensure
             * it's captured by adding a capturing group inside (regex lookarounds do not capture).
             */
            '\[([!^]?)(?=(\])?)' => function (Stateful $lexer, $matches) {
                // Determine the state to enter (depending on whether the lookahead succeeded, i.e. "]" is the first
                // character of the grouping)
                $state = isset($matches[2])
                    ? 'IN_GROUP_SPECIAL_FIRST'
                    : 'IN_GROUP';

                $lexer->pushState($state);

                // Negated grouping if the first character is "!"
                return $matches[1] !== ''
                    ? self::T_GROUP_BEGIN_NEGATED
                    : self::T_GROUP_BEGIN;
            }
        ];
    }
366143
private function _checkPhpTagsStartLine($token) {
		if ($this->_isActive('phpTagsStartLine')) {
			if (!$this->_isLineStart) {
				$this->_writeError('phpTagsStartLine', $this->_getMessage('PHP_TAGS_START_LINE'));
			}
		}
	}
1060373
public static function valid($str)
	{
		// Cached expected number of octets after the current octet
		// until the beginning of the next UTF8 character sequence
		$mState = 0;

		// Cached Unicode character
		$mUcs4 = 0;

		// Cached expected number of octets in the current sequence
		$mBytes = 1;

		$len = strlen($str);

		for ($i = 0; $i < $len; $i++)
		{
			$in = ord($str{$i});

			if ($mState == 0)
			{
				// When mState is zero we expect either a US-ASCII character or a
				// multi-octet sequence.
				if (0 == (0x80 & ($in)))
				{
					// US-ASCII, pass straight through.
					$mBytes = 1;
				}
				elseif (0xC0 == (0xE0 & ($in)))
				{
					// First octet of 2 octet sequence
					$mUcs4 = ($in);
					$mUcs4 = ($mUcs4 & 0x1F) << 6;
					$mState = 1;
					$mBytes = 2;
				}
				elseif (0xE0 == (0xF0 & ($in)))
				{
					// First octet of 3 octet sequence
					$mUcs4 = ($in);
					$mUcs4 = ($mUcs4 & 0x0F) << 12;
					$mState = 2;
					$mBytes = 3;
				}
				elseif (0xF0 == (0xF8 & ($in)))
				{
					// First octet of 4 octet sequence
					$mUcs4 = ($in);
					$mUcs4 = ($mUcs4 & 0x07) << 18;
					$mState = 3;
					$mBytes = 4;
				}
				elseif (0xF8 == (0xFC & ($in)))
				{
					// First octet of 5 octet sequence.
					//
					// This is illegal because the encoded codepoint must be either
					// (a) not the shortest form or
					// (b) outside the Unicode range of 0-0x10FFFF.
					// Rather than trying to resynchronize, we will carry on until the end
					// of the sequence and let the later error handling code catch it.
					$mUcs4 = ($in);
					$mUcs4 = ($mUcs4 & 0x03) << 24;
					$mState = 4;
					$mBytes = 5;
				}
				elseif (0xFC == (0xFE & ($in)))
				{
					// First octet of 6 octet sequence, see comments for 5 octet sequence.
					$mUcs4 = ($in);
					$mUcs4 = ($mUcs4 & 1) << 30;
					$mState = 5;
					$mBytes = 6;
				}
				else
				{
					// Current octet is neither in the US-ASCII range nor a legal first
					// octet of a multi-octet sequence.
					return false;
				}
			}
			else
			{
				// When mState is non-zero, we expect a continuation of the multi-octet
				// sequence
				if (0x80 == (0xC0 & ($in)))
				{
					// Legal continuation.
					$shift = ($mState - 1) * 6;
					$tmp = $in;
					$tmp = ($tmp & 0x0000003F) << $shift;
					$mUcs4 |= $tmp;

					// End of the multi-octet sequence. mUcs4 now contains the final
					// Unicode codepoint to be output
					if (0 == --$mState)
					{
						// Check for illegal sequences and codepoints.
						// From Unicode 3.1, non-shortest form is illegal
						if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || ((3 == $mBytes) && ($mUcs4 < 0x0800)) || ((4 == $mBytes) && ($mUcs4 < 0x10000))
							|| (4 < $mBytes)
							|| (($mUcs4 & 0xFFFFF800) == 0xD800) // From Unicode 3.2, surrogate characters are illegal
							|| ($mUcs4 > 0x10FFFF)) // Codepoints outside the Unicode range are illegal
						{
							return false;
						}

						// Initialize UTF8 cache.
						$mState = 0;
						$mUcs4 = 0;
						$mBytes = 1;
					}
				}
				else
				{
					//((0xC0 & (*in) != 0x80) && (mState != 0))
					// Incomplete multi-octet sequence.
					return false;
				}
			}
		}

		return true;
	}
1274426
private function validate()
    {
        if (!stristr(self::CHARACTER_LIST, $this->value[0])) {
            throw new \Exception('Invalid first character: ' . $this->value[0]);
        }

        if (!in_array($this->value, self::listForCharacter($this->value[0]))) {
            throw new \Exception('Word not in known list of words: ' . $this->value);
        }
    }
654185
protected function matchSetextLines()
	{
		if ($this->text->indexOf('-') === false && $this->text->indexOf('=') === false)
		{
			return;
		}

		// Capture the any series of - or = alone on a line, optionally preceded with the
		// angle brackets notation used in blockquotes
		$regexp = '/^(?=[-=>])(?:> ?)*(?=[-=])(?:-+|=+) *$/m';
		if (!preg_match_all($regexp, $this->text, $matches, PREG_OFFSET_CAPTURE))
		{
			return;
		}

		foreach ($matches[0] as list($match, $matchPos))
		{
			// Compute the position of the end tag. We start on the LF character before the
			// match and keep rewinding until we find a non-space character
			$endPos = $matchPos - 1;
			while ($endPos > 0 && $this->text->charAt($endPos - 1) === ' ')
			{
				--$endPos;
			}

			// Store at the offset of the LF character
			$this->setextLines[$matchPos - 1] = [
				'endLen'     => $matchPos + strlen($match) - $endPos,
				'endPos'     => $endPos,
				'quoteDepth' => substr_count($match, '>'),
				'tagName'    => ($match[0] === '=') ? 'H1' : 'H2'
			];
		}
	}
271341
public function offsetExists($offset)
    {
        switch ($offset) {

            case 'code':
            case 'tag': return isset($this->tag);
            break;
            case 'indexStart':
                return isset($this->indexStart);
            break;
            case 'indexEnd':
                return isset($this->indexEnd);
            break;
            case 'indexLength':
                return !is_null($this->getIndexLength());
            break;
            case 'charStart':
                return isset($this->charStart);
            break;
            case 'charEnd':
                return isset($this->charEnd);
            break;
            case 'charLength':
                return !is_null($this->getCharLength());
            break;
            case 'subSpecs':
                return (0 < count($this->subSpecs)) ? true : false;
            break;
            default:
                return false;
        }
    }
285481
static Matcher startsWithCharSeq(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      List<Matcher> matchers = matcher.<SeqMatcher>as().matchers();
      if (matchers.size() >= 2
          && matchers.get(0) instanceof StartMatcher
          && matchers.get(1) instanceof CharSeqMatcher) {
        List<Matcher> ms = new ArrayList<>();
        ms.add(new StartsWithMatcher(matchers.get(1).<CharSeqMatcher>as().pattern()));
        ms.addAll(matchers.subList(2, matchers.size()));
        return SeqMatcher.create(ms);
      }
    }
    return matcher;
  }
254215
function firstChar( $s ) {
		$matches = array();
		preg_match(
			'/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
				'[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
			$s,
			$matches
		);

		if ( isset( $matches[1] ) ) {
			if ( strlen( $matches[1] ) != 3 ) {
				return $matches[1];
			}

			// Break down Hangul syllables to grab the first jamo
			$code = utf8ToCodepoint( $matches[1] );
			if ( $code < 0xac00 || 0xd7a4 <= $code ) {
				return $matches[1];
			} elseif ( $code < 0xb098 ) {
				return "\xe3\x84\xb1";
			} elseif ( $code < 0xb2e4 ) {
				return "\xe3\x84\xb4";
			} elseif ( $code < 0xb77c ) {
				return "\xe3\x84\xb7";
			} elseif ( $code < 0xb9c8 ) {
				return "\xe3\x84\xb9";
			} elseif ( $code < 0xbc14 ) {
				return "\xe3\x85\x81";
			} elseif ( $code < 0xc0ac ) {
				return "\xe3\x85\x82";
			} elseif ( $code < 0xc544 ) {
				return "\xe3\x85\x85";
			} elseif ( $code < 0xc790 ) {
				return "\xe3\x85\x87";
			} elseif ( $code < 0xcc28 ) {
				return "\xe3\x85\x88";
			} elseif ( $code < 0xce74 ) {
				return "\xe3\x85\x8a";
			} elseif ( $code < 0xd0c0 ) {
				return "\xe3\x85\x8b";
			} elseif ( $code < 0xd30c ) {
				return "\xe3\x85\x8c";
			} elseif ( $code < 0xd558 ) {
				return "\xe3\x85\x8d";
			} else {
				return "\xe3\x85\x8e";
			}
		} else {
			return '';
		}
	}
96411
private function checkForContentInCopyrightTag(File $phpcs_file, $copyright_tag_ptr, $comment_end_ptr): void
    {
        $tokens = $phpcs_file->getTokens();
        $ptr    = $phpcs_file->findNext(T_DOC_COMMENT_STRING, $copyright_tag_ptr, $comment_end_ptr);
        if ($ptr !== false && $tokens[$ptr]['line'] === $tokens[$copyright_tag_ptr]['line']) {
            return;
        }

        $error = 'Content missing for ' . $this->copyright_tag . ' tag in File comment';
        if (!$phpcs_file->addFixableError($error, $copyright_tag_ptr, 'Empty ' . $this->copyright_tag . ' Tag')) {
            return;
        }

        $phpcs_file->fixer->addContent($copyright_tag_ptr, ' ' . $this->getCopyrightLine());
    }
896214
protected function isValidFormat()
    {
        //    Reading 2048 bytes should be enough to validate that the format is HTML
        $data = fread($this->fileHandle, 2048);
        if ((strpos($data, '<') !== false) &&
                (strlen($data) !== strlen(strip_tags($data)))) {
            return true;
        }

        return false;
    }
264035
private void matchEndLine() {
		// First, parse all whitespace characters except for new lines
		index = skipLineSpace(index);

		// Second, check whether we've reached the end-of-file (as signaled by
		// running out of tokens), or we've encountered some token which not a
		// newline.
		if (index >= tokens.size()) {
			return; // EOF
		} else if (tokens.get(index).kind != NewLine) {
			syntaxError("expected end-of-line", tokens.get(index));
		} else {
			index = index + 1;
		}
	}
244918
public static function check_filename(): bool
  {

    $args = \func_get_args();
    // Each argument must be a string starting with a letter, and having than one character made of letters, numbers and underscores
    foreach ( $args as $a ){
      if ( !\is_string($a) || (strpos($a, '/') !== false) || (strpos($a, '\\') !== false) ){
        return false;
      }
    }
    return true;
  }
407001
function readCodeFromFile()
  {
    $fp = @fopen($this->wordlist_file, 'rb');
    if (!$fp) return false;

    $fsize = filesize($this->wordlist_file);
    if ($fsize < 32) return false; // too small of a list to be effective

    if ($fsize < 128) {
      $max = $fsize; // still pretty small but changes the range of seeking
    } else {
      $max = 128;
    }

    fseek($fp, rand(0, $fsize - $max), SEEK_SET);
    $data = fread($fp, 128); // read a random 128 bytes from file
    fclose($fp);
    $data = preg_replace("/\r?\n/", "\n", $data);

    $start = strpos($data, "\n", rand(0, 100)) + 1; // random start position
    $end   = strpos($data, "\n", $start);           // find end of word

    return strtolower(substr($data, $start, $end - $start)); // return substring in 128 bytes
  }
196457
protected function end()
    {
        if ($this->matchChar(';')) {
            return true;
        }

        if ($this->count === strlen($this->buffer) || $this->buffer[$this->count] === '}') {
            // if there is end of file or a closing block next then we don't need a ;
            return true;
        }

        return false;
    }
472512
private boolean previousSegment() {
        assert(state == State.ITER_CHECK_BWD);
        // The input text [(iter index)..limit[ passes the FCD check.
        pos = iter.getIndex();
        // Collect the characters being checked, in case they need to be normalized.
        if(s == null) {
            s = new StringBuilder();
        } else {
            s.setLength(0);
        }
        int nextCC = 0;
        for(;;) {
            // Fetch the previous character and its fcd16 value.
            int c = iter.previousCodePoint();
            if(c < 0) { break; }
            int fcd16 = nfcImpl.getFCD16(c);
            int trailCC = fcd16 & 0xff;
            if(trailCC == 0 && s.length() != 0) {
                // FCD boundary after this character.
                iter.nextCodePoint();
                break;
            }
            s.appendCodePoint(c);
            if(trailCC != 0 && ((nextCC != 0 && trailCC > nextCC) ||
                                CollationFCD.isFCD16OfTibetanCompositeVowel(fcd16))) {
                // Fails FCD check. Find the previous FCD boundary and normalize.
                while(fcd16 > 0xff) {
                    c = iter.previousCodePoint();
                    if(c < 0) { break; }
                    fcd16 = nfcImpl.getFCD16(c);
                    if(fcd16 == 0) {
                        iter.nextCodePoint();
                        break;
                    }
                    s.appendCodePoint(c);
                }
                s.reverse();
                normalize(s);
                limit = pos;
                start = pos - s.length();
                state = State.IN_NORM_ITER_AT_START;
                pos = normalized.length();
                return true;
            }
            nextCC = fcd16 >> 8;
            if(nextCC == 0) {
                // FCD boundary before the following character.
                break;
            }
        }
        start = pos - s.length();
        assert(pos != start);
        iter.moveIndex(s.length());
        state = State.ITER_IN_FCD_SEGMENT;
        return true;
    }
664343
private function checkAndRegisterLineBreakErrors(): void
    {
        $tokens = $this->getTagTokens();
        $prevToken = [];
        $tagCounts = $this->docTagHelper->getTagCounts($tokens);
        $withReturn = false;

        foreach ($tokens as $tokenPos => $token) {
            $thisTagContent = $token['content'];
            $isReturn = $thisTagContent === '@return';

            $isGroupSwitch =
                // Did we switch the tag ...
                $prevToken && ($prevToken['content'] !== $thisTagContent) &&
                // ... but do we skip singles or are we entering the return block which should contain only 1 tag.
                (($tagCounts[$thisTagContent] !== 1) || ($isReturn && !$withReturn));

            // Insert new line between groups or before the return tag if there is no line break already.
            if ($isGroupSwitch && (($prevToken['line'] + 1) === $token['line'])) {
                $isFixing = $this->file->addFixableWarning(
                    static::MESSAGE_MISSING_NEWLINE_BETWEEN_TAGS,
                    $tokenPos,
                    static::CODE_MISSING_NEWLINE_BETWEEN_TAGS,
                    [
                        $prevToken['content']
                    ]
                );

                if ($isFixing) {
                    $this->insertNewLine($token);
                }
            }

            $prevToken = $token;
            // Return should be the last element, so this is ok.
            $withReturn = $isReturn;
        }
    }