laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Suggestion #2546

Open aodamuz opened 3 years ago

aodamuz commented 3 years ago

Could anyone add an event in the "compile" method of the \Illuminate\View\Compilers\BladeCompiler class? I have tried to do it but the tests in github/actions fail although in local they do not fail.

The idea is that an event is fired when a view is compiled. Sometimes we need to compress the HTML and in order not to use third party packages I think there should be an event when compiling a view.

Here the implementation:

use Illuminate\View\Events\CompiledView;

/**
 * Compile the view at the given path.
 *
 * @param  string|null  $path
 * @return void
 */
public function compile($path = null)
{
    if ($path) {
        $this->setPath($path);
    }

    if (! is_null($this->cachePath)) {
        $contents = $this->compileString($this->files->get($this->getPath()));

        if (! empty($this->getPath())) {
            $contents = $this->appendFilePath($contents);
        }

        $this->files->put(
            $path = $this->getCompiledPath($this->getPath()), $contents
        );

        event(new CompiledView($path, $contents));
    }
}

The event would look like this:

<?php

namespace Illuminate\View\Events;

class CompiledView
{
    /**
     * Path to the compiled version of a view.
     *
     * @var string
     */
    public $path;

    /**
     * Contents of the compiled view.
     *
     * @var string
     */
    public $contents;

    /**
     * Create a new event instance.
     *
     * @param  string  $path
     * @param  string  $contents
     * @return void
     */
    public function __construct($path, $contents)
    {
        $this->path = $path;
        $this->contents = $contents;
    }
}