
# PHP API

## `Greph\Greph`

Klassen `Greph\Greph` er det statiske indgangspunkt. Den giver adgang til alle søge-, omskrivnings- og indekseringsoperationer. Alle metoder accepterer enten en enkelt sti eller en liste over stier.

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

### `walk`

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

Opløs `$paths` til en flad `FileList` med absolutte filstier. Tager højde for gitignore, `.grephignore`, filtypefiltre, glob-mønstre, medtagelse af skjulte filer, følgning af symbolske links, registrering af binærfiler og grænsen for maksimal filstørrelse.

```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ør en tekstsøgning, og returnér en `list<TextFileResult>`. Hver `TextFileResult` viser filstien og en liste over `TextMatch`-objekter (linje, kolonne, indhold, fangede værdier og valgfri 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";
    }
}
```

Når `jobs > 1` og antallet af filer overstiger arbejdergrænsen, sender `searchText` automatisk scanningen til en `WorkerPool`. Ellers kører den i processen.

---

### `searchAst`

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

Kør en strukturel AST-søgning, og returnér en `list<AstMatch>`. Mønstre skrives som PHP-kildekode med metakvablerne `$VAR` og `$$$VARIADIC`. Hver `AstMatch` indeholder filen, den fangede `PhpParser\Node`, de fangede værdier, start- og slutlinje samt byteforskydninger og det matchende kildekodesnit.

```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ør en strukturel omskrivning, og returnér en `list<RewriteResult>`. Hver `RewriteResult` viser filstien, det oprindelige indhold, det omskrevne indhold og antallet af erstatninger. Omskrivninger bevarer formateringen: Kun de matchede knudeområder indsættes, og resten af filen forbliver urørt.

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

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

Facaden skriver ikke til disken; kaldende kode afgør, om ændringerne skal anvendes. CLI anvender dem, medmindre `--dry-run` eller `--interactive` er angivet.

---

### Indekseret tekstsøgning

#### `buildTextIndex`

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

Byg et nyt trigram- og identifikator-postingsindeks for `$rootPath`. Indekset gemmes i `$indexPath` (standard er `$rootPath/.greph-index`). `$lifecycle` kan være `static`, `manual-refresh`, `opportunistic-refresh` eller `strict-stale-check`. Returnerer en `IndexBuildResult` med antal filer, antal trigrammer samt antal tilføjede, opdaterede, slettede og uændrede filer.

#### `refreshTextIndex`

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

Opdatér et eksisterende tekstindeks trinvist. Filer hashberegnes igen, og kun ændrede poster omskrives.

#### `searchTextIndexed`

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

Kør en tekstsøgning mod det opvarmede indeks. Returnerer en runtime-fejl, hvis indekset ikke findes (kør først `buildTextIndex`). Returnerer en `list<TextFileResult>` med præcis samme struktur som `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
```

Kør opvarmet tekstsøgning på tværs af flere tekstindeksmapper. Greph søger i hvert relevant indeks, fjerner dubletter ud fra absolut filsti og falder kun tilbage til en indbygget scanning for stier uden for alle angivne indeksrødder.

#### `loadIndexSet`

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

Indlæs et indeks-sæt-manifest, som standard `.greph-index-set.json` i den aktuelle arbejdsmappe.

#### `searchTextIndexedSet`

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

Find de valgte `text`-poster fra et indeks-sæt-manifest, og kør det tilsvarende af `searchTextIndexedMany`.

---

### Indekseret AST-søgning

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

Byg eller opdatér AST-faktaindekset trinvist. Gemmer som standard udtrukne fakta i `$rootPath/.greph-ast-index`.

#### `searchAstIndexed`

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

Brug faktaindekset til at indsnævre kandidater, før match verificeres igen mod kilden. Returnerer samme `list<AstMatch>`-struktur som `searchAst`.

#### `searchAstIndexedMany`

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

Kør opvarmet AST-faktasøgning på tværs af flere AST-indeksmapper.

#### `searchAstIndexedSet`

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

Find de valgte `ast-index`-poster fra et indeks-sæt-manifest, og kør det tilsvarende af `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
```

Byg eller opdatér det cachelagrede lager med parsede træer trinvist. Gemmer som standard serialiserede træer i `$rootPath/.greph-ast-cache`.

#### `searchAstCached`

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

Kør AST-søgning mod de cachelagrede parsede træer uden at køre parseren. Returnerer samme `list<AstMatch>`-struktur som `searchAst`.

#### `searchAstCachedMany`

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

Kør opvarmet søgning i cachelagret AST på tværs af flere cachemapper.

#### `searchAstCachedSet`

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

Find de valgte `ast-cache`-poster fra et indeks-sæt-manifest, og kør det tilsvarende af `searchAstCachedMany`.

---

## `Greph\Text\TextSearchOptions`

Skrivebeskyttet indstillingsobjekt til tekstsøgning.

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

Validering:

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

Brug `walkOptions()` til at udlede den tilsvarende `WalkOptions`, hvis du vil gennemgå filtræet separat.

`tracePlan` bruges af opvarmede indekssøgere, og `greph-index` CLI-flows udsender planlægningsdiagnostik til `stderr`. Den indbyggede `searchText` bruger den ikke.

---

## `Greph\Ast\AstSearchOptions`

Skrivebeskyttet indstillingsobjekt til AST-søgning og -omskrivning.

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

Standardfilteret for filtyper i AST-tilstand er `php`. Når `skipParseErrors` er `true` (standard), springes filer, der ikke kan parses, lydløst over; ændr det til `false` for at få parsefejl som undtagelser. `tracePlan` bruges af opvarmede AST-søgere, og `greph-index ast-index|ast-cache search` til at udsende diagnostik om kandidatfravalg.

---

## `Greph\Walker\WalkOptions`

Skrivebeskyttet indstillingsobjekt til filgennemløberen.

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

Opløs navngivne filtyper til lister over filtypenavne. Indbyggede aliaser:

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

---

## Resultatobjekter

### `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` og `AstCacheBuildResult` følger samme form med henholdsvis `factCount` og `cachedTreeCount` indsat.

---

## Undtagelser

Greph udløser tre typede undtagelser, alle i `Greph\Exceptions`:

| Undtagelse | Hvornår den udløses |
|---|---|
| `WalkerException` | Filsystemfejl under gennemgang (manglende sti, mappe kan ikke læses) |
| `PatternException` | Ugyldigt regex- eller AST-mønster |
| `ParseException` | Kilden PHP kunne ikke parses (kun når `skipParseErrors: false`) |

Indekserede søgemetoder udløser `\RuntimeException`, når der ikke findes et indeks på den anmodede placering. `greph-index` CLI stiller en indstilling `--fallback scan` til rådighed, som fanger disse fejl og i stedet falder tilbage til en søgning uden indeks.
