
# PHP API

## `Greph\Greph`

Класът `Greph\Greph` е статичната входна точка. Той предоставя всички операции за търсене, пренаписване и индексиране. Всички методи приемат единичен път или списък с пътища.

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

### `walk`

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

Разрешава `$paths` до плосък `FileList` с абсолютни файлови пътища. Спазва gitignore, `.grephignore`, филтрите за типове файлове, шаблоните glob, включването на скрити файлове, следването на символни връзки, откриването на двоични файлове и ограничението за максимален размер на файла.

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

Изпълнява текстово търсене и връща `list<TextFileResult>`. Всеки `TextFileResult` съдържа пътя до файла и списък с обекти `TextMatch` (ред, колона, съдържание, съвпадения, незадължителен контекст).

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

Когато `jobs > 1` и броят на файловете надхвърли прага за работници, `searchText` автоматично разпределя сканирането към `WorkerPool`. В противен случай то се изпълнява в текущия процес.

---

### `searchAst`

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

Изпълнява структурно търсене в AST и връща `list<AstMatch>`. Шаблоните се задават като изходен код на PHP с метапроменливи `$VAR` и `$$$VARIADIC`. Всеки `AstMatch` включва файла, заснетия `PhpParser\Node`, съвпаденията, началния и крайния ред и байтови отмествания, както и фрагмента от изходния код, който съвпада.

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

Изпълнява структурно пренаписване и връща `list<RewriteResult>`. Всеки `RewriteResult` съдържа пътя до файла, оригиналното съдържание, пренаписаното съдържание и броя на замените. Пренаписванията запазват форматирането: заменят се само диапазоните на съвпадащите възли, а останалата част от файла остава непроменена.

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

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

Фасадата не записва на диск; извикващият решава дали да приложи промените. CLI ги прилага, освен ако не е зададено `--dry-run` или `--interactive`.

---

### Индексирано търсене на текст

#### `buildTextIndex`

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

Създава нов индекс на триграми и публикации на идентификатори за `$rootPath`. Индексът се съхранява в `$indexPath` (по подразбиране `$rootPath/.greph-index`). `$lifecycle` може да бъде `static`, `manual-refresh`, `opportunistic-refresh` или `strict-stale-check`. Връща `IndexBuildResult` с броя файлове, броя триграми и броя добавени, актуализирани, изтрити и непроменени записи.

#### `refreshTextIndex`

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

Обновява постепенно съществуващ текстов индекс. Файловете се хешират отново и се презаписват само променените записи.

#### `searchTextIndexed`

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

Изпълнява текстово търсене в затопления индекс. Ако индексът не съществува, връща грешка по време на изпълнение (първо извикайте `buildTextIndex`). Връща `list<TextFileResult>` със същата структура като `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
```

Изпълнява търсене в затопления текстов индекс в няколко директории с текстови индекси. Greph търси във всеки приложим индекс, премахва дубликатите по абсолютен файлов път и използва вграденото сканиране само за пътища извън всички зададени корени на индекси.

#### `loadIndexSet`

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

Зарежда манифест на набор от индекси, като по подразбиране използва `.greph-index-set.json` в текущата работна директория.

#### `searchTextIndexedSet`

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

Разрешава избраните записи `text` от манифест на набор от индекси и изпълнява еквивалента на `searchTextIndexedMany`.

---

### Индексирано търсене в 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
```

Създава или постепенно обновява индекса на факти за AST. По подразбиране съхранява извлечените факти в `$rootPath/.greph-ast-index`.

#### `searchAstIndexed`

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

Използва индекса на факти, за да стесни кандидатите, преди повторно да провери съвпаденията спрямо изходния код. Връща резултат със същата структура `list<AstMatch>` като `searchAst`.

#### `searchAstIndexedMany`

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

Изпълнява търсене по затопления индекс на факти за AST в няколко директории с AST индекси.

#### `searchAstIndexedSet`

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

Разрешава избраните записи `ast-index` от манифест на набор от индекси и изпълнява еквивалента на `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
```

Създава или постепенно обновява хранилището с кеширани синтактични дървета. По подразбиране съхранява сериализираните дървета в `$rootPath/.greph-ast-cache`.

#### `searchAstCached`

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

Изпълнява търсене в AST спрямо кешираните синтактични дървета, без изобщо да стартира парсера. Връща резултат със същата структура `list<AstMatch>` като `searchAst`.

#### `searchAstCachedMany`

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

Изпълнява търсене в затопления кеширан AST в няколко директории с кешове.

#### `searchAstCachedSet`

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

Разрешава избраните записи `ast-cache` от манифест на набор от индекси и изпълнява еквивалента на `searchAstCachedMany`.

---

## `Greph\Text\TextSearchOptions`

Обект с опции само за четене за текстово търсене.

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

Проверка:

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

Използвайте `walkOptions()`, за да получите съответния `WalkOptions`, ако искате да обхождате файловото дърво отделно.

`tracePlan` се използва от инструментите за търсене в затоплен индекс, а `greph-index` CLI осигуряват потока за извеждане на диагностични данни от планировчика към `stderr`. Самото вградено `searchText` не го използва.

---

## `Greph\Ast\AstSearchOptions`

Обект с опции само за четене за търсене и пренаписване в 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,
)
```

Филтърът за типове файлове по подразбиране в режим AST е `php`. Когато `skipParseErrors` е `true` (по подразбиране), файловете, които не могат да бъдат парснати, се пропускат без съобщение; задайте `false`, за да се показват грешките при парсване като изключения. `tracePlan` се използва от инструментите за търсене в затоплен AST, а `greph-index ast-index|ast-cache search` — за извеждане на диагностични данни от стесняването на кандидатите.

---

## `Greph\Walker\WalkOptions`

Обект с опции само за четене за обхождача на файлове.

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

Разрешава именуваните типове файлове до списъци с разширения. Вградени псевдоними:

| Псевдоним | Разширения |
|---|---|
| `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']);
```

---

## Обекти с резултати

### `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` и `AstCacheBuildResult` следват същата структура, като съответно се заменят с `factCount` и `cachedTreeCount`.

---

## Изключения

Greph хвърля три типизирани изключения, всички в `Greph\Exceptions`:

| Изключение | Кога се хвърля |
|---|---|
| `WalkerException` | Грешки във файловата система по време на обхождане (липсващ път, директория без достъп за четене) |
| `PatternException` | Невалиден регулярен израз или AST шаблон |
| `ParseException` | Изходният код на PHP не може да бъде анализиран (само когато `skipParseErrors: false`) |

Методите за индексирано търсене хвърлят `\RuntimeException`, когато на заявеното място няма индекс. `greph-index` CLI предоставя опция `--fallback scan`, която прихваща тези изключения и вместо това преминава към сканиране без индекс.
