getNamespaceUseDeclarations.

@param Tokens $tokens
@param array  $useIndexes
505409
private function getNamespaceUseDeclarations(Tokens $tokens, array $useIndexes)
    {
        $uses = array();

        foreach ($useIndexes as $index) {
            $declarationEndIndex = $tokens->getNextTokenOfKind($index, array(';'));
            $declarationContent = $tokens->generatePartialCode($index + 1, $declarationEndIndex - 1);

            // ignore multiple use statements like: `use BarB, BarC as C, BarD;`
            // that should be split into few separate statements
            if (false !== strpos($declarationContent, ',')) {
                continue;
            }

            $declarationParts = preg_split('/\s+as\s+/i', $declarationContent);

            if (1 === count($declarationParts)) {
                $fullName = $declarationContent;
                $declarationParts = explode('\\', $fullName);
                $shortName = end($declarationParts);
                $aliased = false;
            } else {
                $fullName = $declarationParts[0];
                $shortName = $declarationParts[1];
                $declarationParts = explode('\\', $fullName);
                $aliased = $shortName !== end($declarationParts);
            }

            $shortName = trim($shortName);

            $uses[$shortName] = array(
                'aliased' => $aliased,
                'end' => $declarationEndIndex,
                'fullName' => trim($fullName),
                'shortName' => $shortName,
                'start' => $index,
            );
        }

        return $uses;
    }
823601
private function getNamespaceDeclarations(Tokens $tokens)
    {
        $namespaces = array();

        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(T_NAMESPACE)) {
                continue;
            }

            $declarationEndIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));

            $namespaces[] = array(
                'end' => $declarationEndIndex,
                'name' => trim($tokens->generatePartialCode($index + 1, $declarationEndIndex - 1)),
                'start' => $index,
            );
        }

        return $namespaces;
    }
1072698
protected function getNamespace($key, array $tokens)
    {
        $namespace = null;
        $tokenCount = count($tokens);
        for ($i = $key; $i < $tokenCount; $i++) {
            if ($this->isPartOfNamespace($tokens[$i])) {
                $namespace .= $tokens[$i][1];
            } elseif ($tokens[$i] == ';') {
                return $namespace;
            }
        }
    }
77178
private function activeNamespace(int $tokenID): string
    {
        foreach ($this->namespaces as $namespace => $position) {
            if ($tokenID >= $position[self::O_TOKEN] && $tokenID <= $position[self::C_TOKEN]) {
                return $namespace;
            }
        }

        //Seems like no namespace declaration
        $this->namespaces[''] = [
            self::O_TOKEN => 0,
            self::C_TOKEN => count($this->tokens),
            self::N_USES  => [],
        ];

        return '';
    }
898852
private function extractUseStatement(\ArrayIterator $tokens)
    {
        $result = [''];
        while ($tokens->valid()
            && (self::T_LITERAL_USE_SEPARATOR !== $tokens->current()[0])
            && (self::T_LITERAL_END_OF_USE !== $tokens->current()[0])
        ) {
            if (T_AS === $tokens->current()[0]) {
                $result[] = '';
            }
            if (T_STRING === $tokens->current()[0] || T_NS_SEPARATOR === $tokens->current()[0]) {
                $result[\count($result) - 1] .= $tokens->current()[1];
            }
            $tokens->next();
        }

        if (1 == \count($result)) {
            $backslashPos = strrpos($result[0], '\\');

            if (false !== $backslashPos) {
                $result[] = substr($result[0], $backslashPos + 1);
            } else {
                $result[] = $result[0];
            }
        }

        return array_reverse($result);
    }
475682
public static function alias(array $tokens) {
        $column     = self::column($tokens, new MetaData());
        $tableAlias = Table::alias($tokens);

        return empty($tableAlias) ? $column : $tableAlias . '.' . $column;
    }
589860
private function nextToken(&$tokens, $context)
    {
        while (true) {
            $token = next($tokens);
            if ($token[0] === T_WHITESPACE) {
                continue;
            }
            if ($token[0] === T_COMMENT) {
                $pos = strpos($token[1], '@OA\\');
                if ($pos) {
                    $line = $context->line ? $context->line + $token[2] : $token[2];
                    $commentContext = new Context(['line' => $line], $context);
                    Logger::notice('Annotations are only parsed inside `/**` DocBlocks, skipping ' . $commentContext);
                }
                continue;
            }

            return $token;
        }
    }
