### Install and initialize the bundle Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Install the bundle and initialize your app. The init command asks a few questions about your setup and prepares things to go. ```terminal $ composer require symfonycasts/tailwind-bundle $ php bin/console tailwind:init ``` -------------------------------- ### createProcess Usage Example Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-binary.md Demonstrates how to instantiate TailwindBinary and execute a build process. ```php use Symfonycasts ailwindBundle ailwindBinary; $binary = new TailwindBinary('/var/www/var/tailwind', '/var/www', null, 'v4.1.0'); $process = $binary->createProcess(['-i', 'assets/styles/app.css', '-o', 'var/tailwind/app.built.css']); $process->run(); echo $process->getOutput(); ``` -------------------------------- ### getVersion Usage Example Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-binary.md Demonstrates how to retrieve the Tailwind version with error handling. ```php $binary = new TailwindBinary('/var/www/var/tailwind', '/var/www', null, null); try { $version = $binary->getVersion(); } catch (\RuntimeException $e) { fwrite(STDERR, 'Unable to detect tailwind version: '.$e->getMessage()); } ``` -------------------------------- ### getBinaryName Usage Example Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-binary.md Examples of generating binary names for different platforms. ```php $name = TailwindBinary::getBinaryName('v4.1.0', 'linux-x64'); // "tailwindcss-linux-x64" $name = TailwindBinary::getBinaryName('v3.4.17', 'windows-x64'); // "tailwindcss-windows-x64.exe" ``` -------------------------------- ### runInit(): Process Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Runs the Tailwind binary with the `init` command to scaffold a `tailwind.config.js` file (for v3). Returns a started Process. ```APIDOC ## runInit(): Process ### Description Runs the Tailwind binary with the `init` command to scaffold a `tailwind.config.js` file (for v3). Returns a started Process. ### Method runInit ### Signature ```php public function runInit(): Process ``` ### Parameters None. ### Returns A started `Process` running ` init` (used by `tailwind:init` to scaffold `tailwind.config.js` for v3). ### Throws None directly (the underlying binary failure surfaces as a non-successful exit code). ``` -------------------------------- ### runInit method implementation Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Starts a process running ' init' to scaffold tailwind.config.js for v3. Writes the command line in verbose mode. ```php public function runInit(): Process { $binary = $this->createBinary(); $process = $binary->createProcess(['init']); if ($this->output->isVerbose()) { $this->output->writeln([ ' Command:', ' '.$process->getCommandLine(), ]); } $process->start(); return $process; } ``` -------------------------------- ### Example configuration for symfonycasts_tailwind.yaml Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/configuration.md Example YAML configuration for the SymfonyCasts Tailwind Bundle, showing input_css, config_file, binary_version, and other options. Comments indicate defaults and mutual exclusions. ```yaml # config/packages/symfonycasts_tailwind.yaml symfonycasts_tailwind: input_css: - 'assets/styles/app.css' - 'assets/styles/print.css' config_file: 'tailwind.config.js' # binary: 'node_modules/.bin/tailwindcss' # mutually exclusive with binary_version binary_version: 'v4.1.0' binary_platform: 'auto' # or 'linux-x64', 'macos-arm64', ... postcss_config_file: 'postcss.config.js' # v3 only strict_mode: true # false in test env by default process_timeout: 120 # 0 disables the timeout ``` -------------------------------- ### Interactive tailwind:init command example Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-init.md Shows the command invocation and the expected prompts with default answers for binary management and major version. ```bash php bin/console tailwind:init # Are you managing your own Tailwind CSS binary (if unsure, choose no and one will be downloaded)? [yes/no] no # Which major version do you wish to use? [4] 4 ``` -------------------------------- ### Programmatic Usage Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-build.md Example of running the build process programmatically within a kernel. ```php // programmatic equivalent inside a kernel $builder = $container->get('.tailwind.builder'); // private in prod; use a compiler pass to fetch it $process = $builder->runBuild(watch: false, poll: false, minify: true); $process->wait(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-build.md Common CLI commands for building, minifying, watching, and configuring the Tailwind build. ```bash # one-shot build of the first configured input file php bin/console tailwind:build # build a specific input, minified (for deployment) php bin/console tailwind:build assets/styles/print.css --minify # watch for changes (v3/v4) with filesystem polling (v3 only) php bin/console tailwind:build --watch --poll # v3: use a specific PostCSS config for this run php bin/console tailwind:build --postcss='postcss.config.js' ``` -------------------------------- ### Usage Example Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-version-finder.md Shows how to instantiate TailwindVersionFinder and call latestVersionFor with different version strings, catching the possible exceptions. ```php use Symfonycasts\TailwindBundle\TailwindVersionFinder; $finder = new TailwindVersionFinder(); try { $latest = $finder->latestVersionFor('4'); // e.g. "v4.1.6" $latest = $finder->latestVersionFor('v3.4.17'); // latest 3.x } catch (\InvalidArgumentException $e) { // "Cannot parse major version from ..." } catch (\RuntimeException $e) { // "Could not find a Tailwind CSS x.x release." } ``` -------------------------------- ### Install Flowbite package Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Install the Flowbite package via npm to use plugins like Flowbite Datepicker. ```terminal $ npm install flowbite ``` -------------------------------- ### runBuild method signature Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Declares the runBuild method with parameters for watch, poll, minify, inputFile, and postCssConfigFile. Returns a started Process. ```php public function runBuild( bool $watch, bool $poll, bool $minify, ?string $inputFile = null, ?string $postCssConfigFile = null, ): Process ``` -------------------------------- ### runBuild(bool $watch, bool $poll, bool $minify, ?string $inputFile = null, ?string $postCssConfigFile = null): Process Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Builds Tailwind CSS by running the Tailwind binary with the given options. Returns a started Process that the caller must wait on or poll. ```APIDOC ## runBuild(bool $watch, bool $poll, bool $minify, ?string $inputFile = null, ?string $postCssConfigFile = null): Process ### Description Builds Tailwind CSS by running the Tailwind binary with the given options. Returns a started Process that the caller must wait on or poll. ### Method runBuild ### Signature ```php public function runBuild( bool $watch, bool $poll, bool $minify, ?string $inputFile = null, ?string $postCssConfigFile = null, ): Process ``` ### Parameters - **watch** (bool) - Required - Add `--watch`; sets no process timeout and feeds an `InputStream` so the process stays alive. - **poll** (bool) - Required - Add `--poll` (filesystem polling). Throws when the binary is v4. - **minify** (bool) - Required - Add `--minify`. - **inputFile** (?string) - Optional - Input CSS file to compile; defaults to the first configured input path. Must be one of the configured inputs. - **postCssConfigFile** (?string) - Optional - Overrides the constructor's PostCSS config path for this run. ### Returns A started `Symfony\Component\Process\Process` (the caller must `wait()` or poll it). The command built is: ``` [-c ] -i -o /.built.css [--watch [--poll]] [--minify] [--postcss ] ``` The `-c` config argument is only added when the binary is **not** v4; `--watch`/`--poll`/`--minify`/`--postcss` are only appended when requested. ### Throws - `\InvalidArgumentException` - `The input CSS file "%s" is not one of the configured input files.` when `$inputFile` resolves to a path not in the configured inputs. - `\InvalidArgumentException` - `The --poll option is not supported in Tailwind CSS v4.0.0 and later.` when `$poll` is true and the binary is v4. - `\InvalidArgumentException` - `Custom PostCSS configuration is not supported in Tailwind CSS v4.0.0 and later.` when a PostCSS config is effective (constructor value or `$postCssConfigFile`) and the binary is v4. - `\InvalidArgumentException` - `The PostCSS config file "%s" does not exist.` from `validatePostCssConfigFile()` when a provided PostCSS config file is missing both as-is and relative to `projectRootDir`. ### Notes In watch mode `$process->setTimeout(null)` is applied and an `InputStream` is set as input ("setting an input stream causes the command to 'wait' for the watch"). Otherwise the timeout is `$this->processTimeout ?: null` (`0` → `null` = disabled). ### Example ```php use Symfonycasts\TailwindBundle\TailwindBuilder; $builder = new TailwindBuilder( '/var/www', ['assets/styles/app.css', 'assets/styles/second.css'], '/var/www/var/tailwind', binaryVersion: 'v4.1.0', ); // one-shot production build (minified) $process = $builder->runBuild(watch: false, poll: false, minify: true, inputFile: 'assets/styles/app.css'); $process->wait(); if (!$process->isSuccessful()) { throw new \RuntimeException('Tailwind build failed: '.$process->getErrorOutput()); } ``` ```php // watch mode with polling (v3 only) $process = $builder->runBuild(watch: true, poll: true, minify: false); while ($process->isRunning()) { // $process->getIncrementalOutput() ... usleep(100_000); } ``` ``` -------------------------------- ### Install Tailwind via npm Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Installs the Tailwind CSS package using npm to allow for extra plugins. ```terminal $ npm add tailwindcss ``` -------------------------------- ### Test kernel setup with strict mode off - TailwindCssAssetCompiler Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-css-asset-compiler.md Shows how to set up a test kernel with strict mode off, swapping a built asset into app.css. After booting, requesting the asset returns the contents of var/tailwind/app.built.css, or the raw source CSS when the built file does not exist and strict_mode is false. ```php // In a test kernel: swap a built asset into app.css (strict mode off) $kernel = new TailwindTestKernel('test', false, [ 'input_css' => [__DIR__.'/assets/styles/app.css'], 'binary_version' => 'v3.4.17', ]); $kernel->boot(); // requesting the asset now returns the contents of var/tailwind/app.built.css // (or the raw source CSS when the built file does not exist and strict_mode is false) ``` -------------------------------- ### TailwindBuilder::getInternalOutputCssPath example output Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/types.md Shows the resulting path string when the input is 'assets/styles/app.css' and the tailwindVarDir is '/var/www/var/tailwind'. ```php // input 'assets/styles/app.css', tailwindVarDir '/var/www/var/tailwind' '/var/www/var/tailwind/app.built.css' ``` -------------------------------- ### Usage example for getOutputCssContent() with exception handling Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Shows how to call getOutputCssContent() and catch the RuntimeException to display the error message, which tells the developer to run 'php bin/console tailwind:build'. ```php try { $css = $builder->getOutputCssContent('assets/styles/app.css'); } catch (\RuntimeException $e) { // tell the developer to run "php bin/console tailwind:build" echo $e->getMessage(); } ``` -------------------------------- ### Shell Error Handling Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-build.md Example of handling build errors at the shell level. ```bash # error handling at the shell level php bin/console tailwind:build --poll && echo OK || echo "Build failed (check the error above)" ``` -------------------------------- ### Add Tailwind build as Symfony CLI worker Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Configure the Symfony CLI to start the tailwind:build command as a worker whenever you run symfony server:start. If running as a daemon, use symfony server:log to tail the worker output. ```yaml # .symfony.local.yaml workers: # ... tailwind: cmd: ['symfony', 'console', 'tailwind:build', '--watch'] ``` -------------------------------- ### tailwind:update execute() method (PHP) Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-update.md Protected method implementing the command logic. Throws RuntimeException when a locally managed binary is configured, when no version is available, or when a non-standard setup is detected. Updates binary_version in config and returns Command::SUCCESS. ```php protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); if ($this->binaryPath) { throw new \RuntimeException('Cannot update: you are managing your own Tailwind CSS binary. Update it manually.'); } if (!$this->binaryVersion) { throw new \RuntimeException('Cannot determine the current version. Set "binary_version" in your symfonycasts_tailwind config (or run "tailwind:init").'); } $io->note(\sprintf('Current version: %s — looking for the latest release in the same major...', $this->binaryVersion)); $latestVersion = $this->versionFinder->latestVersionFor($this->binaryVersion); if ($latestVersion === $this->binaryVersion) { $io->success(\sprintf('Already on the latest version (%s). Nothing to do!', $latestVersion)); return self::SUCCESS; } $bundleConfig = $this->bundleConfig(); if (!$bundleConfig) { throw new \RuntimeException('You are using a non-standard Symfony setup. Update "binary_version" in your config manually.'); } $bundleConfig['symfonycasts_tailwind']['binary_version'] = $latestVersion; $this->writeBundleConfig($bundleConfig); $io->success(\sprintf('Tailwind CSS updated from %s to %s!', $this->binaryVersion, $latestVersion)); $io->warning('Run "php bin/console cache:clear" so the updated configuration is picked up.'); $io->warning('If "tailwind:build --watch" is running, restart it to use the new version.'); return self::SUCCESS; } ``` -------------------------------- ### Catch missing built CSS file in strict mode Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/errors.md Example of catching a RuntimeException when strict_mode is enabled and the build was skipped, indicating the built CSS file is missing. The error message suggests running the tailwind:build command. ```php // in a kernel/test, when strict_mode is on and the build was skipped: try { $assetMapper->getMappedAsset('styles/app.css'); } catch (\RuntimeException $e) { // 'Built Tailwind CSS file does not exist: run "php bin/console tailwind:build" to generate it' } ``` -------------------------------- ### configure() Method Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-build.md Defines the arguments and options available for the command. ```php protected function configure(): void { $this ->addArgument('input_css', InputArgument::OPTIONAL, 'The input CSS file to compile') ->addOption('watch', 'w', null, 'Watch for changes and rebuild automatically') ->addOption('poll', null, null, 'Use polling instead of filesystem events when watching') ->addOption('minify', 'm', InputOption::VALUE_NONE, 'Minify the output CSS') ->addOption('postcss', null, InputOption::VALUE_REQUIRED, 'Load custom PostCSS configuration') ; } ``` -------------------------------- ### Configure symfonycasts_tailwind bundle with input_css and binary_platform Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/symfonycasts-tailwind-bundle.md YAML configuration demonstrating how to set input CSS files and override binary platform auto-detection with binary_platform. ```yaml # config/packages/symfonycasts_tailwind.yaml symfonycasts_tailwind: input_css: - 'assets/styles/app.css' - 'assets/styles/print.css' binary_platform: 'linux-x64' # override auto-detection ``` -------------------------------- ### execute() method implementation for tailwind:init Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-init.md The main command logic that prompts for binary management or version, writes config, creates Tailwind config, and adds directives. Throws RuntimeException if not interactive, returns FAILURE if config creation fails, and warns to clear cache on success. ```php protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); if (!$input->isInteractive()) { throw new \RuntimeException('tailwind:init command must be run interactively.'); } $bundleConfig = $this->bundleConfig(); if ($io->confirm('Are you managing your own Tailwind CSS binary (if unsure, choose no and one will be downloaded)?', false)) { $binaryPath = $io->ask('Enter the path to your Tailwind CSS binary:', 'node_modules/.bin/tailwindcss'); $bundleConfig['symfonycasts_tailwind']['binary'] = $binaryPath; } else { $majorVersion = $io->ask('Which major version do you wish to use?', '4'); $latestVersion = $this->versionFinder->latestVersionFor($majorVersion); $bundleConfig['symfonycasts_tailwind']['binary_version'] = $latestVersion; } $this->writeBundleConfig($bundleConfig); $builder = new TailwindBuilder( $this->rootDir, $this->inputCss, $this->rootDir.'/var/tailwind', binaryPath: $bundleConfig['symfonycasts_tailwind']['binary'] ?? null, binaryVersion: $bundleConfig['symfonycasts_tailwind']['binary_version'] ?? null, ); if (!$this->createTailwindConfig($io, $builder)) { return self::FAILURE; } $this->addTailwindDirectives($io, $builder); $io->success('Tailwind CSS is ready to use!'); $io->warning('Run "php bin/console cache:clear" so the updated configuration is picked.'); return self::SUCCESS; } ``` -------------------------------- ### Add Flowbite plugin to Tailwind config Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Add the Flowbite plugin to tailwind.config.js after installing the package. ```javascript module.exports = { plugins: [ require('flowbite/plugin') ] } ``` -------------------------------- ### getVersion(): string Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-binary.md Returns the configured binaryVersion, or parses the version from the binary's --help output. The parsed value is cached on the instance. ```APIDOC ## getVersion(): string ### Description Returns the configured binaryVersion, or parses the version from the binary's --help output. The parsed value is cached on the instance. ### Method getVersion ### Signature public function getVersion(): string ### Parameters None. ### Returns The configured binaryVersion, or the version parsed from the binary's --help output (first v\d+.\d+.\d+ match, e.g. v4.1.0). The parsed value is cached on the instance. ### Throws - \RuntimeException with message Could not determine the tailwindcss version. when the --help process fails or its output contains no version pattern. ### Example ```php $binary = new TailwindBinary('/var/www/var/tailwind', '/var/www', null, null); try { $version = $binary->getVersion(); } catch (\RuntimeException $e) { fwrite(STDERR, 'Unable to detect tailwind version: '.$e->getMessage()); } ``` ``` -------------------------------- ### Usage pattern in TailwindUpdateCommand::execute() Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-config.md Shows the typical workflow of reading the config, modifying a value, and writing it back. ```php // TailwindUpdateCommand::execute() — the working pattern in consumers of this base $bundleConfig = $this->bundleConfig(); $bundleConfig['symfonycasts_tailwind']['binary_version'] = $latestVersion; $this->writeBundleConfig($bundleConfig); ``` -------------------------------- ### TailwindBinary constructor Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-binary.md Constructor accepts binary download directory, working directory, optional binary path/version, console output, HTTP client, and platform override. If both binaryPath and binaryVersion are set, binaryVersion is discarded. ```php public function __construct( private string $binaryDownloadDir, private string $cwd, private ?string $binaryPath, private ?string $binaryVersion, private ?SymfonyStyle $output = null, ?HttpClientInterface $httpClient = null, private string $binaryPlatform = 'auto', ) ``` -------------------------------- ### runBuild command template Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Shows the command structure built by runBuild. The -c config argument is only added when the binary is not v4; --watch/--poll/--minify/--postcss are appended only when requested. ```text [-c ] -i -o /.built.css [--watch [--poll]] [--minify] [--postcss ] ``` -------------------------------- ### TailwindInitCommand constructor Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-init.md Constructor for TailwindInitCommand. Injects TailwindVersionFinder, the input CSS paths array, and the project root directory forwarded to the parent. ```php public function __construct( private TailwindVersionFinder $versionFinder, private array $inputCss, string $rootDir, ) ``` -------------------------------- ### Programmatic equivalent of tailwind:init Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-init.md PHP code that skips the interactive prompts by directly creating a TailwindVersionFinder and TailwindBuilder with a binary version. ```php // programmatic equivalent (skipping the interactive prompts) $finder = new TailwindVersionFinder(); $builder = new TailwindBuilder($rootDir, ['assets/styles/app.css'], $rootDir.'/var/tailwind', binaryVersion: $finder->latestVersionFor('4')); ``` -------------------------------- ### Constructor for TailwindConfigCommand Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-config.md Constructor accepting the project root directory as a protected property, used to compute the bundle config file path. ```php public function __construct( protected string $rootDir, ) ``` -------------------------------- ### One-shot production build with runBuild Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Creates a TailwindBuilder with v4.1.0 binary and runs a minified production build for a specific input file, waiting for completion and throwing on failure. ```php use Symfonycasts\TailwindBundle\TailwindBuilder; $builder = new TailwindBuilder( '/var/www', ['assets/styles/app.css', 'assets/styles/second.css'], '/var/www/var/tailwind', binaryVersion: 'v4.1.0', ); // one-shot production build (minified) $process = $builder->runBuild(watch: false, poll: false, minify: true, inputFile: 'assets/styles/app.css'); $process->wait(); if (!$process->isSuccessful()) { throw new \RuntimeException('Tailwind build failed: '.$process->getErrorOutput()); } ``` -------------------------------- ### bundleConfigFile() method Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-config.md Returns the path to the bundle's YAML configuration file under the project root. ```php protected function bundleConfigFile(): string { return $this->rootDir.'/config/packages/symfonycasts_tailwind.yaml'; } ``` -------------------------------- ### getConfigFilePath(): string Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Returns the configured `tailwind.config.js` path. ```APIDOC ## getConfigFilePath(): string ### Description Returns the configured `tailwind.config.js` path. ### Method getConfigFilePath ### Signature ```php public function getConfigFilePath(): string ``` ### Parameters None. ### Returns The configured `tailwind.config.js` path (default `'tailwind.config.js'`). ``` -------------------------------- ### Dump bundle configuration Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Dump the full configuration of the symfonycasts_tailwind bundle. ```terminal $ php bin/console config:dump symfonycasts_tailwind ``` -------------------------------- ### Constructor Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-version-finder.md The constructor accepts an optional HttpClientInterface. If a GitHub token is available, it wraps the client in a ScopingHttpClient for the GitHub API base URI with auth_bearer to avoid rate limits. ```php public function __construct(?HttpClientInterface $httpClient = null) { $httpClient ??= HttpClient::create(); // authenticate calls when a GitHub token is available to avoid the low // rate limit applied to anonymous requests (60 requests per hour, // shared by IP address) if (null !== $token = self::githubToken()) { $httpClient = ScopingHttpClient::forBaseUri($httpClient, 'https://api.github.com/', [ 'auth_bearer' => $token, ]); } $this->httpClient = $httpClient; } ``` -------------------------------- ### Handle build failures with try-catch Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/errors.md Recommended consumer handling for non-throwing failure signals. Catches InvalidArgumentException for bad build options, LogicException for missing configuration, and RuntimeException for build/network failures, writing messages to STDERR. ```php try { $builder->runBuild(watch: false, poll: false, minify: true)->wait(); } catch (\InvalidArgumentException $e) { fwrite(STDERR, 'Bad build options: '.$e->getMessage()); } catch (\LogicException $e) { fwrite(STDERR, 'Configure the bundle first: '.$e->getMessage()); } catch (\RuntimeException $e) { fwrite(STDERR, 'Build/network failure: '.$e->getMessage()); } ``` -------------------------------- ### createBinary() method implementation Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Lazily creates and caches a TailwindBinary instance using the builder's constructor settings. Throws a LogicException via TailwindBinary::getBinaryPath() if neither binaryPath nor binaryVersion is configured. ```php public function createBinary(): TailwindBinary { return $this->binary ??= new TailwindBinary($this->tailwindVarDir, $this->projectRootDir, $this->binaryPath, $this->binaryVersion, $this->output, null, $this->binaryPlatform); } ``` -------------------------------- ### bundleConfig() method Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-config.md Parses and returns the bundle configuration array. Throws a RuntimeException if the symfony/yaml package is missing, and returns an empty array if the config file does not exist. ```php protected function bundleConfig(): array { if (!class_exists(Yaml::class)) { throw new \RuntimeException('You are using a non-standard Symfony setup. You will need to manage the bundle configuration manually.'); } if (!file_exists($this->bundleConfigFile())) { return []; } return Yaml::parseFile($this->bundleConfigFile()); } ``` -------------------------------- ### getVersion Method Definition Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-binary.md Defines the getVersion method which returns the configured version or parses it from the binary's --help output. ```php public function getVersion(): string { if ($this->binaryVersion) { return $this->binaryVersion; } $process = $this->createProcess(['--help']); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException('Could not determine the tailwindcss version.'); } if (!preg_match('#(v\d+\.\d+\.\d+)#', $process->getOutput(), $matches)) { throw new \RuntimeException('Could not determine the tailwindcss version.'); } return $this->binaryVersion = $matches[1]; } ``` -------------------------------- ### Configure binary option Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Instructs the bundle to use a specific Tailwind binary path. ```yaml # config/packages/symfonycasts_tailwind.yaml symfonycasts_tailwind: binary: 'node_modules/.bin/tailwindcss' ``` -------------------------------- ### getConfigFilePath method implementation Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Returns the configured tailwind.config.js path, defaulting to 'tailwind.config.js'. ```php public function getConfigFilePath(): string { return $this->configPath; } ``` -------------------------------- ### Configure input_css option Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Sets the source Tailwind CSS file path in the bundle configuration. ```yaml # config/packages/symfonycasts_tailwind.yaml symfonycasts_tailwind: input_css: 'assets/styles/other.css' ``` -------------------------------- ### Constructor for TailwindUpdateCommand Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-update.md Constructor signature for TailwindUpdateCommand, injecting TailwindVersionFinder, rootDir, binaryPath, and binaryVersion. The rootDir is forwarded to the parent TailwindConfigCommand. ```php public function __construct( private TailwindVersionFinder $versionFinder, string $rootDir, private ?string $binaryPath, private ?string $binaryVersion, ) ``` -------------------------------- ### Configure multiple input_css files Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Allows providing an array of multiple input CSS files. ```yaml # config/packages/symfonycasts_tailwind.yaml symfonycasts_tailwind: input_css: - 'assets/styles/other.css' - 'assets/styles/another.css' ``` -------------------------------- ### getOutputCssContent() method implementation Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Returns the contents of the built CSS file for the given input file. Throws a RuntimeException with a specific message if the built file does not exist, instructing to run 'php bin/console tailwind:build'. ```php public function getOutputCssContent(string $inputFile): string { if (!is_file($this->getInternalOutputCssPath($inputFile))) { throw new \RuntimeException('Built Tailwind CSS file does not exist: run "php bin/console tailwind:build" to generate it'); } return file_get_contents($this->getInternalOutputCssPath($inputFile)); } ``` -------------------------------- ### Constructor Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-build.md The constructor for the TailwindBuildCommand, requiring the TailwindBuilder service. ```php public function __construct( private TailwindBuilder $tailwindBuilder, ) ``` -------------------------------- ### Build minified CSS before compiling asset map Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Run tailwind:build with --minify before asset-map:compile during deployment so the built file is available. ```terminal $ php bin/console tailwind:build --minify $ php bin/console asset-map:compile ``` -------------------------------- ### createBinary(): TailwindBinary Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Creates and returns a lazily created and cached TailwindBinary instance wired with the builder's constructor settings. Throws a LogicException when neither binaryPath nor binaryVersion is configured. ```APIDOC ## createBinary(): TailwindBinary ### Description Creates and returns a lazily created and cached TailwindBinary instance wired with the builder's constructor settings (download dir = `tailwindVarDir`, cwd = `projectRootDir`). ### Method PHP method ### Endpoint `TailwindBuilder::createBinary()` ### Parameters None. ### Returns - **TailwindBinary** - A lazily created and cached TailwindBinary instance. ### Throws - **\LogicException** - Via `TailwindBinary::getBinaryPath()` when neither `binaryPath` nor `binaryVersion` is configured. ``` -------------------------------- ### tailwind:init command declaration Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-init.md Declares the tailwind:init command with its name and description, extending TailwindConfigCommand. The class is marked @internal and final. ```php #[AsCommand( name: 'tailwind:init', description: 'Initializes Tailwind CSS for your project', )] final class TailwindInitCommand extends TailwindConfigCommand { ... } ``` -------------------------------- ### Configure the TailwindBundle definitions (src/SymfonycastsTailwindBundle.php) Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/configuration.md This snippet shows the `configure` method of the `SymfonycastsTailwindBundle` class, where all bundle configuration options are declared using Symfony's `DefinitionConfigurator`. It defines nodes for each option: `input_css` (array with scalar prototype and cast-to-array normalization), `config_file`, `binary`, `binary_version` (with normalization to prepend 'v'), `binary_platform` (enum), `postcss_config_file`, `strict_mode` (boolean), and `process_timeout` (integer). The defaults and info messages match the option table, but the code uses `defaultNull()` for options that default to `null` in the table. Note that the table lists `binary_platform` values including `auto`, which is the default, and the code uses `self::PLATFORMS` constant for the enum values. ```php public function configure(DefinitionConfigurator $definition): void { $definition->rootNode() ->children() ->arrayNode('input_css') ->prototype('scalar')->end() ->beforeNormalization()->castToArray()->end() ->info('Paths to CSS files to process through Tailwind') ->defaultValue(['%kernel.project_dir%/assets/styles/app.css']) ->end() ->scalarNode('config_file') ->info('Path to the tailwind.config.js file') ->defaultValue('%kernel.project_dir%/tailwind.config.js') ->end() ->scalarNode('binary') ->info('The tailwind binary to use instead of downloading a new one') ->defaultNull() ->end() ->scalarNode('binary_version') ->info('Tailwind CLI version to download - required unless "binary" is set (run "tailwind:init" to configure)') ->defaultNull() ->beforeNormalization() ->ifString() ->then(static function (string $version): string { return 'v'.ltrim($version, 'vV'); }) ->end() ->end() ->enumNode('binary_platform') ->values(self::PLATFORMS) ->info('Tailwind CLI platform to download - "auto" will try to detect the platform automatically') ->defaultValue('auto') ->end() ->scalarNode('postcss_config_file') ->info('Path to PostCSS config file which is passed to the Tailwind CLI') ->defaultNull() ->end() ->booleanNode('strict_mode') ->info('When enabled, an exception will be thrown if there are no built assets (default: false in `test` env, true otherwise)') ->defaultNull() ->end() ->integerNode('process_timeout') ->info('Timeout in seconds for the Tailwind build process - use "0" to disable') ->defaultValue(60) ->end() ->end(); } ``` -------------------------------- ### Configure binary_platform option Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Overrides the automatic platform detection for downloading the Tailwind binary. ```yaml # config/packages/symfonycasts_tailwind.yaml symfonycasts_tailwind: # one of: 'linux-arm64', 'linux-arm64-musl', 'linux-x64', 'linux-x64-musl', 'macos-arm64', 'macos-x64', 'windows-x64' binary_platform: 'linux-x64' ``` -------------------------------- ### Register SymfonycastsTailwindBundle in config/bundles.php Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/symfonycasts-tailwind-bundle.md PHP code that enables the bundle for all environments by adding SymfonycastsTailwindBundle::class with 'all' => true in the returns array. ```php // config/bundles.php use Symfonycasts\TailwindBundle\SymfonycastsTailwindBundle; return [ // ... SymfonycastsTailwindBundle::class => ['all' => true], ]; ``` -------------------------------- ### compile(string $content, MappedAsset $asset, AssetMapperInterface $assetMapper): string - TailwindCssAssetCompiler Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-css-asset-compiler.md Compiles the asset by registering the built CSS path as a file dependency and returning the full contents of /.built.css. The original content parameter is ignored and replaced entirely. Throws a RuntimeException with message 'Built Tailwind CSS file does not exist: run "php bin/console tailwind:build" to generate it' when the built file is missing, reachable in strict mode when tailwind:build has not been run. ```php public function compile(string $content, MappedAsset $asset, AssetMapperInterface $assetMapper): string { $asset->addFileDependency($this->tailwindBuilder->getInternalOutputCssPath($asset->sourcePath)); return $this->tailwindBuilder->getOutputCssContent($asset->sourcePath); } ``` -------------------------------- ### Non-interactive tailwind:init fails fast Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-init.md Invoking the command with --no-interaction throws a RuntimeException with the message 'tailwind:init command must be run interactively.' ```bash # non-interactive usage fails fast php bin/console tailwind:init --no-interaction # RuntimeException: "tailwind:init command must be run interactively." ``` -------------------------------- ### execute() Method Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-build.md The execution logic that triggers the build process via the TailwindBuilder. ```php protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $this->tailwindBuilder->setOutput($io); $process = $this->tailwindBuilder->runBuild( watch: $input->getOption('watch'), poll: $input->getOption('poll'), minify: $input->getOption('minify'), inputFile: $input->getArgument('input_css'), postCssConfigFile: $input->getOption('postcss'), ); $process->wait(static function ($type, $buffer) use ($io) { $io->write($buffer); }); if (!$process->isSuccessful()) { $io->error('Tailwind CSS build failed: see output above.'); return self::FAILURE; } return self::SUCCESS; } ``` -------------------------------- ### Strict-mode failure handling - TailwindCssAssetCompiler Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-css-asset-compiler.md Demonstrates the strict-mode failure when the built CSS file is missing. The exception is caught and its message is echoed, which is 'Built Tailwind CSS file does not exist: run "php bin/console tailwind:build" to generate it'. ```php // strict-mode failure surfaces as a RuntimeException during asset map compilation try { $mapped = $assetMapper->getMappedAsset('styles/app.css'); } catch (\RuntimeException $e) { echo $e->getMessage(); // 'Built Tailwind CSS file does not exist: run "php bin/console tailwind:build" to generate it' } ``` -------------------------------- ### loadExtension method in SymfonycastsTailwindBundle Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/symfonycasts-tailwind-bundle.md Loads the bundle's extension by importing services.php and injecting normalized config values into private service definitions. Computes strict_mode as the configured value or true unless the kernel environment is 'test'. Replaces arguments on .tailwind.css_asset_compiler, .tailwind.builder, .tailwind.command.init, and .tailwind.command.update. ```php public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void { $container->import('../config/services.php'); $strictMode = $config['strict_mode'] ?? ('test' !== $builder->getParameter('kernel.environment')); $builder->findDefinition('.tailwind.css_asset_compiler') ->replaceArgument(1, $strictMode) ; $builder->findDefinition('.tailwind.builder') ->replaceArgument(1, $config['input_css']) ->replaceArgument(3, $config['binary']) ->replaceArgument(4, $config['binary_version']) ->replaceArgument(5, $config['config_file']) ->replaceArgument(6, $config['postcss_config_file']) ->replaceArgument(7, $config['binary_platform']) ->replaceArgument(8, $config['process_timeout']) ; $builder->findDefinition('.tailwind.command.init') ->replaceArgument(1, $config['input_css']) ; $builder->findDefinition('.tailwind.command.update') ->replaceArgument(2, $config['binary']) ->replaceArgument(3, $config['binary_version']) ; } ``` -------------------------------- ### createProcess Method Definition Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-binary.md Defines the createProcess method which prepares a Symfony Process instance with the binary path and provided arguments. ```php public function createProcess(array $arguments = []): Process { // add binary to the front of the $arguments array array_unshift($arguments, $this->getBinaryPath()); return new Process($arguments, $this->cwd); } ``` -------------------------------- ### createProcess(array $arguments = []): Process Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-binary.md Creates a Symfony Process instance to run the Tailwind binary with the provided CLI arguments. The resolved binary path is automatically prepended to the arguments, and the working directory is set to the configured cwd. ```APIDOC ## createProcess(array $arguments = []): Process ### Description Creates a Symfony Process instance to run the Tailwind binary with the provided CLI arguments. The resolved binary path is automatically prepended to the arguments, and the working directory is set to the configured cwd. ### Method createProcess ### Signature public function createProcess(array $arguments = []): Process ### Parameters - **arguments** (array) - Optional - CLI arguments passed to the binary (the resolved binary path is prepended automatically). ### Returns A started-not-yet-run Symfony\Component\Process\Process whose command is [binaryPath, ...$arguments] and whose working directory is cwd. ### Throws - \LogicException from the private getBinaryPath() when neither binaryPath nor binaryVersion was provided - message: You must specify a "binary" or "binary_version" in your symfonycasts_tailwind config (or run "tailwind:init"). ### Example ```php use Symfonycasts\TailwindBundle\TailwindBinary; $binary = new TailwindBinary('/var/www/var/tailwind', '/var/www', null, 'v4.1.0'); $process = $binary->createProcess(['-i', 'assets/styles/app.css', '-o', 'var/tailwind/app.built.css']); $process->run(); echo $process->getOutput(); ``` ``` -------------------------------- ### TailwindBuilder Constructor Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md The constructor for initializing the TailwindBuilder with project paths, configuration, and binary settings. ```php public function __construct( private readonly string $projectRootDir, array $inputPaths, private readonly string $tailwindVarDir, private readonly ?string $binaryPath = null, private readonly ?string $binaryVersion = null, private readonly string $configPath = 'tailwind.config.js', private readonly ?string $postCssConfigPath = null, private readonly string $binaryPlatform = 'auto', private readonly int $processTimeout = 60, ) ``` -------------------------------- ### getInternalOutputCssPath method implementation Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Returns the built CSS path for a given input path, e.g., var/tailwind/app.built.css for assets/styles/app.css. ```php public function getInternalOutputCssPath(string $inputPath): string { $inputFileName = pathinfo($inputPath, \PATHINFO_FILENAME); return "{$this->tailwindVarDir}/{$inputFileName}.built.css"; } ``` -------------------------------- ### Command Declaration Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-build.md The class definition for the tailwind:build command. ```php #[AsCommand( name: 'tailwind:build', description: 'Builds the Tailwind CSS assets.', )] final class TailwindBuildCommand extends Command { ... } ``` -------------------------------- ### Configure binary_version option Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/doc/index.rst Sets a specific version for the Tailwind binary. ```yaml # config/packages/symfonycasts_tailwind.yaml symfonycasts_tailwind: binary_version: 'v3.3.0' ``` -------------------------------- ### getOutputCssContent(string $inputFile): string Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Returns the full contents of the built Tailwind CSS file for a given input CSS path. Throws a RuntimeException if the built file has not been generated yet. ```APIDOC ## getOutputCssContent(string $inputFile): string ### Description Returns the full contents of the built Tailwind CSS file for the given input CSS path. Throws a RuntimeException if the built file has not been generated yet. ### Method PHP method ### Endpoint `TailwindBuilder::getOutputCssContent(string $inputFile)` ### Parameters - **inputFile** (string) - Required - An input CSS path. ### Returns - **string** - The full contents of the built CSS file for that input. ### Throws - **\RuntimeException** - When the built file does not exist. Message: `Built Tailwind CSS file does not exist: run "php bin/console tailwind:build" to generate it` ### Example ```php try { $css = $builder->getOutputCssContent('assets/styles/app.css'); } catch (\RuntimeException $e) { // tell the developer to run "php bin/console tailwind:build" echo $e->getMessage(); } ``` ``` -------------------------------- ### writeBundleConfig() method Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/command-tailwind-config.md Writes the given configuration array to the bundle config file as YAML. ```php protected function writeBundleConfig(array $bundleConfig): void { file_put_contents($this->bundleConfigFile(), Yaml::dump($bundleConfig)); } ``` -------------------------------- ### setOutput method signature Source: https://github.com/symfonycasts/tailwind-bundle/blob/1.x/_autodocs/api-reference/tailwind-builder.md Sets the SymfonyStyle output for notes and verbose command lines. ```php public function setOutput(SymfonyStyle $output): void ```