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.
use Greph\Greph;
walk
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.
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
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).
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
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.
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
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.
$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.
Pesquisa de texto indexada
buildTextIndex
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
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
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.
Greph::buildTextIndex('.');
$results = Greph::searchTextIndexed('function', 'src');
searchTextIndexedMany
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
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
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.
Pesquisa de AST indexada
buildAstIndex / refreshAstIndex
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
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
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
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
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
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
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
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.
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 >= 1beforeContext, afterContext >= 0maxCount === 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.
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.
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 |
new FileTypeFilter(includeTypes: ['php'], excludeTypes: ['md']);
Objetos de resultado
Greph\Text\TextFileResult
final readonly class TextFileResult
{
public string $file;
/** @var list<TextMatch> */
public array $matches;
public function matchCount(): int;
public function hasMatches(): bool;
}
Greph\Text\TextMatch
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
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
final readonly class RewriteResult
{
public string $file;
public string $originalContents;
public string $rewrittenContents;
public int $replacementCount;
public function changed(): bool;
}
Greph\Index\IndexBuildResult
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.