{@inheritdoc}

@see \CommunityTranslation\Parser\Parser::parseSourceFile()
552531
public function parseSourceFile($packageHandle, $packageVersion, $path, $relDirectory = '')
    {
        if (!$this->filesystem->isFile($path)) {
            throw new UserMessageException(t('Unable to find the file %s', $path));
        }
        $tmp = $this->app->make(VolatileDirectory::class);
        $workDir = $tmp->getPath();
        if (!@$this->filesystem->copy($path, $workDir . '/' . basename($path))) {
            unset($tmp);
            throw new UserMessageException(t('Failed to copy a temporary file'));
        }
        $result = $this->parseDirectory($packageHandle, $packageVersion, $workDir, $relDirectory, '');
        unset($tmp);

        return $result;
    }
1201624
static public function parseFile($file, KTranslatorInterface $translator)
    {
        $strings   = array();
        $catalogue = $translator->getCatalogue();

        // Catch exceptions if any.
        try {
            $translations = $translator->getObject('object.config.factory')->fromFile($file);
        }  catch (Exception $e) {
            $translations = array();
        }

        foreach ($translations as $key => $value) {
            $strings[$catalogue->getPrefix() . $catalogue->generateKey($key)] = $value;
        }

        return $strings;
    }
962146
public function loadSource($source)
    {
        $parser = new Parser();

        list($this->headers, $this->content) = $parser->parsePart($source);
    }
1303690
public function parse($file)
    {
        if (isset($this->_tree[$file])) {
            return $this->_tree[$file];
        }
        $parser = $this->_classes['parser'];
        return $this->_tree[$file] = $parser::parse(file_get_contents($file), ['lines' => true]);
    }
1211066
protected static function getSourceCode($file, $line)
    {
        $first = ($line - 9 > 0) ? $line - 9 : 1;

        try {
            $contents = file($file);
            $source = [
                'first' => $first,
                'source' => array_slice($contents, $first - 1, 19),
            ];
        } catch (Exception $e) {
            $source = [];
        }

        return $source;
    }
