WebpackAssets.php 2.24 KB
<?php

namespace FootyRoom\Support;

use Illuminate\Contracts\Cache\Repository;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Foundation\Application;

class WebpackAssets
{
    /**
     * @var \Illuminate\Contracts\Foundation\Application
     */
    protected $app;

    /**
     * @var \Illuminate\Contracts\Cache\Repository
     */
    protected $cache;

    /**
     * Array of required entries.
     *
     * @var array
     */
    protected $entries;

    public function __construct(Container $container, Repository $cache)
    {
        $this->app = $container->make(Application::class);
        $this->cache = $cache;
        $this->entries = [];
    }

    /**
     * Add specified webpack entry to the list of entries to be loaded.
     */
    public function require(string $entry): void
    {
        $this->entries[] = $entry;
    }

    /**
     * Add specified webpack entry to be the first in list of entries to be loaded.
     */
    public function requireFirst(string $entry): void
    {
        array_unshift($this->entries, $entry);
    }

    /**
     * Returns public paths to all assets (chunks) that belong to required entries.
     */
    public function getAssets(): array
    {
        if ($this->app->environment() === 'development') {
            $ttl = 0.02; // 1 second
        } else {
            $ttl = 1440; // 1 day
        }

        $cacheKey = md5(implode($this->entries));
        
        return $this->cache->remember('webpack-assets-'.$cacheKey, $ttl, function () {
            $assets = [
                'css' => [],
                'js' => [],
            ];

            $manifest = json_decode(file_get_contents($this->app->basePath('webpack-assets.json')));

            foreach ($this->entries as $entry) {
                if (isset($manifest->{$entry}->js)) {
                    $assets['js'] = array_merge($assets['js'], $manifest->{$entry}->js);
                }

                if (isset($manifest->{$entry}->css)) {
                    $assets['css'] = array_merge($assets['css'], $manifest->{$entry}->css);
                }
            }

            $assets['js'] = array_unique($assets['js']);
            $assets['css'] = array_unique($assets['css']);

            return $assets;
        });
    }
}