Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Css Parser Laravel Package

sabberworm/php-css-parser

Parse and manipulate CSS in PHP with a fast, flexible parser. Convert CSS into an object model, inspect and edit rules, selectors, and declarations, then render back to CSS. Useful for minifying, rewriting assets, or building CSS tooling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require sabberworm/php-css-parser
    
  2. Basic Parsing:
    use Sabberworm\CSS\Parser;
    
    $css = file_get_contents('styles.css');
    $parser = new Parser($css);
    $document = $parser->parse();
    
  3. First Use Case: Output the parsed CSS with default formatting:
    echo $document->render();
    

Where to Look First

  • Documentation: Focus on the Parser, Document, RuleSet, and Rule classes.
  • Examples: The README provides practical use cases (e.g., modifying selectors, shrinking sizes).
  • Output Formatting: Explore OutputFormat for customizing rendered CSS.

Implementation Patterns

Common Workflows

  1. Parsing and Modifying CSS:

    $parser = new Parser($css);
    $document = $parser->parse();
    
    // Modify rules (e.g., add a prefix to all selectors)
    foreach ($document->getAllDeclarationBlocks() as $block) {
        foreach ($block->getSelectors() as $selector) {
            $selector->setSelector('.prefix-' . $selector->getSelector());
        }
    }
    
    // Output the modified CSS
    echo $document->render();
    
  2. Conditional Rule Removal:

    foreach ($document->getAllRuleSets() as $ruleSet) {
        $ruleSet->removeRule('font-'); // Removes all font-related rules
    }
    
  3. Dynamic Value Adjustment:

    foreach ($document->getAllValues() as $value) {
        if ($value instanceof \Sabberworm\CSS\Value\Size && !$value->isRelative()) {
            $value->setSize($value->getSize() * 0.8); // Scale down sizes
        }
    }
    

Integration Tips

  • Laravel Service Provider: Bind the parser as a singleton for reuse:
    $this->app->singleton(Parser::class, function () {
        return new Parser(file_get_contents(storage_path('app/public/css/styles.css')));
    });
    
  • Middleware for CSS Processing: Use middleware to parse and modify CSS before serving:
    public function handle($request, Closure $next) {
        $document = app(Parser::class)->parse();
        // Modify $document here...
        $response = $next($request);
        $response->headers->set('Content-Type', 'text/css');
        return $response->setContent($document->render());
    }
    
  • Blade Directives: Create a custom Blade directive to inline-process CSS:
    Blade::directive('processCss', function ($expression) {
        $css = file_get_contents($expression);
        $document = (new Parser($css))->parse();
        // Modify $document...
        return "<?php echo \$document->render(); ?>";
    });
    
    Usage in Blade:
    <style>{{ @processCss('css/styles.css') }}</style>
    

Gotchas and Tips

Pitfalls

  1. Strict Parsing:

    • Enabling strict parsing (Settings::create()->beStrict()) will throw exceptions on invalid CSS. Useful for debugging but may break in production if CSS is user-generated.
    • Example:
      $parser = new Parser($css, Settings::create()->beStrict());
      $document = $parser->parse(); // Throws on invalid CSS
      
  2. Multibyte Support:

    • Disabling multibyte functions (withMultibyteSupport(false)) speeds up parsing but may fail with non-ASCII characters. Only disable if you control the input CSS.
    • Example:
      $parser = new Parser($css, Settings::create()->withMultibyteSupport(false));
      
  3. Selector Specificity:

    • The Selector class does not compute specificity by default. Use third-party libraries (e.g., league/cssselector) if you need specificity calculations.
  4. Nested At-Rules:

    • Deeply nested at-rules (e.g., @media @media) may not parse as expected. Flatten or simplify nested structures before parsing.

Debugging

  • Inspect the AST: Use var_dump($document) or print_r($document) to debug the parsed structure. The README provides a var_dump example for reference.
  • Line Numbers: All nodes (Rule, Selector, etc.) include lineNumber properties. Useful for error messages:
    foreach ($document->getAllRuleSets() as $ruleSet) {
        foreach ($ruleSet->getRules() as $rule) {
            if ($rule->getLineNumber() > 100) {
                // Log or handle rules from specific lines
            }
        }
    }
    

Extension Points

  1. Custom Value Types: Extend Value or ValueList to handle domain-specific CSS values (e.g., custom units or functions):

    class CustomUnit extends \Sabberworm\CSS\Value\Size {
        public function render() {
            return $this->size . 'custom-unit';
        }
    }
    
  2. Output Format Extensions: Subclass OutputFormat to add custom formatting rules:

    class CustomFormat extends \Sabberworm\CSS\OutputFormat {
        public function renderRule($rule) {
            // Custom logic for rendering rules
            return parent::renderRule($rule);
        }
    }
    
  3. Pre/Post-Processing Hooks: Use Laravel's service container to wrap the parser with custom logic:

    $this->app->resolving(Parser::class, function ($parser, $app) {
        $parser->setCss($app['custom.css.processor']->process($parser->getCss()));
    });
    

Performance Tips

  • Reuse Parser Instances: Parse once and reuse the Document object for multiple modifications:
    $parser = new Parser($css);
    $document = $parser->parse();
    
    // Multiple modifications...
    $document->render(); // Output once
    
  • Avoid getAllValues(): This method traverses the entire AST. Cache results if used repeatedly:
    $values = $document->getAllValues(); // Expensive
    // Store $values for later use
    

Laravel-Specific Quirks

  • File Caching: Cache parsed CSS documents in Laravel's cache:
    $cacheKey = 'css.styles';
    $document = Cache::remember($cacheKey, now()->addHours(1), function () {
        return (new Parser(file_get_contents('styles.css')))->parse();
    });
    
  • Asset Pipeline: Use Laravel Mix to process CSS files with the parser before compilation:
    // mix.js
    const { Parser } = require('sabberworm/php-css-parser');
    mix.process('styles.css', (content) => {
        const parser = new Parser(content);
        const document = parser.parse();
        // Modify document...
        return document.render();
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata