Pular para o conteúdo

PHP API

Greph\Greph

A classe Greph\Greph é o ponto de entrada estático. Ela disponibiliza todas as operações de pesquisa, reescrita e indexação. Todos os métodos aceitam um único caminho ou uma lista de caminhos.

PHP
use Greph\Greph;

walk

PHP
public static function walk(string|array $paths, ?WalkOptions $options = null): FileList

Resolve $paths em uma FileList plana de caminhos absolutos de arquivos. Respeita gitignore, .grephignore, filtros de tipo de arquivo, padrões glob, inclusão de arquivos ocultos, seguimento de links simbólicos, detecção de binários e o limite máximo de tamanho de arquivo.

PHP
use Greph\Walker\WalkOptions;
use Greph\Walker\FileTypeFilter;

$files = Greph::walk('src', new WalkOptions(
    fileTypeFilter: new FileTypeFilter(['php']),
));

foreach ($files->paths() as $path) {
    echo "$path\n";
}

searchText

PHP
public static function searchText(
    string $pattern,
    string|array $paths,
    ?TextSearchOptions $options = null,
): array

Executa uma pesquisa de texto e retorna um list<TextFileResult>. Cada TextFileResult expõe o caminho do arquivo e uma lista de objetos TextMatch (linha, coluna, conteúdo, capturas, contexto opcional).

PHP
use Greph\Greph;
use Greph\Text\TextSearchOptions;

$results = Greph::searchText(
    'function',
    'src',
    new TextSearchOptions(
        fixedString: true,
        caseInsensitive: true,
        beforeContext: 1,
        afterContext: 1,
        jobs: 4,
    ),
);

foreach ($results as $file) {
    foreach ($file->matches as $match) {
        echo "{$file->file}:{$match->line}:{$match->content}\n";
    }
}

Quando jobs > 1 e a quantidade de arquivos ultrapassam o limite de trabalhadores, searchText encaminha automaticamente a varredura para um WorkerPool. Caso contrário, ela é executada no próprio processo.


searchAst

PHP
public static function searchAst(
    string $pattern,
    string|array $paths,
    ?AstSearchOptions $options = null,
): array

Executa uma pesquisa estrutural de AST e retorna um list<AstMatch>. Os padrões são escritos como código-fonte PHP com metavariáveis $VAR e $$$VARIADIC. Cada AstMatch inclui o arquivo, o PhpParser\Node capturado, as capturas, os deslocamentos de linha e byte inicial e final e o trecho de código-fonte correspondente.

PHP
use Greph\Greph;
use Greph\Ast\AstSearchOptions;

$matches = Greph::searchAst(
    'new $CLASS()',
    'src',
    new AstSearchOptions(),
);

foreach ($matches as $match) {
    echo "{$match->file}:{$match->startLine}:{$match->code}\n";
}

rewriteAst

PHP
public static function rewriteAst(
    string $searchPattern,
    string $rewritePattern,
    string|array $paths,
    ?AstSearchOptions $options = null,
): array

Executa uma reescrita estrutural e retorna um list<RewriteResult>. Cada RewriteResult expõe o caminho do arquivo, o conteúdo original, o conteúdo reescrito e a quantidade de substituições. As reescritas preservam a formatação: apenas os intervalos dos nós correspondentes são substituídos; o restante do arquivo permanece intacto.

PHP
$rewrites = Greph::rewriteAst(
    'array($$$ITEMS)',
    '[$$$ITEMS]',
    'src',
);

foreach ($rewrites as $result) {
    if ($result->changed()) {
        file_put_contents($result->file, $result->rewrittenContents);
    }
}

A fachada não grava em disco; quem chama decide se aplica as alterações. CLI as aplica, a menos que --dry-run ou --interactive esteja definido.


buildTextIndex

PHP
public static function buildTextIndex(
    string $rootPath = '.',
    ?string $indexPath = null,
    IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): IndexBuildResult

Cria um novo índice de trigramas e postings de identificadores para $rootPath. O índice é armazenado em $indexPath (o padrão é $rootPath/.greph-index). $lifecycle pode ser static, manual-refresh, opportunistic-refresh ou strict-stale-check. Retorna um IndexBuildResult com a quantidade de arquivos, trigramas e itens adicionados, atualizados, excluídos ou inalterados.

refreshTextIndex

PHP
public static function refreshTextIndex(
    string $rootPath = '.',
    ?string $indexPath = null,
    IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): IndexBuildResult

Atualiza incrementalmente um índice de texto existente. Os arquivos são submetidos a novo hash e apenas as entradas alteradas são reescritas.

searchTextIndexed

PHP
public static function searchTextIndexed(
    string $pattern,
    string|array $paths,
    ?TextSearchOptions $options = null,
    ?string $indexPath = null,
): array

Executa uma pesquisa de texto usando o índice carregado. Gera um erro de runtime se o índice não existir (execute buildTextIndex primeiro). Retorna um list<TextFileResult> com o mesmo formato de searchText.