553836
public function process(File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        $functionName = $phpcsFile->findNext(array(T_STRING), $stackPtr);
        $openBracket  = $tokens[$stackPtr]['parenthesis_opener'];
        $closeBracket = $tokens[$stackPtr]['parenthesis_closer'];

        $multiLine = ($tokens[$openBracket]['line'] !== $tokens[$closeBracket]['line']);

        $nextParam = $openBracket;
        $params    = array();
        while (($nextParam = $phpcsFile->findNext(T_VARIABLE, ($nextParam + 1), $closeBracket)) !== false) {
            $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($nextParam + 1), ($closeBracket + 1), true);
            if ($nextToken === false) {
                break;
            }

            $nextCode = $tokens[$nextToken]['code'];

            if ($nextCode === T_EQUAL) {
                if ($tokens[($nextToken + 1)]['code'] === T_WHITESPACE) {
                    $gap   = strlen($tokens[($nextToken + 1)]['content']);
                    $arg   = $tokens[$nextParam]['content'];

                    if ($gap != 1) {
                        $error = "Expected 1 space between default value and equals sign for argument \"$arg\"; $gap found";
                        $phpcsFile->addError($error, $nextToken, 'FunctionArgSpacing');
                    }
                } else {
                    $error = "Expected 1 space between default value and equals sign for argument";
                    $phpcsFile->addError($error, $nextToken, 'FunctionArgSpacing');
                }
            }

            // Find and check the comma (if there is one).
            $nextComma = $phpcsFile->findNext(T_COMMA, ($nextParam + 1), $closeBracket);
            if ($nextComma !== false) {
                // Comma found.
                if ($tokens[($nextComma - 1)]['code'] === T_WHITESPACE) {
                    $space = strlen($tokens[($nextComma - 1)]['content']);
                    $arg   = $tokens[$nextParam]['content'];
                    $error = "Expected 0 spaces between argument \"$arg\" and comma; $space found";
                    $phpcsFile->addError($error, $nextToken, 'FunctionArgSpacing');
                }
            }

            // Take references into account when expecting the
            // location of whitespace.
            if ($phpcsFile->isReference(($nextParam - 1)) === true) {
                $whitespace = $tokens[($nextParam - 2)];
            } else {
                $whitespace = $tokens[($nextParam - 1)];
            }

            if (empty($params) === false) {
                // This is not the first argument in the function declaration.
                $arg = $tokens[$nextParam]['content'];

                if ($whitespace['code'] === T_WHITESPACE) {
                    $gap = strlen($whitespace['content']);

                    // Before we throw an error, make sure there is no type hint.
                    $comma     = $phpcsFile->findPrevious(T_COMMA, ($nextParam - 1));
                    $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($comma + 1), null, true);
                    if ($phpcsFile->isReference($nextToken) === true) {
                        $nextToken++;
                    }

                    if ($nextToken !== $nextParam) {
                        // There was a type hint, so check the spacing between
                        // the hint and the variable as well.
                        $hint = $tokens[$nextToken]['content'];

                        if ($gap !== 1 && $multiLine === false) {
                            $error = "Expected 1 space between type hint and argument \"$arg\"; $gap found";
                            $phpcsFile->addError($error, $nextToken, 'FunctionTypeHintSpacing');
                        }

                        if ($multiLine === false) {
                            if ($tokens[($comma + 1)]['code'] !== T_WHITESPACE) {
                                $error = "Expected 1 space between comma and type hint \"$hint\"; 0 found";
                                $phpcsFile->addError($error, $nextToken, 'FunctionTypeHintSpacing');
                            } else {
                                $gap = strlen($tokens[($comma + 1)]['content']);
                                if ($gap !== 1) {
                                    $error = "Expected 1 space between comma and type hint \"$hint\"; $gap found";
                                    $phpcsFile->addError($error, $nextToken, 'FunctionTypeHintSpacing');
                                }
                            }
                        }
                    } elseif ($multiLine === false && $gap !== 1) {
                        $error = "Expected 1 space between comma and argument \"$arg\"; $gap found";
                        $phpcsFile->addError($error, $nextToken, 'FunctionArgSpacing');
                    }//end if
                } else {
                    $error = "Expected 1 space between comma and argument \"$arg\"; 0 found";
                    $phpcsFile->addError($error, $nextToken, 'FunctionArgSpacing');
                }//end if
            } else {
                // First argument in function declaration.
                if ($whitespace['code'] === T_WHITESPACE) {
                    $gap = strlen($whitespace['content']);
                    $arg = $tokens[$nextParam]['content'];

                    // Before we throw an error, make sure there is no type hint.
                    $bracket   = $phpcsFile->findPrevious(T_OPEN_PARENTHESIS, ($nextParam - 1));
                    $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($bracket + 1), null, true);
                    if ($phpcsFile->isReference($nextToken) === true) {
                        $nextToken++;
                    }

                    if ($nextToken !== $nextParam) {
                        // There was a type hint, so check the spacing between
                        // the hint and the variable as well.
                        $hint = $tokens[$nextToken]['content'];

                        if ($gap !== 1 && $multiLine === false) {
                            $error = "Expected 1 space between type hint and argument \"$arg\"; $gap found";
                            $phpcsFile->addError($error, $nextToken, 'FunctionTypeHintSpacing');
                        }

                        if ($multiLine === false
                            && $tokens[($bracket + 1)]['code'] === T_WHITESPACE
                        ) {
                            $gap   = strlen($tokens[($bracket + 1)]['content']);

                            if ($gap != 1) {
                                $error = "Expected 1 space between opening bracket and type hint \"$hint\"; $gap found";
                                $phpcsFile->addError($error, $nextToken, 'FunctionTypeHintSpacing');
                            }
                        }
                    } elseif ($multiLine === false) {
                        if ($gap != 1) {
                            $error = "Expected 1 space between opening bracket and argument \"$arg\"; $gap found";
                            $phpcsFile->addError($error, $nextToken, 'FunctionTypeHintSpacing');
                        }
                    }
                }//end if
            }//end if

            $params[] = $nextParam;
        }//end while

        if (empty($params) === true) {
            // There are no parameters for this function.
            if (($closeBracket - $openBracket) !== 1) {
                $space = strlen($tokens[($closeBracket - 1)]['content']);
                $error = "Expected 0 spaces between brackets of function declaration; $space found";
                $phpcsFile->addError($error, $stackPtr, 'FunctionDeclarationSpacing');
            }
        } else {
            // There should be exactly one space after the opening parenthesis
            if ($tokens[$openBracket + 1]['code'] !== T_WHITESPACE || strlen($tokens[$openBracket + 1]['content']) != 1) {
                // If the open bracket doesn't have a space after it and it's not the last thing on the line, throw an error
                if ($tokens[$openBracket + 1]['content'] != PHP_EOL) {
                    $error = "Expected 1 space between the opening parenthesis and first argument";
                    $phpcsFile->addError($error, $openBracket, 'FunctionDeclarationSpacing');
                }
            }

            // There should be exactly one space or a newline before the closing
            // parenthesis (todo: check for proper indentation if newline)
            if ($tokens[$closeBracket - 1]['code'] !== T_WHITESPACE
                || (
                    strlen($tokens[$closeBracket - 1]['content']) != 1
                    && $tokens[$closeBracket - 2]['content'] !== PHP_EOL
                )
            ) {
                $firstOnLine = $phpcsFile->findFirstOnLine(T_WHITESPACE, $closeBracket, true);

                // Don't throw an error if the closing parenthesis is the first thing on the line
                if ($firstOnLine != $closeBracket) {
                    $error = "Expected 1 space between the last argument and the closing parenthesis";
                    $phpcsFile->addError($error, $closeBracket, 'FunctionDeclarationSpacing');
                }
            }
        }
    }
