Scopes PHP files.

{@inheritdoc}

@throws PhpParserError
519012
public function scope(string $filePath, string $contents, string $prefix, array $patchers, Whitelist $whitelist): string
    {
        if (false === $this->isPhpFile($filePath, $contents)) {
            return $this->decoratedScoper->scope(...func_get_args());
        }

        return $this->scopePhp($contents, $prefix, $whitelist);
    }
1001661
public function process(File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $arrayToken = $tokens[$stackPtr];
        $closeParenthesisPointer = $arrayToken['bracket_closer'];
        /** @var int $previousToCloseParenthesisPointer */
        $previousToCloseParenthesisPointer = TokenHelper::findPreviousEffective($phpcsFile, $closeParenthesisPointer - 1);
        $previousToCloseParenthesisToken = $tokens[$previousToCloseParenthesisPointer];

        if ($previousToCloseParenthesisToken['code'] !== T_COMMA) {
            return;
        }

        $fix = $phpcsFile->addFixableError(
            'Forbidden trailing comma after the last element.',
            $previousToCloseParenthesisPointer,
            'ForbiddenArrayTrailingComma'
        );

        if ($fix === false) {
            return;
        }

        $phpcsFile->fixer->beginChangeset();
        $phpcsFile->fixer->replaceToken($previousToCloseParenthesisPointer, '');
        $phpcsFile->fixer->endChangeset();
    }
287111
private function parseRequestUri(): void
    {
        $requestUri = $this->baseClass->getRequestUri();
        $path = \explode('/', $requestUri);
        $pathCnt = \count($path);
        if ($pathCnt > 0) {
            $file = \array_pop($path);
            $path = \sprintf('%%DOCUMENT_ROOT%%%s%s', \implode(DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR);
            $path = $this->baseClass->parsePath($path);

            $file = \explode('.', $file);
            $ext = '';

            if (\count($file) > 1) {
                $ext = \array_pop($file);
            }

            $file = \explode('__', \implode('.', $file));
            $resizeParams = [];

            if (\count($file) > 1) {
                $resizeParams = $this->parseResizeParams(\explode('_', $file[1]));
            }

            $file = $file[0];

            $this->uriParams['path'] = $path;
            $this->uriParams['file'] = $file;
            $this->uriParams['extension'] = $ext;
            $this->uriParams['resize-params'] = $resizeParams;
        }
    }
1102380
protected void loadDataFromFile(File definitionFile) throws IOException {
		PHPFileParser fp = new PHPFileParser(definitionFile);
		createInternalDataStructre(fp.getSections());
	}
1340036
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        $ignore = array(
                   T_DOUBLE_COLON,
                   T_OBJECT_OPERATOR,
                   T_FUNCTION,
                   T_CONST,
                  );

        $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
        if (in_array($tokens[$prevToken]['code'], $ignore) === true) {
            // Not a call to a PHP function.
            return;
        }

        $function = strtolower($tokens[$stackPtr]['content']);
        if ($function != 'ini_get' && $function != 'ini_set') {
            return;
        }
        $iniToken = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, $stackPtr, null);
        if (in_array(str_replace("'", "", $tokens[$iniToken]['content']), array_keys($this->deprecatedIniDirectives)) === false) {
            return;
        }

        $error = '';

        foreach ($this->deprecatedIniDirectives[str_replace("'", "", $tokens[$iniToken]['content'])] as $version => $forbidden)
        {
            if ($this->supportsAbove($version)) {
                if ($forbidden === true) {
                    $error .= " forbidden";
                } else {
                    $error .= " deprecated";
                }
                $error .= " from PHP " . $version . " and";
            }
        }

        if (strlen($error) > 0) {
            $error = "INI directive " . $tokens[$iniToken]['content'] . " is" . $error;
            $error = substr($error, 0, strlen($error) - 4) . ".";

            $phpcsFile->addWarning($error, $stackPtr);
        }

    }
