본문으로 건너뛰기

API

전체 정적 표면은 TailwindPHP\tw라는 하나의 클래스에 있습니다(내부 Tailwind 클래스의 별칭). 모든 메서드는 정적으로 호출할 수 있으며, 검사 메서드(properties, computedProperties, value, computedValue)는 모두 이 페이지 하단에서 설명하는 입력 형식을 받습니다.

동일한 CSS 구성으로 반복 작업할 때는 tw::compile()을 한 번 호출하고 반환된 TailwindCompiler를 재사용하세요.

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 Tailwind 지시문이 포함된 입력 CSS(기본값 @import "tailwindcss";)
minify bool 출력 최소화(기본값 false)
importPaths string | array | callable | null 전체 @import 해석을 적용해 파일 시스템에서 CSS을 불러옵니다 — 가져오기CSS 참고
cache bool | string 파일 캐싱 사용 — 캐싱 참고
cacheTtl int 캐시 유효 기간(초)

tw::compile()

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

지정된 CSS에 연결된 재사용 가능한 TailwindCompiler를 생성합니다. 파싱과 디자인 시스템 구성은 한 번만 수행되므로 서로 다른 여러 콘텐츠 문자열에 대해 CSS를 생성할 때 효율적입니다. 호출 간에 하나의 스타일시트를 누적하려면 generate()를 사용하고, 페이지마다 독립적인 출력을 얻으려면 generateExact()를 사용합니다. 반환값 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 파일의 경로 — 컴파일러 상태 캐시 참고
polyfills int 내보낼 폴백을 TailwindPHP\POLYFILL_AT_PROPERTY의 비트마스크로 지정합니다(@property 변수의 @layer properties 기본값 및 color-mix() 앞에 적용되는 정적 색상 폴백 TailwindPHP\POLYFILL_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 인스턴스 메서드를 참고하세요.

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()와 비슷하지만, 모든 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()에 전달하세요. 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 문자열을 최소화합니다. 주석을 제거하고, 공백을 줄이며, 16진수 색상을 짧게 표기하고(#ffffff → #fff), 0 값의 단위를 제거하는 등(0px → 0)의 작업을 수행합니다. 반환값 string.

TailwindPHP이 직접 생성하는 CSS의 경우, minify 옵션(tw::generate(['minify' => true]))이나 컴파일러 메서드의 $minify 매개변수를 사용하세요. 이 경로는 직렬화 중에 최소화하므로 더 빠르고, 문자열 기반 처리에서 병합되는 하위 항목의 :not() 선택자를 보존합니다.

PHP
use TailwindPHP\tw;

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

전체 최적화 항목은 캐싱 및 최소화를 참고하세요.

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()가 반환하는 객체는 정적 클래스와 동일한 검사 기능을 제공하며, 컴파일에 사용한 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);
}

네 가지 메서드 모두 직렬화 중 최소화된 CSS를 출력하는 선택적 $minify 플래그를 허용합니다. 결과는 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

이 메서드들은 내부 구조를 반환합니다. 여기에 포함된 내용은 아키텍처를 참고하세요.

하위 수준 함수

tw 클래스는 TailwindPHP의 네임스페이스 함수들을 묶습니다. TailwindCompiler 대신 원시 컴파일 결과가 필요할 때 유용합니다:

함수 용도
compile(string $css, array $options = []): array CSS을 파싱하고 컴파일합니다. (누적 방식) build와 후보 및 선택적 $minify 플래그를 받는 buildExact 클로저, 그리고 sources, root, features, designSystem을 반환합니다. tw::compile()와 같은 옵션을 허용하지만 stateCacheFile는 제외됩니다
StateCache\compileCssCached(string $css, string $cacheFile, array $options = []): array 영구 컴파일러 상태 캐시를 사용해 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() 또는 독립 실행형 TailwindPHP\clearCache() 함수를 사용해 항목을 지우세요.

자세한 안내는 캐싱 및 최소화를 참고하세요.