
# PHP API

## `Greph\Greph`

Klase `Greph\Greph` ir statiskais ieejas punkts. Tā nodrošina visas meklēšanas, pārrakstīšanas un indeksēšanas darbības. Visas metodes pieņem vienu ceļu vai ceļu sarakstu.

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

### `walk`

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

Atrisiniet `$paths`, iegūstot plakanu absolūto failu ceļu `FileList`. Tiek ievēroti gitignore, `.grephignore`, failu tipu filtri un glob modeļi, kā arī slēpto failu iekļaušanas, sekošanas simboliskajām saitēm un bināro failu noteikšanas iestatījumi un maksimālā faila lieluma ierobežojums.

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

Veiciet teksta meklēšanu un atgrieziet `list<TextFileResult>`. Katrs `TextFileResult` norāda faila ceļu un objektu `TextMatch` sarakstu (rinda, kolonna, saturs, tvērumi, neobligātais konteksts).

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

Ja ir norādīts `jobs > 1` un failu skaits pārsniedz darbinieku slieksni, `searchText` automātiski nosūta skenēšanu uz `WorkerPool`. Pretējā gadījumā tā darbojas vienā procesā.

---

### `searchAst`

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

Veiciet strukturālu AST meklēšanu un atgrieziet `list<AstMatch>`. Paraugus raksta kā PHP pirmkodu ar `$VAR` un `$$$VARIADIC` metamainīgajiem. Katrā `AstMatch` ir iekļauts fails, fiksētais `PhpParser\Node`, tvērumi, sākuma/beigu rindas un baitu nobīdes, kā arī atbilstošais avota koda fragments.

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

Veiciet strukturālu pārrakstīšanu un atgrieziet `list<RewriteResult>`. Katrs `RewriteResult` norāda faila ceļu, sākotnējo saturu, pārrakstīto saturu un aizvietojumu skaitu. Formatējums tiek saglabāts: tiek aizvietoti tikai atbilstošo mezglu apgabali, pārējais fails paliek nemainīts.

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

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

Fasāde neraksta diskā; izsaucējs izlemj, vai piemērot izmaiņas. CLI tās piemēro, ja vien nav iestatīts `--dry-run` vai `--interactive`.

---

### Indeksēta teksta meklēšana

#### `buildTextIndex`

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

Izveidojiet jaunu trigrammu un identifikatoru norāžu indeksu objektam `$rootPath`. Indekss tiek saglabāts vietā `$indexPath` (noklusējums ir `$rootPath/.greph-index`). `$lifecycle` var būt `static`, `manual-refresh`, `opportunistic-refresh` vai `strict-stale-check`. Atgriež `IndexBuildResult` ar failu un trigrammu skaitu, kā arī pievienoto, atjaunināto, dzēsto un nemainīto vienumu skaitu.

#### `refreshTextIndex`

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

Pakāpeniski atjauniniet esošu teksta indeksu. Failu jaucējvērtības tiek aprēķinātas no jauna, un tiek pārrakstīti tikai mainītie ieraksti.

#### `searchTextIndexed`

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

Meklējiet tekstu iesildītā indeksā. Ja indeksa nav, atgrieziet izpildlaika kļūdu (vispirms izsauciet `buildTextIndex`). Atgriež `list<TextFileResult>` ar tādu pašu struktūru kā `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
```

Veiciet teksta meklēšanu vairākos iesildītos teksta indeksu direktorijos. Greph meklē katrā atbilstošajā indeksā, noņem dublikātus pēc absolūtā faila ceļa un izmanto sākotnējo skenēšanu tikai tiem ceļiem, kas neatrodas nevienā no norādītajām indeksu saknēm.

#### `loadIndexSet`

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

Ielādējiet indeksu kopas manifestu; pēc noklusējuma — `.greph-index-set.json` pašreizējā darba direktorijā.

#### `searchTextIndexedSet`

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

Atrisiniet atlasītos `text` ierakstus no indeksu kopas manifesta un izpildiet darbībai `searchTextIndexedMany` līdzvērtīgu operāciju.

---

### Indeksēta AST meklēšana

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