301087
final protected function parseRow(): void
    {
        // only parse the next row if only one in buffer
        if (\count($this->bufferedRow) > 1) {
            return;
        }
        if (feof($this->file)) {
            $this->currentRow = null;

            return;
        }

        $this->currentRowEnded = false;
        // read file until row is ended
        while (!$this->currentRowEnded && !feof($this->file)) {
            $data = fread($this->file, 1024);
            xml_parse($this->parser, $data);
        }
    }
259861
public function setFiles()
    {
        $this->files = [];
        $path = $this->getValue();

        if (!preg_match('#^/#', $path)) {
            $path = $this->parser->getServer()->getPrefix().'/'.$path;
        }

        $iterator = new GlobIterator($path);
        foreach ($iterator as $path) {
            $this->files[] = $path;
        }

        return $this;
    }
887752
public function process(File $phpcsFile, $stackPtr)
    {
        if ($this->supportsAbove('7.3') === false) {
            return;
        }

        $funcName = $phpcsFile->getDeclarationName($stackPtr);

        if (strtolower($funcName) !== 'assert') {
            return;
        }

        if ($phpcsFile->hasCondition($stackPtr, $this->scopes) === true) {
            return;
        }

        if ($this->determineNamespace($phpcsFile, $stackPtr) === '') {
            // Not a namespaced function declaration. Parse error, but not our concern.
            return;
        }

        $phpcsFile->addWarning('Declaring a free-standing function called assert() is deprecated since PHP 7.3.', $stackPtr, 'Found');
    }
184780
public function setData($definitions)
    {
        if (is_array($definitions)) {
            $this->parsedData = $definitions;
            return;
        }

        if (!is_file($definitions)) {
            throw new InvalidArgumentException(
                "The form definition file '{$definitions}' does not exists."
            );
        }

        try {
            $this->parsedData = Yaml::parse(file_get_contents($definitions));
        } catch (\Exception $caught) {
            throw new ParserErrorException(
                'Error parsing form definitions: '.$caught->getMessage(),
                0,
                $caught
            );
        }
    }
801931
function parse( $inputFiles = false, $iniFile = false, $reset = true, $placement = false )
    {
        if ( $inputFiles === false or
             $iniFile === false )
        {
            eZDebug::accumulatorStart( 'ini_parse_find_files', 'Ini load', 'Find INI Files2' );
            $this->findInputFiles( $inputFiles, $iniFile );
            eZDebug::accumulatorStop( 'ini_parse_find_files' );
        }

        if ( $reset )
            $this->reset();

        foreach ( $inputFiles as $inputFile )
        {
            if ( file_exists( $inputFile ) )
            {
                $this->parseFile( $inputFile, $placement );
            }
        }
    }
1020802
public function setHeaders($headers) 
    {

       if(!$this->_parserObj) {
           $this->initParser($this->getRespondType());

        }

        /** @var array  _headers */
        $this->_headers = $this->getParser()->getHeaders();
        $this->_headers = array_merge($this->_headers,$headers);
    }
336468
public function process(File $phpcsFile, $stackPtr)
    {
        // Get all parameters from method signature.
        $paramNames = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
        if (empty($paramNames)) {
            return;
        }

        $supportsPHP4 = $this->supportsBelow('4.4');

        foreach ($paramNames as $param) {
            if ($param['type_hint'] === '') {
                continue;
            }

            // Strip off potential nullable indication.
            $typeHint = ltrim($param['type_hint'], '?');

            if ($supportsPHP4 === true) {
                $phpcsFile->addError(
                    'Type declarations were not present in PHP 4.4 or earlier.',
                    $param['token'],
                    'TypeHintFound'
                );

            } elseif (isset($this->newTypes[$typeHint])) {
                $itemInfo = array(
                    'name' => $typeHint,
                );
                $this->handleFeature($phpcsFile, $param['token'], $itemInfo);

                // As of PHP 7.0, using `self` or `parent` outside class scope throws a fatal error.
                // Only throw this error for PHP 5.2+ as before that the "type hint not supported" error
                // will be thrown.
                if (($typeHint === 'self' || $typeHint === 'parent')
                    && $this->inClassScope($phpcsFile, $stackPtr, false) === false
                    && $this->supportsAbove('5.2') !== false
                ) {
                    $phpcsFile->addError(
                        "'%s' type cannot be used outside of class scope",
                        $param['token'],
                        ucfirst($typeHint) . 'OutsideClassScopeFound',
                        array($typeHint)
                    );
                }
            } elseif (isset($this->invalidTypes[$typeHint])) {
                $error = "'%s' is not a valid type declaration. Did you mean %s ?";
                $data  = array(
                    $typeHint,
                    $this->invalidTypes[$typeHint],
                );

                $phpcsFile->addError($error, $param['token'], 'InvalidTypeHintFound', $data);
            }
        }
    }