237454
protected function generateViewFile($sourceFile,$viewFile)
	{
		static $regexRules=array(
			'<%=?\s*(.*?)\s*%>',		// PHP statements or expressions
			'<\/?(com|cache|clip):([\w\.]+)\s*((?:\s*\w+\s*=\s*\'.*?(?<!\\\\)\'|\s*\w+\s*=\s*".*?(?<!\\\\)"|\s*\w+\s*=\s*\{.*?\})*)\s*\/?>', // component tags
			'<!---.*?--->',	// template comments
		);
		$this->_sourceFile=$sourceFile;
		$this->_input=file_get_contents($sourceFile);
		$n=preg_match_all('/'.implode('|',$regexRules).'/msS',$this->_input,$matches,PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
		$textStart=0;
		$this->_output="<?php /* source file: $sourceFile */ ?>\n";
		for($i=0;$i<$n;++$i)
		{
			$match=&$matches[$i];
			$str=$match[0][0];
			$matchStart=$match[0][1];
			$matchEnd=$matchStart+strlen($str)-1;

			if($matchStart>$textStart)
				$this->_output.=substr($this->_input,$textStart,$matchStart-$textStart);
			$textStart=$matchEnd+1;

			if(strpos($str,'<com:')===0)	// opening component tag
			{
				$type=$match[3][0];
				if($str[strlen($str)-2]!=='/')  // open tag
					$this->_output.=$this->processBeginWidget($type,$match[4][0],$match[2][1]);
				else
					$this->_output.=$this->processWidget($type,$match[4][0],$match[2][1]);
			}
			elseif(strpos($str,'</com:')===0)	// closing component tag
				$this->_output.=$this->processEndWidget($match[3][0],$match[2][1]);
			elseif(strpos($str,'<cache:')===0)	// opening cache tag
			{
				$id=$match[3][0];
				if($str[strlen($str)-2]!=='/')  // open tag
					$this->_output.=$this->processBeginCache($id,$match[4][0],$match[2][1]);
				else
					$this->_output.=$this->processCache($id,$match[4][0],$match[2][1]);
			}
			elseif(strpos($str,'</cache:')===0)	// closing cache tag
				$this->_output.=$this->processEndCache($match[3][0],$match[2][1]);
			elseif(strpos($str,'<clip:')===0)	// opening clip tag
			{
				$id=$match[3][0];
				if($str[strlen($str)-2]!=='/')  // open tag
					$this->_output.=$this->processBeginClip($id,$match[4][0],$match[2][1]);
				else
					$this->_output.=$this->processClip($id,$match[4][0],$match[2][1]);
			}
			elseif(strpos($str,'</clip:')===0)	// closing clip tag
				$this->_output.=$this->processEndClip($match[3][0],$match[2][1]);
			elseif(strpos($str,'<%=')===0)	// expression
				$this->_output.=$this->processExpression($match[1][0],$match[1][1]);
			elseif(strpos($str,'<%')===0)	// statement
				$this->_output.=$this->processStatement($match[1][0],$match[1][1]);
		}
		if($textStart<strlen($this->_input))
			$this->_output.=substr($this->_input,$textStart);

		file_put_contents($viewFile,$this->_output);
	}
298369
public function parse() {
        /* @var $scope_resource AbstractResourceFile */
        $scope_resource = $this->getScope();
        if (!$scope_resource instanceof AbstractResourceFile) {
            throw new InvalidConfigException("INVALID scope resource file to parse.");
        }
        $contents = str_replace("\r", "\n", $this->contents);
        $annotation_lines = explode("\n", $contents);
        foreach ($annotation_lines as $annotation_line) {
            $annotation_line = trim($annotation_line);
            $matches = array();
            if ('@' !== substr($annotation_line, 0, 1)) {
                continue;
            }
            $this->say($annotation_line . '[' . $this->scope->getRealPath() . ']');
            if (preg_match('#^@([a-zA-Z]+)\s(.+)$#', $annotation_line, $matches)) {
                $command_name = $matches[1];
                $params = $matches[2];
            } elseif (preg_match('#^@([0-9a-zA-Z\/\\\]+)\((.*)\)$#', $annotation_line, $matches)) {
                $command_name = $matches[1];
                $params = $matches[2];
            } else {
                continue;
            }
            // Get the instance
            if ('require' === strtolower($command_name)) {
                $command_annotation = new RequireAnnotation($this);
            } elseif ('use' === strtolower($command_name)) {
                $command_annotation = new UseAnnotation($this);
            } elseif (class_exists($command_name)) {
                $command_annotation = new $command_name($this);
            } else {
                continue;
            }
            if ($command_annotation instanceof AbstractAnnotation) {
                $command_annotation->parse($params);
                StaticsManager::registAnnotation($command_annotation);
            }
        }
    }
860206
public function fromFileSource(FileSourceInterface $fileSource)
    {
        if ($fileSource instanceof PathSourceInterface) {
            return $this->fromPath($fileSource->getPath());
        }

        throw new RuntimeException('Unsupported file source');
    }
279463
public function setSourceFile($file)
    {
        $this->currentReaderId = $this->getPdfReaderId($file);
        $this->objectsToCopy[$this->currentReaderId] = [];

        $reader = $this->getPdfReader($this->currentReaderId);
        $this->setMinPdfVersion($reader->getPdfVersion());

        return $reader->getPageCount();
    }
246721
public function loadFile($pFile, $pParseKeys = false)
    {
        $this->_content = parse_ini_file($pFile, true);

        if ($pParseKeys) {
            $this->_parseKeys($this->_content);
        }
        return $this;
    }
810627
public function process(File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        if ($tokens[$stackPtr]['code'] === \T_NEW && $this->supportsBelow('5.3') !== true) {
            return;
        } elseif ($tokens[$stackPtr]['code'] === \T_CLONE && $this->supportsBelow('5.6') !== true) {
            return;
        }

        if (isset($tokens[$stackPtr]['nested_parenthesis']) === false) {
            // The `new className/clone $a` has to be in parentheses, without is not supported.
            return;
        }

        $parenthesisCloser = end($tokens[$stackPtr]['nested_parenthesis']);
        $parenthesisOpener = key($tokens[$stackPtr]['nested_parenthesis']);

        if (isset($tokens[$parenthesisOpener]['parenthesis_owner']) === true) {
            // If there is an owner, these parentheses are for a different purpose.
            return;
        }

        $prevBeforeParenthesis = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($parenthesisOpener - 1), null, true);
        if ($prevBeforeParenthesis !== false && $tokens[$prevBeforeParenthesis]['code'] === \T_STRING) {
            // This is most likely a function call with the new/cloned object as a parameter.
            return;
        }

        $nextAfterParenthesis = $phpcsFile->findNext(Tokens::$emptyTokens, ($parenthesisCloser + 1), null, true);
        if ($nextAfterParenthesis === false) {
            // Live coding.
            return;
        }

        if ($tokens[$nextAfterParenthesis]['code'] !== \T_OBJECT_OPERATOR
            && $tokens[$nextAfterParenthesis]['code'] !== \T_OPEN_SQUARE_BRACKET
        ) {
            return;
        }

        $data      = array('instantiation', '5.3');
        $errorCode = 'OnNewFound';

        if ($tokens[$stackPtr]['code'] === \T_CLONE) {
            $data      = array('cloning', '5.6');
            $errorCode = 'OnCloneFound';
        }

        $phpcsFile->addError(
            'Class member access on object %s was not supported in PHP %s or earlier',
            $parenthesisCloser,
            $errorCode,
            $data
        );
    }