676017
protected function getRequiredUseClasses(array $fields, array $additions = [])
    {
        $commands = [];

        foreach ($additions as $addition) {
            $commands[] = $this->getUseClassCommand($addition);
        }

        $collections = $this->getRelationCollections($fields, 'form');

        foreach ($collections as $collection) {
            $command = $this->getUseClassCommand($collection->getFullForeignModel());

            if (!in_array($command, $commands)) {
                $commands[] = $this->getUseClassCommand($collection->getFullForeignModel());
            }
        }

        // Attempt to include classes that don't start with \\ with using command.
        foreach ($fields as $field) {
            if (!empty($field->onStore) && !in_array($field->onStore, $commands)) {
                $commands[] = $this->extractNamespace($field->onStore);
            }

            if (!empty($field->onUpdate) && !in_array($field->onUpdate, $commands)) {
                $commands[] = $this->extractNamespace($field->onUpdate);
            }
            // Extract the name spaces fromt he custom rules
            $customRules = $this->extractCustomValidationRules($field->getValidationRule());
            $namespaces = $this->extractCustomValidationNamespaces($customRules);
            foreach ($namespaces as $namespace) {
                $commands[] = $this->getUseClassCommand($namespace);
            }
        }

        usort($commands, function ($a, $b) {
            return strlen($a) - strlen($b);
        });

        return implode(PHP_EOL, array_unique($commands));
    }
115998
private function checkDeclaration(int $usePos): void
    {
        $file = $this->getFile()->getBaseFile();

        if (TokenHelper::findNextLocal($file, T_COMMA, $usePos + 1)) {
            $endPos = TokenHelper::findNext($file, [T_OPEN_CURLY_BRACKET, T_SEMICOLON], $usePos + 1);
            $tokens = $file->getTokens();

            if ($tokens[$endPos]['code'] === T_OPEN_CURLY_BRACKET) {
                $file->addError(
                    self::MESSAGE_MULTIPLE_TRAITS_PER_DECLARATION,
                    $usePos,
                    static::CODE_MULTIPLE_TRAITS_PER_DECLARATION
                );
            } else {
                $fix = $file->addFixableError(
                    self::MESSAGE_MULTIPLE_TRAITS_PER_DECLARATION,
                    $usePos,
                    static::CODE_MULTIPLE_TRAITS_PER_DECLARATION
                );

                if ($fix) {
                    $this->fixeUse($endPos, $usePos);
                }
            }
        }
    }
514213
private function getIndentationForFix(int $usePos): string
    {
        $file = $this->getFile()->getBaseFile();
        $indentation = '';
        $currentPointer = $usePos - 1;
        $tokens = $file->getTokens();

        while ($tokens[$currentPointer]['code'] === T_WHITESPACE &&
            $tokens[$currentPointer]['content'] !== $file->eolChar) {
            $indentation .= $tokens[$currentPointer]['content'];
            $currentPointer--;
        }

        return $indentation;
    }
152979
public function extractClassNameFromUse(string $use)
    {
        $matches = [];

        if (preg_match(self::USE_CLASS_EXTRACT_REGEXP, $use, $matches) === 0) {
            throw new InvalidNamespaceException($use);
        }

        $className = $matches['classname'];
        $namespace = array_key_exists('namespace', $matches) ? $matches['namespace'] : '';

        if (substr($namespace, -1, 1) === '\\') {
            $namespace = substr($namespace, 0, -1);
        }

        return [
            $className,
            $namespace
        ];
    }
1367179
private function cleanupGroupDelimiters(array &$tokens)
    {
        $indexes = $this->getUnmatchedGroupDelimiterIndexes($tokens);

        while (!empty($indexes)) {
            $lastIndex = array_pop($indexes);
            $token = $tokens[$lastIndex];
            unset($tokens[$lastIndex]);

            if ($token->type === Tokenizer::TOKEN_GROUP_BEGIN) {
                $this->addCorrection(
                    self::CORRECTION_UNMATCHED_GROUP_LEFT_DELIMITER_IGNORED,
                    $token
                );
            } else {
                $this->addCorrection(
                    self::CORRECTION_UNMATCHED_GROUP_RIGHT_DELIMITER_IGNORED,
                    $token
                );
            }
        }
    }
