PHP API
Greph\Greph
La clase Greph\Greph es el punto de entrada estático. Expone todas las operaciones de búsqueda, reescritura e indexación. Todos los métodos aceptan una ruta o una lista de rutas.
use Greph\Greph;
walk
public static function walk(string|array $paths, ?WalkOptions $options = null): FileList
Resuelve $paths en una lista plana FileList de rutas de archivo absolutas. Respeta gitignore, .grephignore, los filtros por tipo de archivo, los patrones glob, la inclusión de archivos ocultos, el seguimiento de enlaces simbólicos, la detección de binarios y el límite de tamaño máximo de archivo.
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
Ejecuta una búsqueda de texto y devuelve un list<TextFileResult>. Cada TextFileResult muestra la ruta del archivo y una lista de objetos TextMatch (línea, columna, contenido, capturas y 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";
}
}
Cuando jobs > 1 y la cantidad de archivos supera el umbral de trabajadores, searchText distribuye automáticamente el análisis a un WorkerPool. De lo contrario, se ejecuta en el mismo proceso.
searchAst
public static function searchAst(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
): array
Ejecuta una búsqueda estructural de AST y devuelve un list<AstMatch>. Los patrones se escriben como código fuente PHP con met variables $VAR y $$$VARIADIC. Cada AstMatch incluye el archivo, el PhpParser\Node capturado, las capturas, los números de línea de inicio y fin, las posiciones de bytes y el fragmento del código fuente que coincide.
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
Ejecuta una reescritura estructural y devuelve un list<RewriteResult>. Cada RewriteResult muestra la ruta del archivo, el contenido original, el contenido reescrito y el número de reemplazos. Las reescrituras conservan el formato: solo se sustituyen los rangos de nodos coincidentes; el resto del archivo permanece intacto.
$rewrites = Greph::rewriteAst(
'array($$$ITEMS)',
'[$$$ITEMS]',
'src',
);
foreach ($rewrites as $result) {
if ($result->changed()) {
file_put_contents($result->file, $result->rewrittenContents);
}
}
La fachada no escribe en el disco; quien llama decide si aplica los cambios. CLI los aplica, salvo que se establezca --dry-run o --interactive.
Búsqueda de texto indexado
buildTextIndex
public static function buildTextIndex(
string $rootPath = '.',
?string $indexPath = null,
IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): IndexBuildResult
Crea un índice nuevo de trigramas y publicaciones de identificadores para $rootPath. El índice se guarda en $indexPath (de forma predeterminada, en $rootPath/.greph-index). $lifecycle puede ser static, manual-refresh, opportunistic-refresh o strict-stale-check. Devuelve un IndexBuildResult con el recuento de archivos, el recuento de trigramas y los recuentos de elementos añadidos, actualizados, eliminados y sin cambios.
refreshTextIndex
public static function refreshTextIndex(
string $rootPath = '.',
?string $indexPath = null,
IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): IndexBuildResult
Actualiza de forma incremental un índice de texto existente. Vuelve a calcular los hashes de los archivos y solo reescribe las entradas que han cambiado.
searchTextIndexed
public static function searchTextIndexed(
string $pattern,
string|array $paths,
?TextSearchOptions $options = null,
?string $indexPath = null,
): array
Ejecuta una búsqueda de texto en el índice precargado. Si el índice no existe, devuelve un error en tiempo de ejecución (llame primero a buildTextIndex). Devuelve un list<TextFileResult> con la misma estructura que searchText.
Greph::buildTextIndex('.');
$results = Greph::searchTextIndexed('function', 'src');
searchTextIndexedMany
public static function searchTextIndexedMany(
string $pattern,
string|array $paths,
array $indexPaths,
?TextSearchOptions $options = null,
): array
Ejecuta una búsqueda de texto precargada en varios directorios de índices de texto. Greph busca en cada índice aplicable, elimina los duplicados por ruta absoluta del archivo y recurre al análisis nativo solo para las rutas que quedan fuera de todas las raíces de índices proporcionadas.
loadIndexSet
public static function loadIndexSet(?string $manifestPath = null): IndexSet
Carga un manifiesto de conjunto de índices; de forma predeterminada, carga .greph-index-set.json en el directorio de trabajo actual.
searchTextIndexedSet
public static function searchTextIndexedSet(
string $pattern,
string|array $paths,
?TextSearchOptions $options = null,
?string $manifestPath = null,
array $entryNames = [],
): array
Resuelve las entradas text seleccionadas de un manifiesto de conjunto de índices y ejecuta el equivalente de searchTextIndexedMany.
Búsqueda de AST indexado
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
Crea o actualiza de forma incremental el índice de datos de AST. De forma predeterminada, guarda los datos extraídos en $rootPath/.greph-ast-index.
searchAstIndexed
public static function searchAstIndexed(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
?string $indexPath = null,
): array
Usa el índice de datos para acotar los candidatos antes de volver a verificar las coincidencias con el código fuente. Devuelve el mismo formato de list<AstMatch> que searchAst.
searchAstIndexedMany
public static function searchAstIndexedMany(
string $pattern,
string|array $paths,
array $indexPaths,
?AstSearchOptions $options = null,
): array
Ejecuta una búsqueda de datos de AST precargados en varios directorios de índices de AST.
searchAstIndexedSet
public static function searchAstIndexedSet(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
?string $manifestPath = null,
array $entryNames = [],
): array
Resuelve las entradas ast-index seleccionadas de un manifiesto de conjunto de índices y ejecuta el equivalente de 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
Crea o actualiza de forma incremental el almacén de árboles sintácticos analizados en caché. De forma predeterminada, guarda los árboles serializados en $rootPath/.greph-ast-cache.
searchAstCached
public static function searchAstCached(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
?string $indexPath = null,
): array
Ejecuta una búsqueda de AST en los árboles sintácticos analizados en caché, sin pasar por el analizador. Devuelve el mismo formato de list<AstMatch> que searchAst.
searchAstCachedMany
public static function searchAstCachedMany(
string $pattern,
string|array $paths,
array $indexPaths,
?AstSearchOptions $options = null,
): array
Ejecuta una búsqueda de AST en caché precargada en varios directorios de caché.
searchAstCachedSet
public static function searchAstCachedSet(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
?string $manifestPath = null,
array $entryNames = [],
): array
Resuelve las entradas ast-cache seleccionadas de un manifiesto de conjunto de índices y ejecuta el equivalente de searchAstCachedMany.
Greph\Text\TextSearchOptions
Objeto de opciones de solo lectura para la búsqueda 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,
)
Validación:
jobs >= 1beforeContext, afterContext >= 0maxCount === null || maxCount >= 1
Use walkOptions() para obtener el WalkOptions correspondiente si quiere recorrer el árbol de archivos por separado.
tracePlan lo utilizan los buscadores de índices precargados y los flujos greph-index CLI para emitir diagnósticos del planificador en stderr. La búsqueda nativa con searchText no lo utiliza.
Greph\Ast\AstSearchOptions
Objeto de opciones de solo lectura para la búsqueda y reescritura 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,
)
El filtro de tipos de archivo predeterminado para el modo AST es php. Cuando skipParseErrors es true (valor predeterminado), se omiten silenciosamente los archivos que no se pueden analizar; cámbielo a false para que los errores de análisis aparezcan como excepciones. tracePlan lo utilizan los buscadores de AST precargados y greph-index ast-index|ast-cache search para emitir diagnósticos de reducción de candidatos.
Greph\Walker\WalkOptions
Objeto de opciones de solo lectura para el recorredor de archivos.
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
Resuelve los tipos de archivo con nombre en listas de extensiones. Alias integrados:
| Alias | Extensiones |
|---|---|
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 y AstCacheBuildResult siguen la misma estructura, sustituyendo respectivamente factCount y cachedTreeCount.
Excepciones
Greph lanza tres excepciones tipadas, todas en Greph\Exceptions:
| Excepción | Cuándo se lanza |
|---|---|
WalkerException |
Errores del sistema de archivos durante el recorrido (ruta inexistente, directorio ilegible) |
PatternException |
Expresión regular o patrón AST no válidos |
ParseException |
No se pudo analizar el código fuente de PHP (solo cuando skipParseErrors: false) |
Los métodos de búsqueda indexada lanzan \RuntimeException cuando no hay ningún índice en la ubicación solicitada. greph-index CLI ofrece una opción --fallback scan que captura estos errores y recurre a un análisis sin índice.