
# PHP API

## `Greph\Greph`

Razred `Greph\Greph` je statična vstopna točka. Ponuja vse operacije iskanja, prepisovanja in indeksiranja. Vse metode sprejemajo eno pot ali seznam poti.

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

### `walk`

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

Razreši `$paths` v enodimenzionalni `FileList` absolutnih poti do datotek. Upošteva pravila gitignore, `.grephignore`, filtre vrst datotek, vzorce glob, vključevanje skritih datotek, sledenje simbolnim povezavam, zaznavanje binarnih datotek in omejitev največje velikosti datotek.

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

Izvede iskanje besedila in vrne `list<TextFileResult>`. Vsak `TextFileResult` razkrije pot do datoteke in seznam objektov `TextMatch` (vrstica, stolpec, vsebina, zajeti podatki, izbirni 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";
    }
}
```

Če je nastavljeno `jobs > 1` in število datotek preseže prag za delavce, `searchText` samodejno preda pregled `WorkerPool`. Sicer se izvaja znotraj procesa.

---

### `searchAst`

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

Izvede strukturno iskanje AST in vrne `list<AstMatch>`. Vzorci so zapisani kot izvorna koda PHP z metavariablami `$VAR` in `$$$VARIADIC`. Vsak `AstMatch` vključuje datoteko, zajeti `PhpParser\Node`, zajete vrednosti, začetno in končno vrstico ter odmika v bajtih, pa tudi izsek ujemajoče se izvorne kode.

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

Izvede strukturno prepisovanje in vrne `list<RewriteResult>`. Vsak `RewriteResult` razkrije pot do datoteke, izvirno vsebino, prepisano vsebino in število zamenjav. Prepisovanje ohranja oblikovanje: zamenjajo se samo obsegi ujemajočih se vozlišč, preostanek datoteke pa ostane nedotaknjen.

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

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

Fasada ne zapisuje na disk; klicatelj odloči, ali bo spremembe uveljavil. CLI jih uveljavi, razen če je nastavljeno `--dry-run` ali `--interactive`.

---

### Iskanje po indeksiranem besedilu

#### `buildTextIndex`

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

Ustvari nov indeks trigrame in objav identifikatorjev za `$rootPath`. Indeks se shrani v `$indexPath` (privzeto `$rootPath/.greph-index`). `$lifecycle` je lahko `static`, `manual-refresh`, `opportunistic-refresh` ali `strict-stale-check`. Vrne `IndexBuildResult` s številom datotek, številom trigramov ter številom dodanih, posodobljenih, izbrisanih in nespremenjenih elementov.

#### `refreshTextIndex`

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

Postopoma osveži obstoječi besedilni indeks. Datoteke se znova zgoščijo, prepišejo pa se samo spremenjeni vnosi.

#### `searchTextIndexed`

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

Izvede iskanje besedila po ogretem indeksu. Če indeks ne obstaja, sproži napako izvajalnega okolja (najprej pokličite `buildTextIndex`). Vrne `list<TextFileResult>` v povsem enaki obliki kot `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
```

Izvede iskanje po ogretem besedilnem indeksu v več imenikih z indeksi. Greph preišče vsak ustrezen indeks, odstrani podvojene rezultate glede na absolutno pot do datoteke in uporabi izvorni pregled samo za poti zunaj vseh podanih korenskih imenikov indeksov.

#### `loadIndexSet`

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

Naloži manifest nabora indeksov; privzeto `.greph-index-set.json` v trenutnem delovnem imeniku.

#### `searchTextIndexedSet`

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

Razreši izbrane vnose `text` iz manifesta nabora indeksov in izvede enakovredno operacijo kot `searchTextIndexedMany`.

---

### Iskanje po indeksiranem AST

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

Ustvari ali postopoma osveži indeks dejstev AST. Izluščena dejstva so privzeto shranjena v `$rootPath/.greph-ast-index`.

#### `searchAstIndexed`

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

Z indeksom dejstev zoži nabor kandidatov, nato pa ujemanja znova preveri glede na izvorno kodo. Vrne `list<AstMatch>` v enaki obliki kot `searchAst`.

#### `searchAstIndexedMany`

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

Izvede iskanje po ogretem indeksu dejstev AST v več imenikih indeksov AST.

#### `searchAstIndexedSet`

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

Razreši izbrane vnose `ast-index` iz manifesta nabora indeksov in izvede enakovredno operacijo kot `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
```

Ustvari ali postopoma osveži shrambo predpomnjenih razčlenjenih dreves. Serializirana drevesa so privzeto shranjena v `$rootPath/.greph-ast-cache`.

#### `searchAstCached`

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

Izvede iskanje AST po predpomnjenih razčlenjenih drevesih in v celoti preskoči razčlenjevalnik. Vrne `list<AstMatch>` v enaki obliki kot `searchAst`.

#### `searchAstCachedMany`

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

Izvede iskanje po ogretem predpomnjenem AST v več imenikih predpomnilnika.

#### `searchAstCachedSet`

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

Razreši izbrane vnose `ast-cache` iz manifesta nabora indeksov in izvede enakovredno operacijo kot `searchAstCachedMany`.

---

## `Greph\Text\TextSearchOptions`

Nespremenljiv objekt možnosti za iskanje besedila.

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

Preverjanje:

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

Če želite drevo datotek pregledati ločeno, uporabite `walkOptions()` za izpeljavo ustreznega `WalkOptions`.

`tracePlan` uporabljajo iskalniki po ogretih indeksih, tokovi `greph-index` CLI pa izpisujejo diagnostiko načrtovalnika v `stderr`. Izvorni `searchText` ga ne uporablja.

---

## `Greph\Ast\AstSearchOptions`

Nespremenljiv objekt možnosti za iskanje in prepisovanje 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,
)
```

Privzeti filter vrste datotek za način AST je `php`. Če je `skipParseErrors` nastavljena na `true` (privzeto), se datoteke, ki jih ni mogoče razčleniti, tiho preskočijo; nastavite jo na `false`, da se napake pri razčlenjevanju prikažejo kot izjeme. `tracePlan` uporabljajo vnaprej ogreti iskalniki AST, `greph-index ast-index|ast-cache search` pa za izpis diagnostike ob izločanju kandidatov.

---

## `Greph\Walker\WalkOptions`

Predmet možnosti samo za branje za sprehajalnik datotek.

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

Imena vrst datotek preslika v sezname končnic. Vgrajeni vzdevki:

| Vzdevek | Končnice |
|---|---|
| `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']);
```

---

## Objekti z rezultati

### `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` in `AstCacheBuildResult` imata enako obliko, pri čemer sta `factCount` oziroma `cachedTreeCount` nadomeščena.

---

## Izjeme

Greph sproži tri tipizirane izjeme, vse v `Greph\Exceptions`:

| Izjema | Kdaj se sproži |
|---|---|
| `WalkerException` | Napake datotečnega sistema med pregledovanjem (manjkajoča pot, neberljiv imenik) |
| `PatternException` | Neveljaven regularni izraz ali vzorec AST |
| `ParseException` | Izvorne kode PHP ni bilo mogoče razčleniti (samo kadar `skipParseErrors: false`) |

Metode indeksiranega iskanja sprožijo `\RuntimeException`, kadar na zahtevani lokaciji ni indeksa. `greph-index` CLI ponuja možnost `--fallback scan`, ki ujame te izjeme in namesto tega uporabi neindeksirano pregledovanje.
