
# PHP API

## `Greph\Greph`

Klass `Greph\Greph` on staatiline sisenemispunkt. See pakub kõiki otsingu-, ümberkirjutus- ja indekseerimistoiminguid. Kõik meetodid aktsepteerivad kas ühte teed või teede loendit.

```php
use Greph\Greph;
```

### `walk`

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

Lahendab `$paths` tasaseks absoluutsete failiteede `FileList`-ks. Järgib gitignore'i ja `.grephignore` reegleid ning failitüübi filtreid, glob-mustreid, peidetud failide kaasamist, sümbollinkide järgimist, binaarfailide tuvastamist ja faili suuruse ülempiiri.

```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
```

Käivitab tekstiotsingu ja tagastab `list<TextFileResult>`. Iga `TextFileResult` sisaldab failiteed ja objektide `TextMatch` loendit (rida, veerg, sisu, tabamused, valikuline kontekst).

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

Kui `jobs > 1` ja failide arv ületab tööprotsesside läve, suunab `searchText` skannimise automaatselt `WorkerPool`-le. Vastasel juhul käivitub see protsessisiseselt.

---

### `searchAst`

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

Käivitab struktuurse AST-otsingu ja tagastab `list<AstMatch>`. Mustrid kirjutatakse lähtekoodina PHP, kasutades metavariabeleid `$VAR` ja `$$$VARIADIC`. Iga `AstMatch` sisaldab faili, tabatud `PhpParser\Node`, tabamusi, algus- ja lõpurida, baidiofsette ning sobitatud lähtekoodilõiku.

```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
```

Käivitab struktuurse ümberkirjutuse ja tagastab `list<RewriteResult>`. Iga `RewriteResult` sisaldab failiteed, algset sisu, ümberkirjutatud sisu ja asenduste arvu. Vorming säilib: asendatakse ainult sobitatud sõlmede vahemikud, ülejäänud fail jääb puutumata.

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

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

Fassaad ei kirjuta kettale; helistaja otsustab, kas muudatused rakendada. CLI rakendab need, kui pole määratud `--dry-run` ega `--interactive`.

---

### Indekseeritud tekstiotsing

#### `buildTextIndex`

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

Koostab värske trigrammi- ja tunnuseesinemiste indeksi asukohale `$rootPath`. Indeks salvestatakse asukohta `$indexPath` (vaikimisi `$rootPath/.greph-index`). `$lifecycle` võib olla `static`, `manual-refresh`, `opportunistic-refresh` või `strict-stale-check`. Tagastab objekti `IndexBuildResult` koos failide ja trigrammide arvuga ning lisatud, uuendatud, kustutatud ja muutmata kirjete arvuga.

#### `refreshTextIndex`

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

Värskendab tekstiindeksit järk-järgult. Failide räsi arvutatakse uuesti ja ümber kirjutatakse ainult muudetud kirjed.

#### `searchTextIndexed`

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

Käivitab tekstiotsingu soojendatud indeksis. Kui indeksit pole, tagastab käitusaegse vea (kutsuge esmalt `buildTextIndex`). Tagastab `searchText`-ga täpselt sama struktuuriga `list<TextFileResult>`.

```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
```

Käivitab soojendatud tekstiotsingu mitmes tekstiindeksi kataloogis. Greph otsib igast sobivast indeksist, eemaldab absoluutsete failiteede järgi duplikaadid ja kasutab algset skannimist ainult nende teede puhul, mis ei asu ühegi antud indeksi juurkataloogis.

#### `loadIndexSet`

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

Laadib indeksikomplekti manifesti, vaikimisi praeguses töökataloogis asuvast failist `.greph-index-set.json`.

#### `searchTextIndexedSet`

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

Lahendab indeksikomplekti manifestist valitud kirjed `text` ja käivitab toimingu `searchTextIndexedMany` vaste.

---

### Indekseeritud AST-otsing

