TokenNavigatorTrait.php

Code Hygiene Score: 100

Keine Issues gefunden.

Klassen 1

Funktionen 4

Verwendet von 1

Code

<?php

declare(strict_types=1);

namespace Infrastructure\CodeAnalysis;

// @responsibility: Token-Navigation für PHP-Tokenizer

/**
 * Trait for navigating PHP token arrays.
 *
 * Provides helper methods to find and extract tokens from
 * token arrays generated by token_get_all().
 */
trait TokenNavigatorTrait
{
    /**
     * Extract a type name starting from a position.
     *
     * @param array<mixed> $tokens
     */
    private function extractTypeName(array $tokens, int $startIndex): ?string
    {
        $count = count($tokens);

        for ($i = $startIndex; $i < $count; $i++) {
            $token = $tokens[$i];

            if (!is_array($token)) {
                continue;
            }

            if ($token[0] === T_WHITESPACE) {
                continue;
            }

            if (in_array($token[0], [T_STRING, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED], true)) {
                return $token[1];
            }

            // Stop at unexpected token
            break;
        }

        return null;
    }

    /**
     * Find next T_STRING token and return its value.
     *
     * @param array<mixed> $tokens
     */
    private function findNextString(array $tokens, int $startIndex): ?string
    {
        $count = count($tokens);

        for ($i = $startIndex + 1; $i < $count; $i++) {
            if (!is_array($tokens[$i])) {
                if ($tokens[$i] === '(') {
                    return null; // Anonymous function
                }

                continue;
            }

            if ($tokens[$i][0] === T_STRING) {
                return $tokens[$i][1];
            }

            if ($tokens[$i][0] !== T_WHITESPACE) {
                break;
            }
        }

        return null;
    }

    /**
     * Find previous non-whitespace token index.
     *
     * @param array<mixed> $tokens
     */
    private function findPrevNonWhitespace(array $tokens, int $index): ?int
    {
        for ($i = $index - 1; $i >= 0; $i--) {
            if (!is_array($tokens[$i]) || $tokens[$i][0] !== T_WHITESPACE) {
                return $i;
            }
        }

        return null;
    }

    /**
     * Find next non-whitespace token index.
     *
     * @param array<mixed> $tokens
     */
    private function findNextNonWhitespace(array $tokens, int $index): ?int
    {
        $count = count($tokens);

        for ($i = $index + 1; $i < $count; $i++) {
            if (!is_array($tokens[$i]) || $tokens[$i][0] !== T_WHITESPACE) {
                return $i;
            }
        }

        return null;
    }
}
← Übersicht Graph