834524
public function process(File $phpcsFile, $stackPtr)
    {
        if ($this->supportsAbove('7.1') === false) {
            return;
        }

        $tokens = $phpcsFile->getTokens();

        // Verify this use statement is used with a closure - if so, it has to have parenthesis before it.
        $previousNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true, null, true);
        if ($previousNonEmpty === false || $tokens[$previousNonEmpty]['code'] !== \T_CLOSE_PARENTHESIS
            || isset($tokens[$previousNonEmpty]['parenthesis_opener']) === false
        ) {
            return;
        }

        // ... and (a variable within) parenthesis after it.
        $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
        if ($nextNonEmpty === false || $tokens[$nextNonEmpty]['code'] !== \T_OPEN_PARENTHESIS) {
            return;
        }

        if (isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false) {
            // Live coding.
            return;
        }

        $closurePtr = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($tokens[$previousNonEmpty]['parenthesis_opener'] - 1), null, true);
        if ($closurePtr === false || $tokens[$closurePtr]['code'] !== \T_CLOSURE) {
            return;
        }

        // Get the parameters declared by the closure.
        $closureParams = PHPCSHelper::getMethodParameters($phpcsFile, $closurePtr);

        $errorMsg = 'Variables bound to a closure via the use construct cannot use the same name as superglobals, $this, or a declared parameter since PHP 7.1. Found: %s';

        for ($i = ($nextNonEmpty + 1); $i < $tokens[$nextNonEmpty]['parenthesis_closer']; $i++) {
            if ($tokens[$i]['code'] !== \T_VARIABLE) {
                continue;
            }

            $variableName = $tokens[$i]['content'];

            if ($variableName === '$this') {
                $phpcsFile->addError($errorMsg, $i, 'FoundThis', array($variableName));
                continue;
            }

            if (isset($this->superglobals[$variableName]) === true) {
                $phpcsFile->addError($errorMsg, $i, 'FoundSuperglobal', array($variableName));
                continue;
            }

            // Check whether it is one of the parameters declared by the closure.
            if (empty($closureParams) === false) {
                foreach ($closureParams as $param) {
                    if ($param['name'] === $variableName) {
                        $phpcsFile->addError($errorMsg, $i, 'FoundShadowParam', array($variableName));
                        continue 2;
                    }
                }
            }
        }
    }
