
# API

整个静态接口都集中在一个类上：`TailwindPHP\tw`（内部类 `Tailwind` 的别名）。所有方法都可静态调用，检查方法（`properties`、`computedProperties`、`value`、`computedValue`）均接受本页底部介绍的 [输入格式](#input-formats)。

对于同一 CSS 配置的重复操作，调用一次 [`tw::compile()`](#twcompile)，然后复用返回的 [`TailwindCompiler`](#tailwindcompiler-instance-methods)。

```php
use TailwindPHP\tw;

$css = tw::generate('<div class="flex items-center p-4 bg-blue-500">');
```

## tw::generate()

```php
public static function generate(string|array $input, string $css = '@import "tailwindcss";'): string
```

解析内容，提取类名候选项，并返回生成的 CSS。默认 `$css` 为 `@import "tailwindcss";`，会引入主题、预置样式和工具类。**返回** `string`。

```php
use TailwindPHP\tw;

// String input
$css = tw::generate('<div class="flex p-4">');

// String with custom CSS
$css = tw::generate('<div class="flex bg-brand">', '@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');

// Array input with options
$css = tw::generate([
    'content' => '<div class="flex p-4">',
    'css' => '@import "tailwindcss";',
    'minify' => true,
]);
```

数组形式接受以下键：

| 键 | 类型 | 用途 |
|---|---|---|
| `content` | `string` | 要扫描类名候选项的内容（必需） |
| `css` | `string` | 输入 CSS，其中包含 Tailwind 指令（默认 `@import "tailwindcss";`） |
| `minify` | `bool` | 压缩输出（默认 `false`） |
| `importPaths` | `string \| array \| callable \| null` | 从文件系统加载 CSS，并进行完整的 `@import` 解析——参见 [导入 CSS](https://tailwindphp.inline0.dev/zh/docs/usage/imports) |
| `cache` | `bool \| string` | 启用文件缓存——参见 [缓存](#caching) |
| `cacheTtl` | `int` | 缓存有效期（秒） |

## tw::compile()

```php
public static function compile(string $css = '@import "tailwindcss";', array $options = []): TailwindCompiler
```

创建一个绑定到给定 CSS 的可复用 `TailwindCompiler`。解析和设计系统构建只执行一次，因此当要为许多不同的内容字符串生成 CSS 时，这是高效的选择。使用 `generate()` 在多次调用间累积一个样式表，或使用 [`generateExact()`](#accumulating-vs-exact-generation) 为每页独立生成输出。**返回** `TailwindCompiler`。

```php
use TailwindPHP\tw;

// Default Tailwind
$compiler = tw::compile();

// Custom CSS
$compiler = tw::compile('@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');

$css = $compiler->generate('<div class="flex p-4 bg-brand">');
```

`$options` 数组接受以下选项：

| 选项 | 类型 | 用途 |
|---|---|---|
| `stateCacheFile` | `string` | PHP 文件的路径，用于在请求和进程之间持久化编译器的构造状态——参见 [编译器状态缓存](https://tailwindphp.inline0.dev/zh/docs/advanced/caching#compiler-state-cache) |
| `polyfills` | `int` | 要输出哪些回退值，以 `TailwindPHP\POLYFILL_AT_PROPERTY` 的位掩码表示：`@layer properties`（`@property` 变量的默认值）和 `TailwindPHP\POLYFILL_COLOR_MIX`（`color-mix()` 之前的静态颜色回退值）。默认值为 `POLYFILL_ALL`；`POLYFILL_NONE` 会禁用两者 |
| `importSearchPaths` | `array<string>` | 从文件系统解析 `@import` 时要搜索的目录 |

```php
use TailwindPHP\tw;
use const TailwindPHP\POLYFILL_NONE;

// Cache construction state on disk, reused by later requests
$compiler = tw::compile('@import "tailwindcss";', [
    'stateCacheFile' => __DIR__ . '/cache/tailwind-state.php',
]);

// Plain output without fallbacks, e.g. for CSS modules
$compiler = tw::compile('@import "tailwindcss/utilities.css";', [
    'polyfills' => POLYFILL_NONE,
]);
$compiler->generate('<div class="bg-red-500/50">');
// .bg-red-500\/50 { background-color: color-mix(in oklab, var(--color-red-500) 50%, transparent); }
// (with the default, a `#fb2c3680` fallback comes first and color-mix() moves into @supports)
```

完整的实例接口请参见 [TailwindCompiler 实例方法](#tailwindcompiler-instance-methods)。

## tw::properties()

```php
public static function properties(string|array $input, string $css = '@import "tailwindcss";'): array
```

返回某个类的 **原始** CSS 属性，其中 CSS 变量尚未解析。**返回** `array<string, string>`（属性名 → 值）。

```php
use TailwindPHP\tw;

tw::properties('p-4');
// ['padding' => 'calc(var(--spacing) * 4)']

tw::properties(['flex', 'items-center', 'p-4']);
// ['display' => 'flex', 'align-items' => 'center', 'padding' => 'calc(var(--spacing) * 4)']
```

## tw::computedProperties()

```php
public static function computedProperties(string|array $input, string $css = '@import "tailwindcss";'): array
```

与 [`properties()`](#twproperties) 类似，但会将每个 CSS 变量解析为具体值。**返回** `array<string, string>`。

```php
use TailwindPHP\tw;

tw::computedProperties('p-4');
// ['padding' => '1rem']

tw::computedProperties('text-blue-500');
// ['color' => 'oklch(62.3% .214 259.815)']

tw::computedProperties(['flex', 'items-center', 'gap-4']);
// ['display' => 'flex', 'align-items' => 'center', 'gap' => '1rem']
```

## tw::value()

```php
public static function value(string|array $input, string $css = '@import "tailwindcss";'): ?string
```

返回单个工具类的 **原始** 值。**返回** `?string`——如果未找到该工具类，则返回 `null`。

```php
use TailwindPHP\tw;

tw::value('p-4');           // 'calc(var(--spacing) * 4)'
tw::value('text-blue-500'); // 'var(--color-blue-500)'
```

## tw::computedValue()

```php
public static function computedValue(string|array $input, string $css = '@import "tailwindcss";'): ?string
```

返回单个工具类的 **已解析** 值。**返回** `?string`——如果未找到该工具类，则返回 `null`。

```php
use TailwindPHP\tw;

tw::computedValue('p-4');           // '1rem'
tw::computedValue('text-blue-500'); // 'oklch(62.3% .214 259.815)'
tw::computedValue('gap-4');         // '1rem'
```

## tw::extractCandidates()

```php
public static function extractCandidates(string $html): array
```

从内容中提取 Tailwind 类名（读取 `class` 和 `className` 属性）。**返回** `array<string>`。

```php
use TailwindPHP\tw;

tw::extractCandidates('<div class="flex p-4" className="bg-blue-500">');
// ['flex', 'p-4', 'bg-blue-500']
```

## tw::extractCandidatesFromStrings()

```php
public static function extractCandidatesFromStrings(string $source): array
```

从源码中每个单引号或双引号字符串提取类名候选项，适用于在变量中构建类列表而不是使用 `class` 属性的模板。每个字符串会按空白字符拆分，并保留所有看起来像类名的词元。**返回** `array<string>`。

```php
use TailwindPHP\tw;

$classes = tw::extractCandidatesFromStrings('<?php $wrap = \'p-4 sm:flex\'; $title = "hello world"; ?>');
// ['p-4', 'sm:flex', 'hello', 'world']

$css = tw::compile()->css($classes);
```

普通单词也会通过检查（上文的 `hello`、`world`）；除非它们恰好是工具类名称，否则编译结果为空。请将结果传给 [`css()`](#tailwindcompiler-instance-methods)，因为 `generate()` 只读取 `class` 属性。

## tw::cssMap()

```php
public static function cssMap(string $css = '@import "tailwindcss";'): array
```

根据 CSS 声明构建反向映射，将其映射到工具类，便于将现有 CSS 转换为 Tailwind 类。键是解析了变量的 `"property: value"` 字符串（多属性工具类也会获得一个 `"prop: value; prop: value"` 键），值是类名。**返回** `array<string, string>`。

```php
use TailwindPHP\tw;

$map = tw::cssMap();
$map['display: flex'];       // 'flex'
$map['padding: 1rem'];       // 'p-4'
$map['text-align: center'];  // 'text-center'
$map['color: #fff'];         // 'text-white'
```

此映射覆盖固定列表中的常见工具类（显示、定位、弹性布局、排版、间距和尺寸级别、边框、黑色/白色/透明颜色等），而非所有工具类或主题颜色。`$css` 参数会改变这些工具类解析后的值，但自定义主题令牌（例如 `--color-brand`）不会新增映射条目。

## tw::minify()

```php
public static function minify(string $css): string
```

压缩任意 CSS 字符串：移除注释、合并空白、缩短十六进制颜色（`#ffffff` → `#fff`）、移除零值的单位（`0px` → `0`）等。**返回** `string`。

对于由 TailwindPHP 自行生成的 CSS，优先使用 `minify` 选项（`tw::generate(['minify' => true])`），或使用 [编译器方法](#tailwindcompiler-instance-methods)上的 `$minify` 参数。该路径会在序列化过程中进行压缩，速度更快，并且能保留基于字符串的处理会合并掉的后代 `:not()` 选择器。

```php
use TailwindPHP\tw;

$css = tw::generate('<div class="flex p-4">');
$minified = tw::minify($css);
```

完整优化列表请参见 [缓存与压缩](https://tailwindphp.inline0.dev/zh/docs/advanced/caching)。

## tw::clearCache()

```php
public static function clearCache(string|bool|null $cache = true): int
```

删除缓存的 CSS 文件。传入 `true`（或省略）以使用默认缓存目录，或传入路径字符串以使用自定义目录。**返回** `int`——删除的文件数量。

```php
use TailwindPHP\tw;

tw::clearCache();                  // default directory
tw::clearCache('/path/to/cache');  // custom directory
```

也可以使用独立的 `TailwindPHP\clearCache()` 函数。

## tw::colors()

```php
public static function colors(string $css = '@import "tailwindcss";'): array
```

返回主题中的所有颜色值。**返回** `array<string, string>`（颜色名称 → 计算后的值）。

```php
use TailwindPHP\tw;

tw::colors();
// ['red-500' => 'oklch(63.7% .237 25.331)', 'blue-500' => 'oklch(62.3% .214 259.815)', ...]

// With a custom theme
tw::colors('@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');
// [..., 'brand' => '#3b82f6']
```

## tw::breakpoints()

```php
public static function breakpoints(string $css = '@import "tailwindcss";'): array
```

返回主题中的所有断点值。**返回** `array<string, string>`（断点名称 → 值）。

```php
use TailwindPHP\tw;

tw::breakpoints();
// ['sm' => '40rem', 'md' => '48rem', 'lg' => '64rem', 'xl' => '80rem', '2xl' => '96rem']

tw::breakpoints('@import "tailwindcss"; @theme { --breakpoint-xs: 20rem; }');
// ['sm' => '40rem', ..., '2xl' => '96rem', 'xs' => '20rem']
```

## tw::spacing()

```php
public static function spacing(string $css = '@import "tailwindcss";'): array
```

返回主题中的自定义间距值。**返回** `array<string, string>`（间距名称 → 值）。

```php
use TailwindPHP\tw;

// TailwindCSS 4 uses a single --spacing base value rather than a --spacing-* namespace.
// This returns any custom --spacing-* values defined in the theme.
tw::spacing('@import "tailwindcss"; @theme { --spacing-huge: 10rem; }');
// ['huge' => '10rem']
```

## 输入格式

检查方法（`generate`、`properties`、`computedProperties`、`value`、`computedValue`）接受三种输入形式：

| 格式 | 示例 |
|---|---|
| 仅字符串 | `tw::generate('<div class="flex">')` |
| 字符串 + CSS 字符串 | `tw::generate('<div class="flex">', '@import "tailwindcss"; @theme { ... }')` |
| 带有 `content`（+ 可选 `css`）的数组 | `tw::generate(['content' => '<div class="flex">', 'css' => '@import "tailwindcss";'])` |

```php
use TailwindPHP\tw;

// Format 1: string only
tw::properties('p-4');

// Format 2: string + CSS
tw::properties('bg-brand', '@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');

// Format 3: array
tw::properties(['content' => 'p-4', 'css' => '@import "tailwindcss";']);
```

## TailwindCompiler 实例方法

[`tw::compile()`](#twcompile) 返回的对象提供与静态类相同的检查接口，并绑定到其编译时使用的 CSS。使用它可以避免每次调用都重新解析主题。

```php
public function generate(string $content, bool $minify = false): string
public function css(array $candidates, bool $minify = false): string
public function generateExact(string $content, bool $minify = false): string
public function cssExact(array $candidates, bool $minify = false): string
public function extractCandidates(string $html): array
public function extractCandidatesFromStrings(string $source): array
public function properties(string|array $utilities): array
public function computedProperties(string|array $utilities): array
public function value(string $utility): ?string
public function computedValue(string $utility): ?string
public function minify(string $css): string
public function colors(): array
public function breakpoints(): array
public function spacing(): array
```

```php
use TailwindPHP\tw;

$compiler = tw::compile('@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');

$css        = $compiler->generate('<div class="flex p-4 bg-brand">');
$candidates = $compiler->extractCandidates('<div class="flex p-4 bg-brand">');

$compiler->properties('bg-brand');          // ['background-color' => 'var(--color-brand)']
$compiler->computedProperties('bg-brand');   // ['background-color' => '#3b82f6']
$compiler->value('bg-brand');                // 'var(--color-brand)'
$compiler->computedValue('bg-brand');        // '#3b82f6'

$minified = $compiler->minify($css);

$compiler->colors();        // all color values
$compiler->breakpoints();   // all breakpoint values
$compiler->spacing();       // custom spacing values
```

### 累积生成与精确生成

`generate()` 和 `css()` 会**累积**：每次调用都会将其候选项加入编译器不断扩大的集合，返回的样式表包含截至目前见过的所有内容。这适合跨多个模板逐步构建单个样式表。

`generateExact()` 和 `cssExact()` 每次调用都会**精确**编译给定内容或候选项，调用之间不会沿用状态，同时仍会重复使用编译器已解析的设计系统。输出与对相同内容进行冷启动 `tw::generate()` 所得结果一致。这是通过一个长期运行的编译器为每个页面构建 CSS 的最快方式：

```php
use TailwindPHP\tw;

$compiler = tw::compile($themeCss);

foreach ($pages as $slug => $html) {
    $perPageCss[$slug] = $compiler->generateExact($html, true);
}
```

这四种方法都接受可选的 `$minify` 标志，可在序列化时输出压缩后的 CSS，与 `tw::generate(['minify' => true])` 逐字节相同，而且比事后压缩格式化输出更省资源。

### 高级检查器

如需直接检查已编译的状态：

```php
public function getTheme(): Theme
public function getDesignSystem(): object
public function getCompiled(): array
```

```php
$compiler->getTheme();        // Theme object with resolved values
$compiler->getDesignSystem(); // Design system: utilities, variants, etc.
$compiler->getCompiled();     // Raw compiled state array
```

这些方法会返回内部结构；请参阅 [架构](https://tailwindphp.inline0.dev/zh/docs/advanced/architecture)，了解其中包含的内容。

### 底层函数

`tw` 类封装了 `TailwindPHP` 中的一组命名空间函数。当你需要原始编译结果而非 `TailwindCompiler` 时，这些函数很有用：

| 函数 | 用途 |
|---|---|
| `compile(string $css, array $options = []): array` | 解析并编译 CSS。返回 `build`（累积式）和 `buildExact` 闭包，它们接受候选项和可选的 `$minify` 标志，还会返回 `sources`、`root`、`features` 和 `designSystem`。接受与 [`tw::compile()`](#twcompile) 相同的选项，但不包括 `stateCacheFile` |
| `StateCache\compileCssCached(string $css, string $cacheFile, array $options = []): array` | 使用持久化的 [编译器状态缓存](https://tailwindphp.inline0.dev/zh/docs/advanced/caching#compiler-state-cache)进行 `compile()` |
| `parseCssState()`、`finalizeCssState()`、`compileParsed()` | 解析的两个阶段（可序列化状态，然后从中重建闭包），以及 `compileCssCached()` 使用的最终组装步骤。`parseCss()` 和 `compileAst()` 仍是一步完成的等效方法 |

```php
use function TailwindPHP\compile;

$compiled = compile('@import "tailwindcss";');
$css = $compiled['build'](['flex', 'p-4'], true); // minified
```

## 缓存

`tw::generate()` 可以将编译后的 CSS 缓存到磁盘，以便相同输入跳过重新编译。

| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| `cache` | `bool \| string` | `false` | `true` 启用默认目录；路径字符串会将缓存存放在该路径 |
| `cacheTtl` | `int` | 无 | 缓存有效期（秒）；过期条目会重新编译 |

```php
use TailwindPHP\tw;

// Default directory: sys_get_temp_dir() . '/tailwindphp'
$css = tw::generate([
    'content' => '<div class="flex p-4">',
    'cache' => true,
]);

// Custom directory + TTL
$css = tw::generate([
    'content' => '<div class="flex p-4">',
    'cache' => '/path/to/cache',
    'cacheTtl' => 3600, // expire after 1 hour
]);
```

缓存键根据**内容**、**CSS 配置**和 **minify** 选项生成，因此不同输入会产生不同的缓存文件。使用 [`tw::clearCache()`](#twclearcache) 或独立的 `TailwindPHP\clearCache()` 函数清除条目。

更深入的指南请参阅 [缓存和压缩](https://tailwindphp.inline0.dev/zh/docs/advanced/caching)。