Izveidojiet vai pakāpeniski atjauniniet AST faktu indeksu. Pēc noklusējuma iegūtie fakti tiek saglabāti vietā `$rootPath/.greph-ast-index`.

#### `searchAstIndexed`

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

Izmantojiet faktu indeksu, lai sašaurinātu kandidātu loku, un pēc tam vēlreiz pārbaudiet atbilstības, salīdzinot tās ar avotu. Atgriež tādas pašas formas rezultātu kā `searchAst` `list<AstMatch>`.

#### `searchAstIndexedMany`

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

Veiciet uzsildītu AST faktu meklēšanu vairākās AST indeksu mapēs.

#### `searchAstIndexedSet`

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

Atrisiniet atlasītos `ast-index` ierakstus no indeksu kopas manifesta un veiciet darbību, kas atbilst `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
```

Izveidojiet vai pakāpeniski atsvaidziniet kešoto parsēto koku krātuvi. Pēc noklusējuma serializētie koki tiek glabāti mapē `$rootPath/.greph-ast-cache`.

#### `searchAstCached`

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

Veiciet AST meklēšanu kešotajos parsētajos kokos, pilnībā izlaižot parsētāju. Atgriež tādas pašas formas rezultātu kā `searchAst` `list<AstMatch>`.

#### `searchAstCachedMany`

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

Veiciet uzsildītu kešotā AST meklēšanu vairākās kešatmiņas mapēs.

#### `searchAstCachedSet`

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

Atrisiniet atlasītos `ast-cache` ierakstus no indeksu kopas manifesta un veiciet darbību, kas atbilst `searchAstCachedMany`.

---

## `Greph\Text\TextSearchOptions`

Tikai lasāms teksta meklēšanas opciju objekts.

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

Validācija:

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

Izmantojiet `walkOptions()`, lai iegūtu atbilstošo `WalkOptions`, ja vēlaties atsevišķi pārstaigāt failu koku.

Uzsildītie indeksētās meklēšanas rīki izmanto `tracePlan`, savukārt `greph-index` CLI plūsmas izvada plānotāja diagnostikas informāciju uz `stderr`. Vietējais `searchText` to neizmanto.

---

## `Greph\Ast\AstSearchOptions`

Tikai lasāms AST meklēšanas un pārrakstīšanas opciju objekts.

```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žīmam pēc noklusējuma tiek izmantots failu tipu filtrs `php`. Ja `skipParseErrors` ir `true` (noklusējums), parsēšanas kļūmes failos tiek klusi ignorētas; pārslēdziet to uz `false`, lai parsēšanas kļūdas tiktu parādītas kā izņēmumi. Uzsildītie AST meklēšanas rīki izmanto `tracePlan`, bet `greph-index ast-index|ast-cache search` tiek izmantots kandidātu atlases diagnostikas izvadīšanai.

---

## `Greph\Walker\WalkOptions`

Tikai lasāms failu koka pārlūkošanas opciju objekts.

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

Atrisiniet nosauktos failu tipus līdz paplašinājumu sarakstiem. Iebūvētie aizstājvārdi:

| Aliass | Paplašinājumi |
|---|---|
| `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']);
```

---

## Rezultātu objekti

### `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` un `AstCacheBuildResult` ir vienādas formas; attiecīgi aizstājot `factCount` un `cachedTreeCount`.

---

## Izņēmumi

Greph izmet trīs tipizētus izņēmumus, visi no tiem ir `Greph\Exceptions`:

| Izņēmums | Kad tas tiek izraisīts |
|---|---|
| `WalkerException` | Failu sistēmas kļūdas traversēšanas laikā (trūkstošs ceļš, nelasāma mape) |
| `PatternException` | Nederīga regex izteiksme vai AST raksts |
| `ParseException` | Neizdevās parsēt PHP avotu (tikai tad, ja `skipParseErrors: false`) |

Indeksētās meklēšanas metodes izmet `\RuntimeException`, ja pieprasītajā atrašanās vietā nav indeksa. `greph-index` CLI piedāvā opciju `--fallback scan`, kas uztver šīs kļūdas un tā vietā veic skenēšanu bez indeksa.
