Blame view

app/Support/WebpackAssets.php 2.24 KB
e77200db5   nologostudio.ru   Initial commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
  <?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;
          });
      }
  }