PHP
Greph::buildTextIndex('.');
$results = Greph::searchTextIndexed('function', 'src');

searchTextIndexedMany

PHP
public static function searchTextIndexedMany(
    string $pattern,
    string|array $paths,
    array $indexPaths,
    ?TextSearchOptions $options = null,
): array

Executa pesquisas de texto usando índices carregados em vários diretórios. Greph pesquisa em cada índice aplicável, elimina duplicatas pelo caminho absoluto do arquivo e só recorre à varredura nativa para caminhos fora das raízes de todos os índices fornecidos.

loadIndexSet

PHP
public static function loadIndexSet(?string $manifestPath = null): IndexSet

Carrega um manifesto de conjuntos de índices, usando .greph-index-set.json como padrão no diretório de trabalho atual.

searchTextIndexedSet

PHP
public static function searchTextIndexedSet(
    string $pattern,
    string|array $paths,
    ?TextSearchOptions $options = null,
    ?string $manifestPath = null,
    array $entryNames = [],
): array

Resolve as entradas text selecionadas de um manifesto de conjuntos de índices e executa o equivalente a searchTextIndexedMany.


buildAstIndex / refreshAstIndex

PHP
public static function buildAstIndex(
    string $rootPath = '.',
    ?string $indexPath = null,
    IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): AstIndexBuildResult
public static function refreshAstIndex(
    string $rootPath = '.',
    ?string $indexPath = null,
    IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): AstIndexBuildResult

Cria ou atualiza incrementalmente o índice de fatos de AST. Por padrão, armazena os fatos extraídos em $rootPath/.greph-ast-index.

searchAstIndexed

PHP
public static function searchAstIndexed(
    string $pattern,
    string|array $paths,
    ?AstSearchOptions $options = null,
    ?string $indexPath = null,
): array

Usa o índice de fatos para reduzir os candidatos antes de verificar novamente as correspondências no código-fonte. Retorna um list<AstMatch> com o mesmo formato de searchAst.

searchAstIndexedMany

PHP
public static function searchAstIndexedMany(
    string $pattern,
    string|array $paths,
    array $indexPaths,
    ?AstSearchOptions $options = null,
): array

Executa pesquisas de fatos de AST usando índices carregados em vários diretórios de índices de AST.

searchAstIndexedSet

PHP
public static function searchAstIndexedSet(
    string $pattern,
    string|array $paths,
    ?AstSearchOptions $options = null,
    ?string $manifestPath = null,
    array $entryNames = [],
): array

Resolve as entradas ast-index selecionadas de um manifesto de conjuntos de índices e executa o equivalente a searchAstIndexedMany.

buildAstCache / refreshAstCache

PHP
public static function buildAstCache(
    string $rootPath = '.',
    ?string $indexPath = null,
    IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): AstCacheBuildResult
public static function refreshAstCache(
    string $rootPath = '.',
    ?string $indexPath = null,
    IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): AstCacheBuildResult

Cria ou atualiza incrementalmente o armazenamento em cache de árvores analisadas. Por padrão, armazena árvores serializadas em $rootPath/.greph-ast-cache.

searchAstCached

PHP
public static function searchAstCached(
    string $pattern,
    string|array $paths,
    ?AstSearchOptions $options = null,
    ?string $indexPath = null,
): array

Executa uma pesquisa de AST nas árvores analisadas em cache, ignorando totalmente o analisador. Retorna um list<AstMatch> com o mesmo formato de searchAst.

searchAstCachedMany

PHP
public static function searchAstCachedMany(
    string $pattern,
    string|array $paths,
    array $indexPaths,
    ?AstSearchOptions $options = null,
): array

Executa pesquisas de AST em cache usando vários diretórios de cache.

searchAstCachedSet

PHP
public static function searchAstCachedSet(
    string $pattern,
    string|array $paths,
    ?AstSearchOptions $options = null,
    ?string $manifestPath = null,
    array $entryNames = [],
): array

Resolve as entradas ast-cache selecionadas de um manifesto de conjuntos de índices e executa o equivalente a searchAstCachedMany.


Greph\Text\TextSearchOptions

Objeto imutável de opções para pesquisa de texto.

PHP
new TextSearchOptions(
    bool $fixedString = false,
    bool $caseInsensitive = false,
    bool $wholeWord = false,
    bool $invertMatch = false,
    ?int $maxCount = null,
    int $beforeContext = 0,
    int $afterContext = 0,
    bool $countOnly = false,
    bool $filesWithMatches = false,
    bool $filesWithoutMatches = false,
    bool $jsonOutput = false,
    bool $tracePlan = false,
    int $jobs = 1,
    bool $respectIgnore = true,
    bool $includeHidden = false,
    bool $followSymlinks = false,
    bool $skipBinaryFiles = true,
    bool $includeGitDirectory = false,
    ?FileTypeFilter $fileTypeFilter = null,
    int $maxFileSizeBytes = 10485760,
    array $globPatterns = [],
    bool $showLineNumbers = true,
    bool $showFileNames = true,
)

