You are here

class ManageFilesForm in Minify JS 8

Same name and namespace in other branches
  1. 8.2 src/Form/ManageFilesForm.php \Drupal\minifyjs\Form\ManageFilesForm

Displays a list of detected javascript files and allows actions to be performed on them

Hierarchy

Expanded class hierarchy of ManageFilesForm

1 string reference to 'ManageFilesForm'
minifyjs.routing.yml in ./minifyjs.routing.yml
minifyjs.routing.yml

File

src/Form/ManageFilesForm.php, line 15

Namespace

Drupal\minifyjs\Form
View source
class ManageFilesForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $files = minifyjs_load_all_files();
    $form = [];

    // Statistics
    $number_of_files = 0;
    $minified_files = 0;
    $unminified_size = 0;
    $minified_size = 0;
    $saved_size = 0;

    // Get search query.
    $session = \Drupal::service('user.private_tempstore')
      ->get('minifyjs');
    $query = $session
      ->get('query');

    // Filter the files based on query.
    if ($query) {
      $new_files = [];
      foreach ($files as $fid => $file) {
        if (stripos($file->uri, $query) !== FALSE) {
          $new_files[$fid] = $file;
        }
      }
      $files = $new_files;
    }

    // pager init
    $limit = 100;
    $start = 0;
    if (isset($_REQUEST['page'])) {
      $start = $_REQUEST['page'] * $limit;
    }
    $total = count($files);
    pager_default_initialize($total, $limit);

    // Build the rows of the table.
    $rows = [];
    if ($total) {

      // statistics for all files
      foreach ($files as $fid => $file) {
        $number_of_files++;
        $unminified_size += $file->size;
        $minified_size += $file->minified_size;
        if ($file->minified_uri) {
          $saved_size += $file->size - $file->minified_size;
          $minified_files++;
        }
      }

      // build table rows
      $files_subset = array_slice($files, $start, $limit, TRUE);
      foreach ($files_subset as $fid => $file) {
        $operations = [
          '#type' => 'operations',
          '#links' => $this
            ->operations($file),
        ];
        $rows[$fid] = [
          Link::fromTextAndUrl($file->uri, Url::fromUri('base:' . $file->uri, [
            'attributes' => [
              'target' => '_blank',
            ],
          ])),
          date('Y-m-d', $file->modified),
          $this
            ->format_filesize($file->size),
          $this
            ->minified_filesize($file),
          $this
            ->precentage($file),
          $this
            ->minified_date($file),
          $this
            ->minified_file($file),
          \Drupal::service('renderer')
            ->render($operations),
        ];
      }
    }

    // report on statistics
    drupal_set_message(t('@files javascript files (@min_files minified). The size of all original files is @size and the size of all of the minified files is @minified for a savings of @diff (@percent% smaller overall)', [
      '@files' => $number_of_files,
      '@min_files' => $minified_files,
      '@size' => $this
        ->format_filesize($unminified_size),
      '@minified' => $minified_size ? $this
        ->format_filesize($minified_size) : 0,
      '@diff' => $minified_size ? $this
        ->format_filesize($saved_size) : 0,
      '@percent' => $minified_size ? round($saved_size / $unminified_size * 100, 2) : 0,
    ]), 'status');
    $form['search'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => 'container-inline',
      ],
    ];
    $form['search']['query'] = [
      '#type' => 'textfield',
      '#title' => t('Search'),
      '#title_display' => 'hidden',
      '#default_value' => $query,
    ];
    $form['search']['submit'] = [
      '#type' => 'submit',
      '#value' => t('Search'),
      '#submit' => [
        [
          $this,
          'filterList',
        ],
      ],
    ];
    if ($query) {
      $form['search']['reset'] = [
        '#type' => 'submit',
        '#value' => t('Reset'),
        '#submit' => [
          [
            $this,
            'filterListReset',
          ],
        ],
      ];
    }

    // The table.
    $form['files'] = [
      '#type' => 'tableselect',
      '#header' => [
        t('Original File'),
        t('Last Modified'),
        t('Original Size'),
        t('Minified Size'),
        t('Savings'),
        t('Last Minified'),
        t('Minified File'),
        t('Operations'),
      ],
      '#options' => $rows,
      '#empty' => t('No files have been found. Please scan using the action link above.'),
    ];
    $form['pager'] = [
      '#type' => 'pager',
    ];

    // Bulk minify button.
    if ($total) {
      $form['actions'] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'container-inline',
          ],
        ],
      ];
      $form['actions']['action'] = [
        '#type' => 'select',
        '#options' => [
          'minify' => t('Minify (and re-minify)'),
          'minify_skip' => t('Minify (and skip minified)'),
          'restore' => t('Restore'),
        ],
      ];
      $form['actions']['scope'] = [
        '#type' => 'select',
        '#options' => [
          'selected' => t('Selected files'),
          'all' => t('All files'),
        ],
      ];
      $form['actions']['go'] = [
        '#type' => 'submit',
        '#value' => t('Perform action'),
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'minifyjs_manage_files';
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if (count($form_state
      ->getValue('files'))) {
      $files = minifyjs_load_all_files();

      // get the files to process
      $selected_files = [];
      if ($form_state
        ->getValue('scope') == 'selected') {
        foreach ($form_state
          ->getValue('files') as $fid => $selected) {
          if ($selected) {
            $selected_files[] = $fid;
          }
        }
      }
      else {
        $selected_files = array_keys($files);
      }

      // Build operations
      $operations = array();
      foreach ($selected_files as $fid) {
        switch ($form_state
          ->getValue('action')) {

          // minify all files.
          case 'minify':
            $operations[] = array(
              'minifyjs_batch_minify_file_operation',
              array(
                $fid,
              ),
            );
            break;

          // minify files that have not yet been minified.
          case 'minify_skip':
            $file = $files[$fid];
            if (!$file->minified_uri) {
              $operations[] = array(
                'minifyjs_batch_minify_file_operation',
                array(
                  $fid,
                ),
              );
            }
            break;

          // restore un-minified version of a file.
          case 'restore':
            $operations[] = array(
              'minifyjs_batch_remove_minified_file_operation',
              array(
                $fid,
              ),
            );
            break;
        }
      }

      // Build the batch.
      $batch = array(
        'operations' => $operations,
        'file' => drupal_get_path('module', 'minifyjs') . '/minifyjs.module',
        'error_message' => t('There was an unexpected error while processing the batch.'),
        'finished' => 'minifyjs_batch_finished',
      );
      switch ($form_state
        ->getValue('action')) {
        case 'minify':
          $batch['title'] = t('Minifying Javascript Files.');
          $batch['init_message'] = t('Initializing minify javascript files batch.');
          break;
        case 'restore':
          $batch['title'] = t('Restoring Un-Minified Javascript Files.');
          $batch['init_message'] = t('Initializing restore un-minified javascript files batch.');
          break;
      }

      // Start the batch.
      batch_set($batch);
    }
  }

  /**
   * Filter list submit callback.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function filterList(array &$form, FormStateInterface $form_state) {
    $session = \Drupal::service('user.private_tempstore')
      ->get('minifyjs');
    $session
      ->set('query', $form_state
      ->getValue('query'));
  }

  /**
   * Filter list reset submit callback.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function filterListReset(array &$form, FormStateInterface $form_state) {
    $session = \Drupal::service('user.private_tempstore')
      ->get('minifyjs');
    $session
      ->set('query', NULL);
  }

  /**
   * Helper function to format the filesize.
   *
   * @param int $size
   */
  private function format_filesize($size) {
    if ($size) {
      $suffixes = array(
        '',
        'k',
        'M',
        'G',
        'T',
      );
      $base = log($size) / log(1024);
      $base_floor = floor($base);
      return round(pow(1024, $base - $base_floor), 2) . $suffixes[$base_floor];
    }
    return 0;
  }

  /**
   * Helper function to format date.
   *
   * @param stdClass $file
   */
  private function minified_date($file) {
    if ($file->minified_modified > 0) {
      return date('Y-m-d', $file->minified_modified);
    }
    return '-';
  }

  /**
   * Helper function to format the minified filesize.
   *
   * @param stdClass $file
   */
  private function minified_filesize($file) {
    if ($file->minified_uri) {
      if ($file->minified_size > 0) {
        return $this
          ->format_filesize($file->minified_size);
      }
      return 0;
    }
    return '-';
  }

  /**
   * Helper function to format the file url.
   *
   * @param stdClass $file
   */
  private function minified_file($file) {
    if (!empty($file->minified_uri)) {
      return Link::fromTextAndUrl(basename($file->minified_uri), Url::fromUri(file_create_url($file->minified_uri), [
        'attributes' => [
          'target' => '_blank',
        ],
      ]));
    }
    return '-';
  }

  /**
   * Helper function to format the savings percentage.
   *
   * @param stdClass $file
   */
  private function precentage($file) {
    if ($file->minified_uri) {
      if ($file->minified_size > 0) {
        return round(($file->size - $file->minified_size) / $file->size * 100, 2) . '%';
      }
      return 0 . '%';
    }
    return '-';
  }

  /**
   * Helper function to return the operations available for the file.
   *
   * @param stdClass $file
   */
  private function operations($file) {
    $operations = [];
    if (empty($file->minified_uri)) {
      $operations['minify'] = [
        'title' => t('Minify'),
        'url' => Url::fromUri('base:/admin/config/development/performance/js/' . $file->fid . '/minify'),
      ];
    }
    else {
      $operations['reminify'] = [
        'title' => t('Re-Minify'),
        'url' => Url::fromUri('base:/admin/config/development/performance/js/' . $file->fid . '/minify'),
      ];
      $operations['restore'] = [
        'title' => t('Restore'),
        'url' => Url::fromUri('base:/admin/config/development/performance/js/' . $file->fid . '/restore'),
      ];
    }
    return $operations;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
ManageFilesForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ManageFilesForm::filterList public function Filter list submit callback.
ManageFilesForm::filterListReset public function Filter list reset submit callback.
ManageFilesForm::format_filesize private function Helper function to format the filesize.
ManageFilesForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ManageFilesForm::minified_date private function Helper function to format date.
ManageFilesForm::minified_file private function Helper function to format the file url.
ManageFilesForm::minified_filesize private function Helper function to format the minified filesize.
ManageFilesForm::operations private function Helper function to return the operations available for the file.
ManageFilesForm::precentage private function Helper function to format the savings percentage.
ManageFilesForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.