public function MinifyJs::minifyFile in Minify JS 8.2
Minify File.
Helper function that sends the JS off to be minified, handles the response, stores the file in the filesystem and stores the file info in the managed file tables.
Parameters
int $fid: The file ID of the file to minify.
bool $reset: Reset the cache or not.
Return value
mixed Success of a translated string.
1 call to MinifyJs::minifyFile()
- MinifyJs::minify in src/
MinifyJs.php - Minify a single file.
File
- src/
MinifyJs.php, line 243
Class
- MinifyJs
- Minify JS Service.
Namespace
Drupal\minifyjsCode
public function minifyFile($fid, $reset = FALSE) {
// Load the file by fid.
$files = $this
->loadAllFiles();
$file = $files[$fid];
$js = file_get_contents(DRUPAL_ROOT . DIRECTORY_SEPARATOR . $file->uri);
// Minify the JS, if it has a length. 0 byte files should pass by the
// minification process.
$minified = $js;
if (strlen($js)) {
$minifier = new JSqueeze();
$minified = $minifier
->squeeze($js, TRUE, FALSE);
}
// Create the directory tree if it doesn't exist.
$minifyjs_folder = 'public://minifyjs/' . dirname($file->uri);
$result = $this->fileSystem
->prepareDirectory($minifyjs_folder, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
// Save the file first to the temp folder and then copy to the
// public filesystem.
$file_name = str_replace('.js', '.min.js', basename($file->uri));
$tmp_file = $this->fileSystem
->getTempDirectory() . DIRECTORY_SEPARATOR . $file_name;
$file_uri = $minifyjs_folder . DIRECTORY_SEPARATOR . $file_name;
if (file_put_contents($tmp_file, $minified) !== FALSE) {
if (copy($tmp_file, $file_uri)) {
// Save the file in the managed file table.
if (empty($file->minified_uri)) {
$file = File::create([
'uid' => \Drupal::currentUser()
->id(),
'uri' => $file_uri,
'filename' => $file_name,
'filemime' => $this->mimeTypeGuesser
->guess($file->uri),
'status' => FILE_STATUS_PERMANENT,
]);
$file
->save();
$this->fileUsage
->add($file, 'minifyjs', 'node', 1);
}
$filesize = filesize($file_uri);
// Update the minifyjs table.
\Drupal::database()
->update('minifyjs_file')
->fields([
'minified_uri' => $file_uri,
'minified_size' => $filesize ? $filesize : 0,
'minified_modified' => \Drupal::time()
->getRequestTime(),
])
->condition('fid', $fid)
->execute();
// Clean up temp folder.
unlink($tmp_file);
// Clear the cache so this change will be reflected in
// loadAllFiles().
if ($reset) {
\Drupal::cache()
->delete(MINIFYJS_CACHE_CID);
}
return TRUE;
}
else {
return t('Could not copy the file from the %tmp folder.', [
'%tmp' => $this->fileSystem
->getTempDirectory(),
]);
}
}
else {
return t('Could not save the file - %file', [
'%file' => $this->fileSystem
->getTempDirectory() . DIRECTORY_SEPARATOR . $file_name,
]);
}
}