1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JK\Sam\Filter\Merge; |
4
|
|
|
|
5
|
|
|
use JK\Sam\Filter\Filter; |
6
|
|
|
use SplFileInfo; |
7
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Merge different source files into one. |
11
|
|
|
*/ |
12
|
|
|
class MergeFilter extends Filter |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @param SplFileInfo[] $sources |
16
|
|
|
* @param SplFileInfo[] $destinations |
17
|
|
|
* @return array|SplFileInfo[] |
18
|
|
|
*/ |
19
|
|
|
public function run(array $sources, array $destinations) |
20
|
|
|
{ |
21
|
|
|
$fileSystem = new Filesystem(); |
22
|
|
|
$mergedFiles = []; |
23
|
|
|
|
24
|
|
|
foreach ($this->getSupportedExtensions() as $extension) { |
25
|
|
|
$shouldAddMergeFile = false; |
26
|
|
|
$mergedFile = $this->getCacheDir().'merged.'.$extension; |
27
|
|
|
|
28
|
|
|
// creating the merge file if not exists |
29
|
|
|
if (!$fileSystem->exists($mergedFile)) { |
30
|
|
|
$this->addNotification('creating '.$mergedFile.' merged file'); |
31
|
|
|
$fileSystem->touch($mergedFile); |
32
|
|
|
} |
33
|
|
|
// reset the merge file |
34
|
|
|
$fileSystem->dumpFile($mergedFile, ''); |
35
|
|
|
|
36
|
|
|
foreach ($sources as $source) { |
37
|
|
|
|
38
|
|
|
if ($source->getExtension() !== $extension) { |
39
|
|
|
continue; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$this->addNotification('merging file '.$source); |
43
|
|
|
|
44
|
|
|
// append the current content to the merge file |
45
|
|
|
$content = file_get_contents($source); |
46
|
|
|
$mergedContent = file_get_contents($mergedFile); |
47
|
|
|
$fileSystem->dumpFile($mergedFile, $mergedContent.$content); |
48
|
|
|
|
49
|
|
|
$shouldAddMergeFile = true; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if ($shouldAddMergeFile) { |
53
|
|
|
$mergedFiles[] = $mergedFile; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return $mergedFiles; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Return the file extensions supported by this filter |
62
|
|
|
* |
63
|
|
|
* @return string[] |
64
|
|
|
*/ |
65
|
|
|
public function getSupportedExtensions() |
66
|
|
|
{ |
67
|
|
|
return [ |
68
|
|
|
'css', |
69
|
|
|
'js', |
70
|
|
|
]; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|