#### `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
```

Koostab AST-faktide indeksi või värskendab seda järk-järgult. Ekstraheeritud faktid salvestatakse vaikimisi asukohta `$rootPath/.greph-ast-index`.

#### `searchAstIndexed`

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

Kasutab faktide indeksit kandidaatide valiku kitsendamiseks ja kontrollib seejärel vasted lähtekoodi põhjal uuesti üle. Tagastab `searchAst`-ga sama struktuuriga `list<AstMatch>`.

#### `searchAstIndexedMany`

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

Käivitab soojendatud AST-faktiotsingu mitmes AST-indeksi kataloogis.

#### `searchAstIndexedSet`

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

Lahendab indeksikomplekti manifestist valitud kirjed `ast-index` ja käivitab toimingu `searchAstIndexedMany` vaste.

#### `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
```

Koostab vahemällu salvestatud parsitud puude hoidla või värskendab seda järk-järgult. Serialiseeritud puud salvestatakse vaikimisi asukohta `$rootPath/.greph-ast-cache`.

#### `searchAstCached`

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

Käivitab AST-otsingu vahemällu salvestatud parsitud puudel ja jätab parseri täielikult vahele. Tagastab `searchAst`-ga sama struktuuriga `list<AstMatch>`.

#### `searchAstCachedMany`

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

Käivitab soojendatud vahemällu salvestatud AST-otsingu mitmes vahemälukataloogis.

#### `searchAstCachedSet`

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

Lahendab indeksikomplekti manifestist valitud kirjed `ast-cache` ja käivitab toimingu `searchAstCachedMany` vaste.

---

## `Greph\Text\TextSearchOptions`

Ainult lugemiseks mõeldud tekstiotsingu valikute objekt.

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

Valideerimine:

- `jobs >= 1`
- `beforeContext, afterContext >= 0`
- `maxCount === null || maxCount >= 1`

Kasutage `walkOptions()`, et tuletada vastav `WalkOptions`, kui soovite failipuus eraldi liikuda.

`tracePlan` kasutavad soojendatud indeksiotsijad ning `greph-index` CLI edastavad plaanuri diagnostika `stderr`-le. Algne `searchText` seda ise ei kasuta.

---

## `Greph\Ast\AstSearchOptions`

Ainult lugemiseks mõeldud AST-otsingu ja ümberkirjutuse valikute objekt.

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

AST-režiimi vaikefailitüübi filter on `php`. Kui `skipParseErrors` väärtus on `true` (vaikimisi), jäetakse parsimisel nurjunud failid vaikselt vahele; määrake selle väärtuseks `false`, et kuvada parsimisvead eranditena. `tracePlan` kasutavad soojendatud AST-otsijad ja `greph-index ast-index|ast-cache search` kasutab seda kandidaatide kõrvaldamise diagnostika kuvamiseks.

---

## `Greph\Walker\WalkOptions`

Ainult lugemiseks mõeldud failipuus liikumise valikute objekt.

```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`

Lahendab nimetatud failitüübid laiendite loenditeks. Sisseehitatud aliased:

| Alias | Laiendid |
|---|---|
| `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']);
```

---

## Tulemiobjektid

### `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` ja `AstCacheBuildResult` järgivad sama kuju, kus vastavalt asendatakse `factCount` ja `cachedTreeCount`.

---

## Erandid

Greph viskab kolm tüübistatud erandit, kõik `Greph\Exceptions`-s:

| Erand | Millal see tekib |
|---|---|
| `WalkerException` | Failisüsteemi vead läbimisel (puuduv tee, loetamatu kataloog) |
| `PatternException` | Vigane regex või AST muster |
| `ParseException` | PHP lähtekoodi ei saanud parsida (ainult kui `skipParseErrors: false`) |

Indekseeritud otsingumeetodid viskavad erandi `\RuntimeException`, kui küsitud asukohas indeksit pole. `greph-index` CLI pakub suvandit `--fallback scan`, mis püüab need erandid kinni ja kasutab selle asemel indekseerimata skannimist.
