Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Minifier.php
Go to the documentation of this file.
1 <?php
8 
11 
12 class Minifier implements MinifierInterface
13 {
17  protected $filesystem;
18 
24  protected $inlineHtmlTags = [
25  'b',
26  'big',
27  'i',
28  'small',
29  'tt',
30  'abbr',
31  'acronym',
32  'cite',
33  'code',
34  'dfn',
35  'em',
36  'kbd',
37  'strong',
38  'samp',
39  'var',
40  'a',
41  'bdo',
42  'br',
43  'img',
44  'map',
45  'object',
46  'q',
47  'span',
48  'sub',
49  'sup',
50  'button',
51  'input',
52  'label',
53  'select',
54  'textarea',
55  '\?',
56  ];
57 
61  protected $htmlDirectory;
62 
66  protected $readFactory;
67 
72  public function __construct(
74  Filesystem\Directory\ReadFactory $readFactory
75  ) {
76  $this->filesystem = $filesystem;
77  $this->htmlDirectory = $filesystem->getDirectoryWrite(DirectoryList::TMP_MATERIALIZATION_DIR);
78  $this->readFactory = $readFactory;
79  }
80 
87  public function getMinified($file)
88  {
89  $file = $this->htmlDirectory->getDriver()->getRealPathSafety($file);
90  if (!$this->htmlDirectory->isExist($this->getRelativeGeneratedPath($file))) {
91  $this->minify($file);
92  }
93  return $this->getPathToMinified($file);
94  }
95 
102  public function getPathToMinified($file)
103  {
104  return $this->htmlDirectory->getAbsolutePath($this->getRelativeGeneratedPath($file));
105  }
106 
113  public function minify($file)
114  {
115  $dir = dirname($file);
116  $fileName = basename($file);
117  $content = preg_replace(
118  '#(?<!]]>)\s+</#',
119  '</',
120  preg_replace(
121  '#((?:<\?php\s+(?!echo|print|if|elseif|else)[^\?]*)\?>)\s+#',
122  '$1 ',
123  preg_replace(
124  '#(?<!' . implode('|', $this->inlineHtmlTags) . ')> <#',
125  '><',
126  preg_replace(
127  '#(?ix)(?>[^\S ]\s*|\s{2,})(?=(?:(?:[^<]++|<(?!/?(?:textarea|pre|script)\b))*+)'
128  . '(?:<(?>textarea|pre|script)\b|\z))#',
129  ' ',
130  preg_replace(
131  '#(?<!:|\\\\|\'|")//(?!\s*<\!\[)(?!\s*]]>)[^\n\r]*#',
132  '',
133  preg_replace(
134  '#(?<!:|\'|")//[^\n\r]*(\?>)#',
135  ' $1',
136  preg_replace(
137  '#(?<!:)//[^\n\r]*(<\?php)[^\n\r]*(\s\?>)[^\n\r]*#',
138  '',
139  $this->readFactory->create($dir)->readFile($fileName)
140  )
141  )
142  )
143  )
144  )
145  )
146  );
147 
148  if (!$this->htmlDirectory->isExist()) {
149  $this->htmlDirectory->create();
150  }
151  $this->htmlDirectory->writeFile($this->getRelativeGeneratedPath($file), rtrim($content));
152  }
153 
160  private function getRelativeGeneratedPath($sourcePath)
161  {
162  return $this->filesystem->getDirectoryRead(DirectoryList::ROOT)->getRelativePath($sourcePath);
163  }
164 }
$fileName
Definition: translate.phtml:15
__construct(Filesystem $filesystem, Filesystem\Directory\ReadFactory $readFactory)
Definition: Minifier.php:72