forked from ceesvanegmond/minify
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathBaseProvider.php
executable file
·317 lines (260 loc) · 8.25 KB
/
BaseProvider.php
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<?php namespace Devfactory\Minify\Providers;
use Devfactory\Minify\Exceptions\CannotRemoveFileException;
use Devfactory\Minify\Exceptions\CannotSaveFileException;
use Devfactory\Minify\Exceptions\DirNotExistException;
use Devfactory\Minify\Exceptions\DirNotWritableException;
use Devfactory\Minify\Exceptions\FileNotExistException;
use Illuminate\Filesystem\Filesystem;
use Countable;
abstract class BaseProvider implements Countable
{
protected string $outputDir;
protected string $appended = '';
protected string $filename = '';
protected array $files = [];
protected array $headers = [];
private string $publicPath;
protected Filesystem $file;
private bool $disable_mtime;
private string $hash_salt;
public function __construct(?string $publicPath = null, ?array $config = null, ?Filesystem $file = null)
{
$this->file = $file ?: new Filesystem;
$this->publicPath = $publicPath ?: $_SERVER['DOCUMENT_ROOT'];
if (!is_array($config))
{
$this->disable_mtime = false;
$this->hash_salt = '';
}
else
{
$this->disable_mtime = $config['disable_mtime'] ?: false;
$this->hash_salt = $config['hash_salt'] ?: '';
}
$value = function($key)
{
return $_SERVER[$key] ?? '';
};
$this->headers = [
'User-Agent' => $value('HTTP_USER_AGENT'),
'Accept' => $value('HTTP_ACCEPT'),
'Accept-Language' => $value('HTTP_ACCEPT_LANGUAGE'),
'Accept-Encoding' => 'identity',
'Connection' => 'close',
];
}
/**
* @throws DirNotWritableException
* @throws DirNotExistException
* @throws CannotRemoveFileException
* @throws FileNotExistException
*/
public function make(string $outputDir): bool
{
$this->outputDir = $this->publicPath . $outputDir;
$this->checkDirectory();
if ($this->checkExistingFiles())
{
return false;
}
$this->removeOldFiles();
$this->appendFiles();
return true;
}
/**
* @throws FileNotExistException
*/
public function add(array|string $file): void
{
if (is_array($file))
{
foreach ($file as $value) $this->add($value);
}
else if ($this->checkExternalFile($file))
{
$this->files[] = $file;
}
else {
$file = $this->publicPath . $file;
if (!file_exists($file))
{
throw new FileNotExistException("File '{$file}' does not exist");
}
$this->files[] = $file;
}
}
public function tags(string $baseUrl, array $attributes): string
{
$html = '';
foreach($this->files as $file)
{
$file = $baseUrl . str_replace($this->publicPath, '', $file);
$html .= $this->tag($file, $attributes);
}
return $html;
}
public function count(): int
{
return count($this->files);
}
/**
* @throws FileNotExistException
*/
protected function appendFiles(): void
{
foreach ($this->files as $file) {
$contents = $this->getFileContents($file);
$this->appended .= $contents . "\n";
}
}
/**
* @throws FileNotExistException
*/
protected function getFileContents(string $file): string
{
if ($this->checkExternalFile($file))
{
if (str_starts_with($file, '//')) $file = 'http:' . $file;
$headers = $this->headers;
foreach ($headers as $key => $value)
{
$headers[$key] = $key . ': ' . $value;
}
$context = stream_context_create(['http' => [
'ignore_errors' => true,
'header' => implode("\r\n", $headers),
]]);
$http_response_header = [''];
$contents = file_get_contents($file, false, $context);
if (!str_contains($http_response_header[0], '200'))
{
throw new FileNotExistException("File '{$file}' does not exist");
}
}
else
{
$contents = file_get_contents($file);
}
return $contents;
}
protected function getPublicFileDirectory(string $file): string
{
$publicPath = function_exists('public_path') ? public_path() : '';
$fileWithoutPublicPath = str_replace($publicPath, '', $file);
return str_replace(basename($fileWithoutPublicPath), '', $fileWithoutPublicPath);
}
protected function checkExistingFiles(): bool
{
$this->buildMinifiedFilename();
return file_exists($this->outputDir . $this->filename);
}
/**
* @throws DirNotWritableException
* @throws DirNotExistException
*/
protected function checkDirectory(): void
{
if (!file_exists($this->outputDir))
{
// Try to create the directory
if (!$this->file->makeDirectory($this->outputDir, 0775, true)) {
throw new DirNotExistException("Buildpath '{$this->outputDir}' does not exist");
}
}
if (!is_writable($this->outputDir))
{
throw new DirNotWritableException("Buildpath '{$this->outputDir}' is not writable");
}
}
protected function checkExternalFile(string $file): bool
{
return preg_match('/^(https?:)?\/\//', $file);
}
protected function buildMinifiedFilename(): void
{
$this->filename = $this->getHashedFilename() . (($this->disable_mtime) ? '' : $this->countModificationTime()) . static::EXTENSION;
}
/**
* Build an HTML attribute string from an array.
*/
protected function attributes(array $attributes): string
{
$html = [];
foreach ($attributes as $key => $value)
{
$element = $this->attributeElement($key, $value);
if ( ! is_null($element)) $html[] = $element;
}
$output = count($html) > 0 ? ' '.implode(' ', $html) : '';
return trim($output);
}
/**
* Build a single attribute element.
*/
protected function attributeElement(mixed $key, mixed $value): mixed
{
if (is_numeric($key)) $key = $value;
if(is_bool($value))
return $key;
if ( ! is_null($value))
return $key.'="'.htmlentities($value, ENT_QUOTES, 'UTF-8', false).'"';
return null;
}
protected function getHashedFilename(): string
{
$publicPath = $this->publicPath;
return md5(implode('-', array_map(function($file) use ($publicPath) { return str_replace($publicPath, '', $file); }, $this->files)) . $this->hash_salt);
}
protected function countModificationTime(): int
{
$time = 0;
foreach ($this->files as $file)
{
if ($this->checkExternalFile($file))
{
$userAgent = $this->headers['User-Agent'] ?? '';
$time += hexdec(substr(md5($file . $userAgent), 0, 8));
}
else {
$time += filemtime($file);
}
}
return $time;
}
/**
* @throws CannotRemoveFileException
*/
protected function removeOldFiles(): void
{
$pattern = $this->outputDir . $this->getHashedFilename() . '*';
$find = glob($pattern);
if( is_array($find) && count($find) )
{
foreach ($find as $file)
{
if ( ! unlink($file) ) {
throw new CannotRemoveFileException("File '{$file}' cannot be removed");
}
}
}
}
/**
* @throws CannotSaveFileException
*/
protected function put(mixed $minified): string
{
if(file_put_contents($this->outputDir . $this->filename, $minified) === false)
{
throw new CannotSaveFileException("File '{$this->outputDir}{$this->filename}' cannot be saved");
}
return $this->filename;
}
public function getAppended(): string
{
return $this->appended;
}
public function getFilename(): string
{
return $this->filename;
}
}