1242327
private function parseFiles()
    {
        $parser = $this->app['parser'];
        $builder = $this->app['descriptor.builder'];

        $builder->createProjectDescriptor();
        $projectDescriptor = $builder->getProjectDescriptor();
        $projectDescriptor->setName($this->title);

        $paths = [];

        // filesets
        foreach ($this->filesets as $fs) {
            $ds = $fs->getDirectoryScanner($this->project);
            $dir = $fs->getDir($this->project);
            $srcFiles = $ds->getIncludedFiles();

            foreach ($srcFiles as $file) {
                $paths[] = $dir . FileSystem::getFileSystem()->getSeparator() . $file;
            }
        }

        $this->project->log("Will parse " . count($paths) . " file(s)", Project::MSG_VERBOSE);

        $files = new \phpDocumentor\Fileset\Collection();
        $files->addFiles($paths);

        $mapper = new \phpDocumentor\Descriptor\Cache\ProjectDescriptorMapper($this->app['descriptor.cache']);
        $mapper->garbageCollect($files);
        $mapper->populate($projectDescriptor);

        $parser->setPath($files->getProjectRoot());
        $parser->setDefaultPackageName($this->defaultPackageName);

        $parser->parse($builder, $files);

        $mapper->save($projectDescriptor);

        return $mapper;
    }
301704
public function scope(string $filePath, string $contents, string $prefix, array $patchers, Whitelist $whitelist): string
    {
        if (1 !== preg_match('/composer\.json$/', $filePath)) {
            return $this->decoratedScoper->scope($filePath, $contents, $prefix, $patchers, $whitelist);
        }

        $decodedJson = json_decode($contents);

        if (false === ($decodedJson instanceof stdClass)) {
            throw new LogicException(
                sprintf(
                    'Expected the decoded JSON to be an stdClass instance, got "%s" instead',
                    gettype($decodedJson)
                )
            );
        }

        $decodedJson = AutoloadPrefixer::prefixPackageAutoloadStatements($decodedJson, $prefix, $whitelist);

        return json_encode(
            $decodedJson,
            JSON_PRETTY_PRINT
        );
    }
39278
protected function checkExtends(File $phpcsFile, int $stackPtr): void
    {
        $extendsIndex = $phpcsFile->findNext([T_EXTENDS], $stackPtr + 1);
        if (!$extendsIndex) {
            return;
        }

        $extends = $this->parseExtends($phpcsFile, $extendsIndex);

        foreach ($extends as $extend) {
            $this->fixStatement($phpcsFile, $extend, $stackPtr);
        }
    }
1193267
public function process(File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $token  = $tokens[$stackPtr];

        // Check if the break/continue is within a valid loop structure.
        if (empty($token['conditions']) === false) {
            foreach ($token['conditions'] as $tokenCode) {
                if (isset($this->validLoopStructures[$tokenCode]) === true) {
                    return;
                }
            }
        } else {
            // Deal with older PHPCS versions.
            if (isset($token['scope_condition']) === true && isset($this->backCompat[$tokens[$token['scope_condition']]['code']]) === true) {
                return;
            }
        }

        // If we're still here, no valid loop structure container has been found, so throw an error.
        $error     = "Using '%s' outside of a loop or switch structure is invalid";
        $isError   = false;
        $errorCode = 'Found';
        $data      = array($token['content']);

        if ($this->supportsAbove('7.0')) {
            $error    .= ' and will throw a fatal error since PHP 7.0';
            $isError   = true;
            $errorCode = 'FatalError';
        }

        $this->addMessage($phpcsFile, $error, $stackPtr, $isError, $errorCode, $data);
    }
