View source
<?php
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Site\Settings;
use Drupal\file\Entity\File;
use Patchwork\JSqueeze;
use Symfony\Component\HttpFoundation;
define('MINIFYJS_CACHE_CID', 'minifyjs:all_files');
function minifyjs_form_system_performance_settings_alter(&$form, $form_state, $form_id) {
if (\Drupal::currentUser()
->hasPermission('administer minifyjs')) {
$files = minifyjs_load_all_files();
$files_minified = 0;
foreach ($files as $file) {
if (!empty($file->minified_uri)) {
$files_minified++;
}
}
$form['bandwidth_optimization']['use_minified_javascript'] = [
'#type' => 'checkbox',
'#title' => t('Use Minified JavaScript files.'),
'#disabled' => $files_minified ? FALSE : TRUE,
'#description' => t('Toggle minified javascript files on or off. There are @minified minified files out of @total total files available. <a href=":href">Click here to manage your javascript files</a>.', [
'@minified' => $files_minified,
'@total' => count($files),
':href' => Url::fromUri('base:/admin/config/development/performance/js')
->toString(),
]),
'#default_value' => \Drupal::config('minifyjs.config')
->get('use_minified'),
];
$form['#submit'][] = 'minifyjs_system_performance_settings_submit';
}
}
function minifyjs_system_performance_settings_submit(&$form, $form_state) {
\Drupal::service('config.factory')
->getEditable('minifyjs.config')
->set('use_minified', $form_state
->getValue('use_minified_javascript'))
->save();
}
function minifyjs_js_alter(&$scripts, $assets) {
$do_replace = FALSE;
if (\Drupal::config('minifyjs.config')
->get('use_minified')) {
if (\Drupal::config('minifyjs.config')
->get('disable_admin')) {
if (!\Drupal::service('router.admin_context')
->isAdminRoute()) {
$do_replace = TRUE;
}
}
else {
$do_replace = TRUE;
}
}
if ($do_replace) {
$files = minifyjs_load_all_files();
$minified_files = [];
foreach ($files as $file) {
if (!empty($file->minified_uri)) {
$minified_files[$file->uri] = $file;
}
}
foreach ($scripts as $path => $file) {
if (isset($minified_files[$path])) {
$scripts[$path]['data'] = $minified_files[$path]->minified_uri;
minifyjs_update_scripts($scripts, $path, $minified_files[$path]->minified_uri);
}
}
}
}
function minifyjs_update_scripts(&$scripts, $existing, $new) {
$keys = array_keys($scripts);
$index = array_search($existing, $keys, TRUE);
if ($index !== FALSE) {
$keys[$index] = $new;
$scripts = array_combine($keys, $scripts);
}
}
function minifyjs_load_all_files() {
if ($cache = \Drupal::cache()
->get(MINIFYJS_CACHE_CID)) {
return $cache->data;
}
$result = \Drupal::database()
->select('minifyjs_file', 'f')
->fields('f')
->orderBy('uri')
->execute();
$exclusions = \Drupal::config('minifyjs.config')
->get('exclusion_list');
$files = [];
while ($file = $result
->fetchObject()) {
if (!\Drupal::service('path.matcher')
->matchPath($file->uri, $exclusions)) {
$files[$file->fid] = $file;
}
}
\Drupal::cache()
->set(MINIFYJS_CACHE_CID, $files, strtotime('+1 day', \Drupal::time()
->getRequestTime()));
return $files;
}
function minifyjs_minify_file($fid, $reset = FALSE) {
$files = minifyjs_load_all_files();
$file = $files[$fid];
$js = file_get_contents(DRUPAL_ROOT . '/' . $file->uri);
$minified = $js;
if (strlen($js)) {
$minifier = new JSqueeze();
$minified = $minifier
->squeeze($js, TRUE, FALSE);
}
$minifyjs_folder = 'public://minifyjs/' . dirname($file->uri);
if (!is_dir($minifyjs_folder)) {
mkdir($minifyjs_folder, Settings::get('file_chmod_directory', 0775), TRUE);
}
$file_name = str_replace('.js', '.min.js', basename($file->uri));
$tmp_file = file_directory_temp() . '/' . $file_name;
$file_uri = 'public://minifyjs/' . dirname($file->uri) . '/' . $file_name;
if (file_put_contents($tmp_file, $minified) !== FALSE) {
if (copy($tmp_file, $file_uri)) {
if (empty($file->minified_uri)) {
$file = File::create([
'uid' => \Drupal::currentUser()
->id(),
'uri' => $file_uri,
'filename' => $file_name,
'filemime' => \Drupal::service('file.mime_type.guesser')
->guess($file->uri),
'status' => FILE_STATUS_PERMANENT,
]);
$file
->save();
\Drupal::service('file.usage')
->add($file, 'minifyjs', 'node', 1);
}
$filesize = filesize($file_uri);
\Drupal::database()
->update('minifyjs_file')
->fields([
'minified_uri' => $file_uri,
'minified_size' => $filesize ? $filesize : 0,
'minified_modified' => REQUEST_TIME,
])
->condition('fid', $fid)
->execute();
unlink($tmp_file);
if ($reset) {
\Drupal::cache()
->delete(MINIFYJS_CACHE_CID);
}
return TRUE;
}
else {
return t('Could not copy the file from the %tmp folder.', [
'%tmp' => file_directory_temp(),
]);
}
}
else {
return t('Could not save the file - %file', [
'%file' => file_directory_temp() . '/' . $file_name,
]);
}
}
function minifyjs_remove_minified_file($fid, $reset = FALSE) {
$query = \Drupal::database()
->select('minifyjs_file', 'm')
->fields('m', array(
'minified_uri',
))
->condition('m.fid', $fid);
if ($query
->countQuery()
->execute()
->fetchField() > 0) {
$file = $query
->execute()
->fetchObject();
$query = db_select('file_managed', 'f')
->fields('f', array(
'fid',
))
->condition('f.uri', $file->minified_uri);
if ($query
->countQuery()
->execute()
->fetchField() > 0) {
$file = $query
->execute()
->fetchObject();
$file = File::load($file->fid);
$file
->delete();
\Drupal::database()
->update('minifyjs_file')
->fields([
'minified_uri' => '',
'minified_size' => 0,
'minified_modified' => 0,
])
->condition('fid', $fid)
->execute();
if ($reset) {
\Drupal::cache()
->delete(MINIFYJS_CACHE_CID);
}
return TRUE;
}
}
return t('File not found. Check that the file ID is correct.');
}
function minifyjs_batch_minify_file_operation($fid, &$context) {
$files = minifyjs_load_all_files();
$file = $files[$fid];
$context['message'] = t('Minifying file - %file', [
'%file' => $file->uri,
]);
$result = minifyjs_minify_file($fid);
if ($result === TRUE) {
$context['results']['success'][] = t('File %file was minified successfully.', [
'%file' => $file->uri,
]);
}
else {
$context['results']['errors'][] = $result;
}
}
function minifyjs_batch_remove_minified_file_operation($fid, &$context) {
$files = minifyjs_load_all_files();
$file = $files[$fid];
$context['message'] = t('Restoring un-minified file - %file', [
'%file' => $file->uri,
]);
$result = minifyjs_remove_minified_file($fid);
if ($result === TRUE) {
$context['results']['success'][] = t('File %file was restored successfully.', [
'%file' => $file->uri,
]);
}
else {
$context['results']['errors'][] = $result;
}
}
function minifyjs_batch_finished($success, $results, $operations) {
if (isset($results['success'])) {
if (count($results['success'])) {
foreach ($results['success'] as $success) {
drupal_set_message($success);
}
}
}
if (isset($results['errors'])) {
if (count($results['errors'])) {
foreach ($results['errors'] as $error) {
drupal_set_message($error, 'error');
}
}
}
\Drupal::cache()
->delete(MINIFYJS_CACHE_CID);
}