958619
public function setSourceFile($filename)
    {
        if ($filename instanceof Pdf) {
            return parent::setSourceFile($filename->currentFilename);
        } else {
            return parent::setSourceFile($filename);
        }
        // FIX: tried to be more efficiend but using same parsers brings issues clonning too.
        $newPdf = $filename;
        $this->currentFilename =  $newPdf->currentFilename;

        $this->parsers[$newPdf->currentFilename] = $newPdf->parsers[$newPdf->currentFilename];
        $this->setPdfVersion(
            max($this->getPdfVersion(), $newPdf->currentParser->getPdfVersion())
        );
        $this->currentParser = $this->parsers[$newPdf->currentFilename];
        return $this->currentParser->getPageCount();
    }
1353170
protected function parseFile($file)
    {
        try {
            $dom = XmlUtils::loadFile($file, array($this, 'validateSchema'));
        } catch (\InvalidArgumentException $e) {
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
        }

        return simplexml_import_dom($dom);
    }
688324
public function process(File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === true) {
            $openParenthesis  = $tokens[$stackPtr]['parenthesis_opener'];
            $closeParenthesis = $tokens[$stackPtr]['parenthesis_closer'];
        } else {
            if (version_compare(PHPCSHelper::getVersion(), '2.3.4', '>=')) {
                return;
            }

            // Deal with PHPCS 2.3.0-2.3.3 which do not yet set the parenthesis properly for declare statements.
            $openParenthesis = $phpcsFile->findNext(\T_OPEN_PARENTHESIS, ($stackPtr + 1), null, false, null, true);
            if ($openParenthesis === false || isset($tokens[$openParenthesis]['parenthesis_closer']) === false) {
                return;
            }
            $closeParenthesis = $tokens[$openParenthesis]['parenthesis_closer'];
        }

        $directivePtr = $phpcsFile->findNext(\T_STRING, ($openParenthesis + 1), $closeParenthesis, false);
        if ($directivePtr === false) {
            return;
        }

        $directiveContent = $tokens[$directivePtr]['content'];

        if (isset($this->newDirectives[$directiveContent]) === false) {
            $error = 'Declare can only be used with the directives %s. Found: %s';
            $data  = array(
                implode(', ', array_keys($this->newDirectives)),
                $directiveContent,
            );

            $phpcsFile->addError($error, $stackPtr, 'InvalidDirectiveFound', $data);

        } else {
            // Check for valid directive for version.
            $itemInfo = array(
                'name'   => $directiveContent,
            );
            $this->handleFeature($phpcsFile, $stackPtr, $itemInfo);

            // Check for valid directive value.
            $valuePtr = $phpcsFile->findNext($this->ignoreTokens, $directivePtr + 1, $closeParenthesis, true);
            if ($valuePtr === false) {
                return;
            }

            $this->addWarningOnInvalidValue($phpcsFile, $valuePtr, $directiveContent);
        }
    }