Validação:

  • jobs >= 1
  • beforeContext, afterContext >= 0
  • maxCount === null || maxCount >= 1

Use walkOptions() para obter o WalkOptions correspondente se quiser percorrer a árvore de arquivos separadamente.

tracePlan é usado pelos mecanismos de pesquisa com índices carregados, e os fluxos de greph-index CLI para emitir diagnósticos do planejador para stderr. O próprio searchText nativo não o utiliza.


Greph\Ast\AstSearchOptions

Objeto imutável de opções para pesquisa e reescrita de AST.

PHP
new AstSearchOptions(
    string $language = 'php',
    int $jobs = 1,
    bool $respectIgnore = true,
    bool $includeHidden = false,
    bool $followSymlinks = false,
    bool $skipBinaryFiles = true,
    bool $includeGitDirectory = false,
    ?FileTypeFilter $fileTypeFilter = null,
    int $maxFileSizeBytes = 10485760,
    array $globPatterns = [],
    bool $skipParseErrors = true,
    bool $dryRun = false,
    bool $interactive = false,
    bool $jsonOutput = false,
    bool $tracePlan = false,
)

O filtro padrão de tipo de arquivo para o modo AST é php. Quando skipParseErrors é true (padrão), arquivos que não podem ser analisados são ignorados silenciosamente; altere para false para apresentar erros de análise como exceções. tracePlan é usado pelos mecanismos de pesquisa de AST com índices carregados e greph-index ast-index|ast-cache search para emitir diagnósticos de eliminação de candidatos.


Greph\Walker\WalkOptions

Objeto imutável de opções para o percorridor de arquivos.

PHP
new WalkOptions(
    bool $respectIgnore = true,
    bool $includeHidden = false,
    bool $followSymlinks = false,
    bool $skipBinaryFiles = false,
    bool $includeGitDirectory = false,
    ?FileTypeFilter $fileTypeFilter = null,
    int $maxFileSizeBytes = 10485760,
    array $globPatterns = [],
)

Greph\Walker\FileTypeFilter

Resolve tipos de arquivo nomeados em listas de extensões. Aliases integrados:

Alias Extensões
css css, sass, scss
html htm, html, phtml
js cjs, js, mjs
json json
md markdown, md
php inc, php, php3, php4, php5, php7, php8, phpt, phtml
txt txt
ts ts, tsx
xml xml
yaml yaml, yml
PHP
new FileTypeFilter(includeTypes: ['php'], excludeTypes: ['md']);

Objetos de resultado

Greph\Text\TextFileResult

PHP
final readonly class TextFileResult
{
    public string $file;
    /** @var list<TextMatch> */
    public array $matches;

    public function matchCount(): int;
    public function hasMatches(): bool;
}

Greph\Text\TextMatch

PHP
final readonly class TextMatch
{
    public string $file;
    public int $line;
    public int $column;
    public string $content;
    public string $matchedText;
    /** @var array<int|string, string> */
    public array $captures;
    /** @var list<array{line: int, content: string}> */
    public array $beforeContext;
    /** @var list<array{line: int, content: string}> */
    public array $afterContext;
}

Greph\Ast\AstMatch

PHP
final readonly class AstMatch
{
    public string $file;
    public PhpParser\Node $node;
    /** @var array<string, mixed> */
    public array $captures;
    public int $startLine;
    public int $endLine;
    public int $startFilePos;
    public int $endFilePos;
    public string $code;
}

Greph\Ast\RewriteResult

PHP
final readonly class RewriteResult
{
    public string $file;
    public string $originalContents;
    public string $rewrittenContents;
    public int $replacementCount;

    public function changed(): bool;
}

Greph\Index\IndexBuildResult

PHP
final readonly class IndexBuildResult
{
    public string $rootPath;
    public string $indexPath;
    public int $fileCount;
    public int $trigramCount;
    public int $addedFiles;
    public int $updatedFiles;
    public int $deletedFiles;
    public int $unchangedFiles;
}

AstIndexBuildResult e AstCacheBuildResult seguem a mesma estrutura, com factCount e cachedTreeCount substituídos, respectivamente.


Exceções

Greph lança três exceções tipadas, todas em Greph\Exceptions:

Exceção Quando é lançada
WalkerException Erros do sistema de arquivos durante a travessia (caminho inexistente, diretório ilegível)
PatternException Expressão regular ou padrão AST inválido
ParseException Não foi possível analisar o código-fonte de PHP (somente quando skipParseErrors: false)

Os métodos de pesquisa indexada lançam \RuntimeException quando não há índice no local solicitado. O greph-index CLI oferece uma opção --fallback scan que captura essas exceções e recorre a uma varredura sem índice.