1145641
public static function getNamespace($tokens)
    {
        $count = count($tokens);
        $i = 0;
        $namespace = '';
        $namespace_ok = false;
        while ($i < $count) {
            $token = $tokens[$i];
            if (is_array($token) && $token[0] === T_NAMESPACE) {
                // Found namespace declaration
                while (++$i < $count) {
                    if ($tokens[$i] === ';') {
                        $namespace_ok = true;
                        $namespace = trim($namespace);
                        break;
                    }
                    $namespace .= is_array($tokens[$i]) ? $tokens[$i][1] : $tokens[$i];
                }
                break;
            }
            $i++;
        }
        if (!$namespace_ok) {
            return null;
        } else {
            return $namespace;
        }
    }
1016792
public function createFromTokensAndStart(Tokens $tokens, int $start): Name
    {
        $nameTokens = [];

        $nextTokenPointer = $start;

        $prependNamespace = $this->shouldPrependNamespace($tokens, $nextTokenPointer);

        while ($tokens[$nextTokenPointer]->isGivenKind([T_NS_SEPARATOR, T_STRING])) {
            $nameTokens[] = $tokens[$nextTokenPointer];
            ++$nextTokenPointer;
        }

        /** @var Token[] $nameTokens */
        if ($nameTokens[0]->isGivenKind(T_NS_SEPARATOR)) {
            unset($nameTokens[0]);
            // reset array keys
            $nameTokens = array_values($nameTokens);

            // move start pointer after "\"
            --$nextTokenPointer;
        }

        if (! $tokens[$nextTokenPointer]->isGivenKind([T_STRING, T_NS_SEPARATOR])) {
            --$nextTokenPointer;
        }

        $name = '';
        foreach ($nameTokens as $nameToken) {
            $name .= $nameToken->getContent();
        }

        // resolve fully qualified name - as argument?
        $name = $this->resolveForName($tokens, $name, $prependNamespace);

        return new Name($nextTokenPointer, $start, $name, $tokens);
    }
966725
protected function extractNamespace(array $tokens) : string {
    $namespace = '';
    $found = FALSE;
    foreach ($tokens as $token) {
      if (is_array($token) && $token[0] == T_NAMESPACE) {
        $found = TRUE;
      }
      if (is_array($token) && ($token[0] == T_NS_SEPARATOR || $token[0] == T_STRING)) {
        $namespace .= $token[1];
      }
      elseif ($found && $token == ';') {
        return $namespace;
      }
    }
    return $namespace;
  }
266593
private function grabAttribsBeforePropertyToken(Tokens $tokens, $index)
    {
        static $tokenAttribsMap = [
            T_VAR       => null, // destroy T_VAR token!
            T_PRIVATE   => 'visibility',
            T_PROTECTED => 'visibility',
            T_PUBLIC    => 'visibility',
            T_STATIC    => 'static',
        ];

        $result = $this->grabAttribsBeforeToken(
            $tokens,
            $index,
            $tokenAttribsMap,
            [
                'visibility' => new Token([T_PUBLIC, 'public']),
                'static'     => null,
            ]
        );
        if ($result['visibility'] && 'public' === $result['visibility']->getContent()) {
            // If visibility is public and static is set, we remove visibility.
            if ($result['static']) {
                $result['visibility'] = null;
            }
        }
        return $result;
    }
464418
public function getNamespaces()
	{
		$namespaces = $this->instance->getInstanceNamespaces();

		$usedNamespaces = array_reduce( $this->elements, function( $carry, $element ) use( $namespaces ) {

			foreach ( $element as $key => $entry )
			{
				$namespace = isset( $namespaces[ $entry['namespace'] ] ) ? $namespaces[ $entry['namespace'] ] : $entry['namespace'];
				if ( ! isset( $carry[ $namespace ] ) )
					$carry[ $namespace ] = 1;
			}

			return $carry;
		}, array() );

		return array_keys( $usedNamespaces );
	}