1079899
public function process(File $phpcsFile, $stackPtr)
    {
        if ($this->supportsAbove('7.0') === false) {
            return;
        }

        $tokens = $phpcsFile->getTokens();

        if (isset($tokens[$stackPtr]['scope_opener'], $tokens[$stackPtr]['scope_closer']) === false) {
            // Abstract function, interface function, live coding or parse error.
            return;
        }

        $scopeOpener = $tokens[$stackPtr]['scope_opener'];
        $scopeCloser = $tokens[$stackPtr]['scope_closer'];

        // Does the function declaration have parameters ?
        $params = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
        if (empty($params)) {
            // No named arguments found, so no risk of them being changed.
            return;
        }

        $paramNames = array();
        foreach ($params as $param) {
            $paramNames[] = $param['name'];
        }

        for ($i = ($scopeOpener + 1); $i < $scopeCloser; $i++) {
            if (isset($this->skipPastNested[$tokens[$i]['type']]) && isset($tokens[$i]['scope_closer'])) {
                // Skip past nested structures.
                $i = $tokens[$i]['scope_closer'];
                continue;
            }

            if ($tokens[$i]['code'] !== \T_STRING) {
                continue;
            }

            $foundFunctionName = strtolower($tokens[$i]['content']);

            if (isset($this->changedFunctions[$foundFunctionName]) === false) {
                // Not one of the target functions.
                continue;
            }

            /*
             * Ok, so is this really a function call to one of the PHP native functions ?
             */
            $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($i + 1), null, true);
            if ($next === false || $tokens[$next]['code'] !== \T_OPEN_PARENTHESIS) {
                // Live coding, parse error or not a function call.
                continue;
            }

            $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($i - 1), null, true);
            if ($prev !== false) {
                if (isset($this->noneFunctionCallIndicators[$tokens[$prev]['code']])) {
                    continue;
                }

                // Check for namespaced functions, ie: \foo\bar() not \bar().
                if ($tokens[ $prev ]['code'] === \T_NS_SEPARATOR) {
                    $pprev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prev - 1), null, true);
                    if ($pprev !== false && $tokens[ $pprev ]['code'] === \T_STRING) {
                        continue;
                    }
                }
            }

            /*
             * Address some special cases.
             */
            if ($foundFunctionName !== 'func_get_args') {
                $paramOne = $this->getFunctionCallParameter($phpcsFile, $i, 1);
                if ($paramOne !== false) {
                    switch ($foundFunctionName) {
                        /*
                         * Check if `debug_(print_)backtrace()` is called with the
                         * `DEBUG_BACKTRACE_IGNORE_ARGS` option.
                         */
                        case 'debug_backtrace':
                        case 'debug_print_backtrace':
                            $hasIgnoreArgs = $phpcsFile->findNext(
                                \T_STRING,
                                $paramOne['start'],
                                ($paramOne['end'] + 1),
                                false,
                                'DEBUG_BACKTRACE_IGNORE_ARGS'
                            );

                            if ($hasIgnoreArgs !== false) {
                                // Debug_backtrace() called with ignore args option.
                                continue 2;
                            }
                            break;

                        /*
                         * Collect the necessary information to only throw a notice if the argument
                         * touched/changed is in line with the passed $arg_num.
                         *
                         * Also, we can ignore `func_get_arg()` if the argument offset passed is
                         * higher than the number of named parameters.
                         *
                         * {@internal Note: This does not take calculations into account!
                         *  Should be exceptionally rare and can - if needs be - be addressed at a later stage.}}
                         */
                        case 'func_get_arg':
                            $number = $phpcsFile->findNext(\T_LNUMBER, $paramOne['start'], ($paramOne['end'] + 1));
                            if ($number !== false) {
                                $argNumber = $tokens[$number]['content'];

                                if (isset($paramNames[$argNumber]) === false) {
                                    // Requesting a non-named additional parameter. Ignore.
                                    continue 2;
                                }
                            }
                            break;
                    }
                }
            } else {
                /*
                 * Check if the call to func_get_args() happens to be in an array_slice() or
                 * array_splice() with an $offset higher than the number of named parameters.
                 * In that case, we can ignore it.
                 *
                 * {@internal Note: This does not take offset calculations into account!
                 *  Should be exceptionally rare and can - if needs be - be addressed at a later stage.}}
                 */
                if ($prev !== false && $tokens[$prev]['code'] === \T_OPEN_PARENTHESIS) {

                    $maybeFunctionCall = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prev - 1), null, true);
                    if ($maybeFunctionCall !== false
                        && $tokens[$maybeFunctionCall]['code'] === \T_STRING
                        && ($tokens[$maybeFunctionCall]['content'] === 'array_slice'
                        || $tokens[$maybeFunctionCall]['content'] === 'array_splice')
                    ) {
                        $parentFuncParamTwo = $this->getFunctionCallParameter($phpcsFile, $maybeFunctionCall, 2);
                        $number             = $phpcsFile->findNext(
                            \T_LNUMBER,
                            $parentFuncParamTwo['start'],
                            ($parentFuncParamTwo['end'] + 1)
                        );

                        if ($number !== false && isset($paramNames[$tokens[$number]['content']]) === false) {
                            // Requesting non-named additional parameters. Ignore.
                            continue ;
                        }

                        // Slice starts at a named argument, but we know which params are being accessed.
                        $paramNamesSubset = \array_slice($paramNames, $tokens[$number]['content']);
                    }
                }
            }

            /*
             * For debug_backtrace(), check if the result is being dereferenced and if so,
             * whether the `args` index is used.
             * I.e. whether `$index` in `debug_backtrace()[$stackFrame][$index]` is a string
             * with the content `args`.
             *
             * Note: We already know that $next is the open parenthesis of the function call.
             */
            if ($foundFunctionName === 'debug_backtrace' && isset($tokens[$next]['parenthesis_closer'])) {
                $afterParenthesis = $phpcsFile->findNext(
                    Tokens::$emptyTokens,
                    ($tokens[$next]['parenthesis_closer'] + 1),
                    null,
                    true
                );

                if ($tokens[$afterParenthesis]['code'] === \T_OPEN_SQUARE_BRACKET
                    && isset($tokens[$afterParenthesis]['bracket_closer'])
                ) {
                    $afterStackFrame = $phpcsFile->findNext(
                        Tokens::$emptyTokens,
                        ($tokens[$afterParenthesis]['bracket_closer'] + 1),
                        null,
                        true
                    );

                    if ($tokens[$afterStackFrame]['code'] === \T_OPEN_SQUARE_BRACKET
                        && isset($tokens[$afterStackFrame]['bracket_closer'])
                    ) {
                        $arrayIndex = $phpcsFile->findNext(
                            \T_CONSTANT_ENCAPSED_STRING,
                            ($afterStackFrame + 1),
                            $tokens[$afterStackFrame]['bracket_closer']
                        );

                        if ($arrayIndex !== false && $this->stripQuotes($tokens[$arrayIndex]['content']) !== 'args') {
                            continue;
                        }
                    }
                }
            }

            /*
             * Only check for variables before the start of the statement to
             * prevent false positives on the return value of the function call
             * being assigned to one of the parameters, i.e.:
             * `$param = func_get_args();`.
             */
            $startOfStatement = PHPCSHelper::findStartOfStatement($phpcsFile, $i, $this->ignoreForStartOfStatement);

            /*
             * Ok, so we've found one of the target functions in the right scope.
             * Now, let's check if any of the passed parameters were touched.
             */
            $scanResult = 'clean';
            for ($j = ($scopeOpener + 1); $j < $startOfStatement; $j++) {
                if (isset($this->skipPastNested[$tokens[$j]['type']])
                    && isset($tokens[$j]['scope_closer'])
                ) {
                    // Skip past nested structures.
                    $j = $tokens[$j]['scope_closer'];
                    continue;
                }

                if ($tokens[$j]['code'] !== \T_VARIABLE) {
                    continue;
                }

                if ($foundFunctionName === 'func_get_arg' && isset($argNumber)) {
                    if (isset($paramNames[$argNumber])
                        && $tokens[$j]['content'] !== $paramNames[$argNumber]
                    ) {
                        // Different param than the one requested by func_get_arg().
                        continue;
                    }
                } elseif ($foundFunctionName === 'func_get_args' && isset($paramNamesSubset)) {
                    if (\in_array($tokens[$j]['content'], $paramNamesSubset, true) === false) {
                        // Different param than the ones requested by func_get_args().
                        continue;
                    }
                } elseif (\in_array($tokens[$j]['content'], $paramNames, true) === false) {
                    // Variable is not one of the function parameters.
                    continue;
                }

                /*
                 * Ok, so we've found a variable which was passed as one of the parameters.
                 * Now, is this variable being changed, i.e. incremented, decremented or
                 * assigned something ?
                 */
                $scanResult = 'warning';
                if (isset($variableToken) === false) {
                    $variableToken = $j;
                }

                $beforeVar = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($j - 1), null, true);
                if ($beforeVar !== false && isset($this->plusPlusMinusMinus[$tokens[$beforeVar]['code']])) {
                    // Variable is being (pre-)incremented/decremented.
                    $scanResult    = 'error';
                    $variableToken = $j;
                    break;
                }

                $afterVar = $phpcsFile->findNext(Tokens::$emptyTokens, ($j + 1), null, true);
                if ($afterVar === false) {
                    // Shouldn't be possible, but just in case.
                    continue;
                }

                if (isset($this->plusPlusMinusMinus[$tokens[$afterVar]['code']])) {
                    // Variable is being (post-)incremented/decremented.
                    $scanResult    = 'error';
                    $variableToken = $j;
                    break;
                }

                if ($tokens[$afterVar]['code'] === \T_OPEN_SQUARE_BRACKET
                    && isset($tokens[$afterVar]['bracket_closer'])
                ) {
                    // Skip past array access on the variable.
                    while (($afterVar = $phpcsFile->findNext(Tokens::$emptyTokens, ($tokens[$afterVar]['bracket_closer'] + 1), null, true)) !== false) {
                        if ($tokens[$afterVar]['code'] !== \T_OPEN_SQUARE_BRACKET
                            || isset($tokens[$afterVar]['bracket_closer']) === false
                        ) {
                            break;
                        }
                    }
                }

                if ($afterVar !== false
                    && isset(Tokens::$assignmentTokens[$tokens[$afterVar]['code']])
                ) {
                    // Variable is being assigned something.
                    $scanResult    = 'error';
                    $variableToken = $j;
                    break;
                }
            }

            unset($argNumber, $paramNamesSubset);

            if ($scanResult === 'clean') {
                continue;
            }

            $error = 'Since PHP 7.0, functions inspecting arguments, like %1$s(), no longer report the original value as passed to a parameter, but will instead provide the current value. The parameter "%2$s" was %4$s on line %3$s.';
            $data  = array(
                $foundFunctionName,
                $tokens[$variableToken]['content'],
                $tokens[$variableToken]['line'],
            );

            if ($scanResult === 'error') {
                $data[] = 'changed';
                $phpcsFile->addError($error, $i, 'Changed', $data);

            } elseif ($scanResult === 'warning') {
                $data[] = 'used, and possibly changed (by reference),';
                $phpcsFile->addWarning($error, $i, 'NeedsInspection', $data);
            }

            unset($variableToken);
        }
    }