1084691
public function parseDictionaryFile($packageHandle, $packageVersion, $path, $kinds)
    {
        if (!$this->filesystem->isFile($path)) {
            throw new UserMessageException(t('Unable to find the file %s', $path));
        }
        $translations = null;
        if ($kinds & (self::DICTIONARY_SOURCE | self::DICTIONARY_LOCALIZED_SOURCE)) {
            try {
                $translations = Translations::fromPoFile($path);
                if (count($translations) === 0) {
                    $translations = null;
                }
            } catch (Exception $x) {
                $translations = null;
            }
        }
        if ($translations === null && ($kinds & self::DICTIONARY_LOCALIZED_COMPILED)) {
            try {
                $translations = Translations::fromMoFile($path);
                if (count($translations) === 0) {
                    $translations = null;
                }
            } catch (Exception $x) {
                $translations = null;
            }
        }
        $result = null;
        if ($translations !== null) {
            $locale = null;
            $localeID = $translations->getLanguage();
            $locale = $localeID ? $this->app->make(LocaleRepository::class)->findApproved($localeID) : null;
            if ($locale === null) {
                if ($kinds & self::DICTIONARY_SOURCE) {
                    $translations->setLanguage($this->app->make('community_translation/sourceLocale'));
                    foreach ($translations as $translation) {
                        $translation->setTranslation('');
                        $translation->setPluralTranslation('');
                    }
                    $result = new Parsed();
                    $result->setSourceStrings($translations);
                }
            } else {
                if ($kinds & (self::DICTIONARY_LOCALIZED_SOURCE | self::DICTIONARY_LOCALIZED_COMPILED)) {
                    $translations->setLanguage($locale->getID());
                    $result = new Parsed();
                    $result->setTranslations($locale, $translations);
                }
            }
        }

        return $result;
    }