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 Min Laravel Package

nitra/php-min

PhpMin is a Composer-ready PHP port of the classic CssMin and JsMinPlus tools. It provides simple minification/formatting utilities for CSS and JavaScript assets, packaged for easy installation and use in PHP projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require nitra/php-min
    

    No additional configuration is required for basic usage.

  2. First Use Case: Minifying a JS File

    use Nitra\PhpMin\Minifier;
    
    $minifier = new Minifier();
    $jsCode = file_get_contents('path/to/your/script.js');
    $minifiedJs = $minifier->minify($jsCode);
    
    file_put_contents('path/to/minified/script.min.js', $minifiedJs);
    
  3. First Use Case: Minifying a CSS File

    $cssCode = file_get_contents('path/to/your/style.css');
    $minifiedCss = $minifier->minify($cssCode, Minifier::TYPE_CSS);
    
    file_put_contents('path/to/minified/style.min.css', $minifiedCss);
    
  4. Where to Look First

    • GitHub README for basic usage examples.
    • src/Minifier.php for core logic and available methods.
    • Test cases in tests/ for edge-case handling.

Implementation Patterns

Workflow: Asset Optimization Pipeline

  1. Laravel Service Provider Integration Bind the minifier to Laravel’s container for reusable access:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Minifier::class, function ($app) {
            return new Minifier();
        });
    }
    

    Now inject Minifier into controllers/services:

    use Nitra\PhpMin\Minifier;
    
    public function __construct(private Minifier $minifier) {}
    
  2. Asset Processing Middleware Create middleware to minify assets on-the-fly (e.g., for dynamic JS/CSS):

    // app/Http/Middleware/MinifyAssets.php
    public function handle($request, Closure $next)
    {
        if ($request->wantsJs()) {
            $content = $next($request)->getContent();
            return response($this->minifier->minify($content, Minifier::TYPE_JS));
        }
        return $next($request);
    }
    
  3. Artisan Command for Batch Minification Automate minification for all assets in a directory:

    // app/Console/Commands/MinifyAssets.php
    public function handle()
    {
        $files = File::allFiles(public_path('assets/js'));
        foreach ($files as $file) {
            $content = File::get($file);
            File::put($file->getPathname(), $this->minifier->minify($content, Minifier::TYPE_JS));
        }
    }
    
  4. Integration with Laravel Mix/Vite Use the minifier as a post-processor in custom webpack plugins or Vite transforms:

    // vite.config.js
    export default {
        transform: {
            load(id) {
                if (id.endsWith('.js')) {
                    return {
                        code: minifyJsCode(id), // Call PHP minifier via Node
                        map: null
                    };
                }
            }
        }
    };
    

Gotchas and Tips

Pitfalls

  1. CSS vs. JS Handling

    • The package defaults to JS minification. Explicitly specify Minifier::TYPE_CSS for CSS to avoid unexpected behavior (e.g., broken selectors or properties).
    • Example:
      $minifier->minify($css, Minifier::TYPE_CSS); // Required!
      
  2. Source Maps

    • The package does not generate source maps by default. If debugging minified assets, use a tool like UglifyJS or Terser alongside this package.
  3. Preserving Comments

    • The minifier strips all comments by default. To retain specific comments (e.g., license headers), pre-process the code or use a wrapper:
      $code = preg_replace('/\/\* License \*\/.*?\*\//s', '$0', $code);
      $minified = $minifier->minify($code);
      
  4. Edge Cases in CSS

    • Media queries or custom properties (e.g., --var: value) may break if not properly escaped. Test with complex CSS.
    • URLs in CSS: Relative paths may fail if the minified file is moved. Use absolute paths or post-process URLs.
  5. Performance Overhead

    • Minifying large files (e.g., 1MB+) in PHP may cause memory issues. For bulk operations, consider:
      • Queueing jobs (php artisan queue:work).
      • Offloading to a CLI script.

Debugging Tips

  1. Verify Input/Output Compare original vs. minified output to spot issues:

    echo "Original size: " . strlen($original) . "\n";
    echo "Minified size: " . strlen($minified) . "\n";
    
  2. Check for Syntax Errors Minified JS/CSS may fail silently. Validate with:

  3. Log Errors Wrap minification in a try-catch to log failures:

    try {
        $minified = $minifier->minify($code);
    } catch (\Exception $e) {
        Log::error("Minification failed: " . $e->getMessage());
        return $original; // Fallback
    }
    

Extension Points

  1. Custom Minification Rules Extend the minifier by subclassing Minifier and overriding methods like minifyJs() or minifyCss():

    class CustomMinifier extends Minifier {
        protected function minifyJs($code) {
            $code = parent::minifyJs($code);
            // Add custom logic (e.g., replace specific strings)
            return str_replace('console.log', '', $code);
        }
    }
    
  2. Pre/Post-Processing Chain minification with other transformations:

    $processed = $this->minifier->minify($code, Minifier::TYPE_JS);
    $processed = $this->addHashToUrls($processed); // Custom method
    
  3. Configuration While the package lacks a config file, you can inject settings via constructor:

    $minifier = new Minifier(['preserve_whitespace' => false]);
    
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
croct/coding-standard
croct/plug-php
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields