Preskočiť na obsah

PHP API

Greph\Greph

Trieda Greph\Greph je statickým vstupným bodom. Sprístupňuje všetky operácie vyhľadávania, prepisovania a indexovania. Všetky metódy prijímajú jednu cestu alebo zoznam ciest.

PHP
use Greph\Greph;

walk

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

Preveďte $paths na plochý FileList absolútnych ciest k súborom. Zohľadňuje gitignore, .grephignore, filtre typov súborov, globové vzory, zahrnutie skrytých súborov, sledovanie symbolických odkazov, rozpoznávanie binárnych súborov a maximálny limit veľkosti súborov.

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

Spustite textové vyhľadávanie a vráťte list<TextFileResult>. Každý TextFileResult sprístupňuje cestu k súboru a zoznam objektov TextMatch (riadok, stĺpec, obsah, zachytené hodnoty, voliteľný kontext).

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";
    }
}

Keď je nastavené jobs > 1 a počet súborov prekročí prah pre pracovníkov, searchText automaticky odošle skenovanie do WorkerPool. Inak ho spustí v rámci procesu.


searchAst

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

Spustite štrukturálne vyhľadávanie AST a vráťte list<AstMatch>. Vzory sa zapisujú ako zdrojový kód PHP s metapremennými $VAR a $$$VARIADIC. Každý AstMatch obsahuje súbor, zachytené PhpParser\Node, zachytené hodnoty, posuny začiatku a konca v riadkoch a bajtoch a zodpovedajúci úsek zdrojového kódu.

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

Spustite štrukturálne prepisovanie a vráťte list<RewriteResult>. Každý RewriteResult sprístupňuje cestu k súboru, pôvodný obsah, prepísaný obsah a počet nahradení. Prepisovanie zachováva formátovanie: nahrádzajú sa iba rozsahy zodpovedajúcich uzlov, zvyšok súboru zostáva nedotknutý.

PHP
$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; o použití zmien rozhoduje volajúci. CLI ich použije, pokiaľ nie je nastavené --dry-run alebo --interactive.


buildTextIndex

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

Vytvorte nový index trigramov a výskytov identifikátorov pre $rootPath. Index sa uloží do $indexPath (predvolene $rootPath/.greph-index). $lifecycle môže byť static, manual-refresh, opportunistic-refresh alebo strict-stale-check. Vráti IndexBuildResult s počtom súborov, trigramov a počtami pridaných, aktualizovaných, odstránených a nezmenených položiek.

refreshTextIndex

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

Postupne obnovte existujúci textový index. Súbory sa znova hašujú a prepisujú sa iba zmenené položky.

searchTextIndexed

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

Spustite textové vyhľadávanie v zahriatom indexe. Ak index neexistuje, vráti chybu za behu (najprv zavolajte buildTextIndex). Vráti list<TextFileResult> s rovnakou štruktúrou ako 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

Spustite zahriate textové vyhľadávanie vo viacerých adresároch textových indexov. Greph prehľadá každý príslušný index, odstráni duplicitné výsledky podľa absolútnej cesty k súboru a natívne skenovanie použije iba pre cesty mimo všetkých zadaných koreňových adresárov indexov.

loadIndexSet

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

Načítajte manifest množiny indexov; predvolene sa použije .greph-index-set.json v aktuálnom pracovnom adresári.

searchTextIndexedSet

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

Vyriešte vybraté položky text z manifestu množiny indexov a spustite ekvivalent 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

Vytvorte alebo postupne obnovte index faktov AST. Extrahované fakty sa predvolene ukladajú do $rootPath/.greph-ast-index.

searchAstIndexed

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

Pomocou indexu faktov zúžte množinu kandidátov a potom znova overte zhody voči zdrojovému kódu. Vráti výsledok v rovnakej štruktúre list<AstMatch> ako searchAst.

searchAstIndexedMany

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

Spustite zahriate vyhľadávanie faktov AST vo viacerých adresároch indexov AST.

searchAstIndexedSet

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

Vyriešte vybraté položky ast-index z manifestu množiny indexov a spustite ekvivalent 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

Vytvorte alebo postupne obnovte úložisko stromov z vyrovnávacej pamäte. Serializované stromy sa predvolene ukladajú do $rootPath/.greph-ast-cache.

searchAstCached

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

Spustite vyhľadávanie AST nad stromami z vyrovnávacej pamäte a úplne preskočte parser. Vráti výsledok v rovnakej štruktúre list<AstMatch> ako searchAst.

searchAstCachedMany

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

Spustite zahriate vyhľadávanie v AST z vyrovnávacej pamäte vo viacerých adresároch vyrovnávacej pamäte.

searchAstCachedSet

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

Vyriešte vybrané položky ast-cache z manifestu množiny indexov a spustite ekvivalent searchAstCachedMany.


Greph\Text\TextSearchOptions

Objekt možností iba na čítanie pre textové vyhľadávanie.

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,
)

Overenie:

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

Pomocou walkOptions() odvodíte zodpovedajúce WalkOptions, ak chcete prechádzať strom súborov samostatne.

tracePlan používajú zahriate indexované vyhľadávače a toky greph-index CLI na odosielanie diagnostiky plánovača do stderr. Samotné natívne searchText ho nepoužíva.


Greph\Ast\AstSearchOptions

Objekt možností iba na čítanie pre vyhľadávanie a prepisovanie 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,
)

Predvolený filter typov súborov pre režim AST je php. Keď je skipParseErrors nastavené na true (predvolené), súbory, ktoré sa nepodarí parsovať, sa potichu preskočia; zmeňte hodnotu na false, aby sa chyby parsovania zobrazovali ako výnimky. tracePlan používajú zahriate vyhľadávače AST a greph-index ast-index|ast-cache search na vypisovanie diagnostiky o vyraďovaní kandidátov.


Greph\Walker\WalkOptions

Objekt možností iba na čítanie pre prechádzač súborov.

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

Preveďte pomenované typy súborov na zoznamy prípon. Vstavané aliasy:

Alias Prí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
PHP
new FileTypeFilter(includeTypes: ['php'], excludeTypes: ['md']);

Objekty výsledkov

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 a AstCacheBuildResult majú rovnaký tvar, pričom factCount a cachedTreeCount sú použité namiesto nich.


Výnimky

Greph vyvoláva tri typované výnimky, všetky v Greph\Exceptions:

Výnimka Kedy sa vyvolá
WalkerException Chyby súborového systému počas prechádzania (chýbajúca cesta, nečitateľný adresár)
PatternException Neplatný regulárny výraz alebo vzor AST
ParseException Zdrojový kód PHP sa nepodarilo parsovať (iba keď skipParseErrors: false)

Metódy indexovaného vyhľadávania vyvolajú \RuntimeException, keď sa na požadovanom mieste nenachádza index. Rozhranie greph-index CLI poskytuje možnosť --fallback scan, ktorá tieto výnimky zachytí a namiesto toho použije neindexované prehľadávanie.