PHP API
Greph\Greph
Třída Greph\Greph je statickým vstupním bodem. Zpřístupňuje všechny operace vyhledávání, přepisování a indexování. Všechny metody přijímají jednu cestu nebo seznam cest.
use Greph\Greph;
walk
public static function walk(string|array $paths, ?WalkOptions $options = null): FileList
Převede $paths na plochý FileList absolutních cest k souborům. Respektuje gitignore, .grephignore, filtry typů souborů, vzory glob, zahrnutí skrytých souborů, následování symbolických odkazů, detekci binárních souborů a limit maximální velikosti souboru.
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
Provede textové vyhledávání a vrátí list<TextFileResult>. Každý TextFileResult zpřístupňuje cestu k souboru a seznam objektů TextMatch (řádek, sloupec, obsah, zachycené hodnoty a volitelný kontext).
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";
}
}
Pokud je jobs > 1 a počet souborů překročí limit pro pracovní procesy, searchText automaticky předá skenování fondu WorkerPool. Jinak se spustí v aktuálním procesu.
searchAst
public static function searchAst(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
): array
Provede strukturální vyhledávání AST a vrátí list<AstMatch>. Vzory se zapisují jako zdrojový kód PHP s metaproměnnými $VAR a $$$VARIADIC. Každý AstMatch obsahuje soubor, zachycený PhpParser\Node, zachycené hodnoty, počáteční a koncový řádek a bajtové posuny i odpovídající výřez zdrojového kódu.
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
Provede strukturální přepis a vrátí list<RewriteResult>. Každý RewriteResult zpřístupňuje cestu k souboru, původní obsah, přepsaný obsah a počet náhrad. Přepisy zachovávají formát: nahradí se pouze rozsahy odpovídajících uzlů, zbytek souboru zůstane nedotčen.
$rewrites = Greph::rewriteAst(
'array($$$ITEMS)',
'[$$$ITEMS]',
'src',
);
foreach ($rewrites as $result) {
if ($result->changed()) {
file_put_contents($result->file, $result->rewrittenContents);
}
}
Fasáda nezapisuje na disk; volající rozhoduje, zda změny použije. CLI je použije, pokud není nastaveno --dry-run nebo --interactive.
Indexované textové vyhledávání
buildTextIndex
public static function buildTextIndex(
string $rootPath = '.',
?string $indexPath = null,
IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): IndexBuildResult
Vytvoří nový index trigramů a výskytů identifikátorů pro $rootPath. Index se ukládá do $indexPath (výchozí hodnota je $rootPath/.greph-index). $lifecycle může být static, manual-refresh, opportunistic-refresh nebo strict-stale-check. Vrací IndexBuildResult s počtem souborů a trigramů a počty přidaných, aktualizovaných, odstraněných a nezměněných položek.
refreshTextIndex
public static function refreshTextIndex(
string $rootPath = '.',
?string $indexPath = null,
IndexLifecycle|IndexLifecycleProfile|string|null $lifecycle = null,
): IndexBuildResult
Postupně aktualizuje existující textový index. Soubory se znovu zahashují a znovu se zapíší pouze změněné položky.
searchTextIndexed
public static function searchTextIndexed(
string $pattern,
string|array $paths,
?TextSearchOptions $options = null,
?string $indexPath = null,
): array
Provede textové vyhledávání v zahřátém indexu. Pokud index neexistuje, skončí chybou za běhu (nejprve zavolejte buildTextIndex). Vrací list<TextFileResult> se stejnou strukturou jako searchText.
Greph::buildTextIndex('.');
$results = Greph::searchTextIndexed('function', 'src');
searchTextIndexedMany
public static function searchTextIndexedMany(
string $pattern,
string|array $paths,
array $indexPaths,
?TextSearchOptions $options = null,
): array
Provede textové vyhledávání v zahřátých indexech v několika adresářích. Greph prohledá každý použitelný index, odstraní duplicity podle absolutní cesty k souboru a nativní skenování použije pouze pro cesty mimo všechny zadané kořenové adresáře indexů.
loadIndexSet
public static function loadIndexSet(?string $manifestPath = null): IndexSet
Načte manifest sady indexů; výchozí hodnota je .greph-index-set.json v aktuálním pracovním adresáři.
searchTextIndexedSet
public static function searchTextIndexedSet(
string $pattern,
string|array $paths,
?TextSearchOptions $options = null,
?string $manifestPath = null,
array $entryNames = [],
): array
Z manifestu sady indexů vybere položky text a provede operaci ekvivalentní searchTextIndexedMany.
Indexované vyhledávání AST
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
Vytvoří nebo postupně aktualizuje index faktů AST. Ve výchozím nastavení ukládá extrahovaná fakta do $rootPath/.greph-ast-index.
searchAstIndexed
public static function searchAstIndexed(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
?string $indexPath = null,
): array
Pomocí indexu faktů zúží množinu kandidátů a poté znovu ověří shody vůči zdrojovému kódu. Vrací strukturu list<AstMatch> stejnou jako searchAst.
searchAstIndexedMany
public static function searchAstIndexedMany(
string $pattern,
string|array $paths,
array $indexPaths,
?AstSearchOptions $options = null,
): array
Provede vyhledávání faktů AST v zahřátých indexech v několika adresářích indexů AST.
searchAstIndexedSet
public static function searchAstIndexedSet(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
?string $manifestPath = null,
array $entryNames = [],
): array
Z manifestu sady indexů vybere položky ast-index a provede operaci ekvivalentní 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
Vytvoří nebo postupně aktualizuje úložiště stromů po parsování. Ve výchozím nastavení ukládá serializované stromy do $rootPath/.greph-ast-cache.
searchAstCached
public static function searchAstCached(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
?string $indexPath = null,
): array
Provede vyhledávání AST nad stromovými strukturami uloženými v cache, takže parser vůbec nespouští. Vrací strukturu list<AstMatch> stejnou jako searchAst.
searchAstCachedMany
public static function searchAstCachedMany(
string $pattern,
string|array $paths,
array $indexPaths,
?AstSearchOptions $options = null,
): array
Provede vyhledávání v zahřáté cache AST v několika adresářích cache.
searchAstCachedSet
public static function searchAstCachedSet(
string $pattern,
string|array $paths,
?AstSearchOptions $options = null,
?string $manifestPath = null,
array $entryNames = [],
): array
Z manifestu sady indexů vybere položky ast-cache a provede operaci ekvivalentní searchAstCachedMany.
Greph\Text\TextSearchOptions
Objekt pouze pro čtení s možnostmi textového vyhledávání.
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,
)
Ověření:
jobs >= 1beforeContext, afterContext >= 0maxCount === null || maxCount >= 1
Chcete-li samostatně procházet strom souborů, použijte walkOptions() a odvoďte z něj odpovídající WalkOptions.
tracePlan využívají vyhledávače v zahřátých indexech a toky greph-index CLI slouží k výpisu diagnostiky plánovače do stderr. Samotné nativní searchText jej nepoužívá.
Greph\Ast\AstSearchOptions
Objekt pouze pro čtení s možnostmi vyhledávání a přepisování 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,
)
Výchozí filtr typů souborů pro režim AST je php. Pokud je skipParseErrors nastaveno na true (výchozí hodnota), soubory, které se nepodaří parsovat, se tiše přeskočí; nastavte false, aby se chyby při parsování vyvolávaly jako výjimky. tracePlan využívají vyhledávače AST v zahřátých indexech a greph-index ast-index|ast-cache search slouží k výpisu diagnostiky o vyřazování kandidátů.
Greph\Walker\WalkOptions
Objekt pouze pro čtení s možnostmi procházení souborů.
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
Převede pojmenované typy souborů na seznamy přípon. Vestavěné aliasy:
| Alias | Přípony |
|---|---|
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']);
Objekty výsledků
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 a AstCacheBuildResult mají stejný tvar, přičemž factCount a cachedTreeCount jsou dosazeny v tomto pořadí.
Výjimky
Greph vyvolává tři typované výjimky, všechny v Greph\Exceptions:
| Výjimka | Kdy je vyvolána |
|---|---|
WalkerException |
Chyby souborového systému při procházení (chybějící cesta, nečitelný adresář) |
PatternException |
Neplatný regulární výraz nebo vzor AST |
ParseException |
Zdrojový kód PHP se nepodařilo analyzovat (pouze když skipParseErrors: false) |
Metody indexovaného vyhledávání vyvolají \RuntimeException, pokud na požadovaném místě není žádný index. greph-index CLI nabízí volbu --fallback scan, která tyto chyby zachytí a místo toho přejde k prohledávání bez indexu.