You are here

public function ResponsiveFaviconsAdmin::submitForm in Responsive Favicons 8

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides ConfigFormBase::submitForm

File

src/Form/ResponsiveFaviconsAdmin.php, line 139

Class

ResponsiveFaviconsAdmin
Class ResponsiveFaviconsAdmin.

Namespace

Drupal\responsive_favicons\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $config = $this
    ->config('responsive_favicons.settings');

  // We want to save tags as an array.
  $tags = explode(PHP_EOL, $form_state
    ->getValue('tags'));
  $tags = array_map('trim', $tags);
  $tags = array_filter($tags);
  $config
    ->set('tags', $tags);

  // Get the favicons location type.
  $path_type = $form_state
    ->getValue('path_type');
  $config
    ->set('path_type', $path_type);

  // Local path.
  if ($path_type === 'path') {
    $path = rtrim($form_state
      ->getValue('local_path'));
    $config
      ->set('path', $path);
  }

  // Checkbox.
  $config
    ->set('remove_default', $form_state
    ->getValue('remove_default'));

  // If path type is upload handle uploaded zip file.
  if ($path_type === 'upload') {
    $path = rtrim($form_state
      ->getValue('upload_path'));
    $config
      ->set('path', $path);

    // Attempt the upload and extraction of the zip file. This code is largely
    // based on the code in Drupal core.
    //
    // @see UpdateManagerInstall->submitForm().
    $local_cache = NULL;
    if (!empty($_FILES['files']['name']['upload'])) {
      $validators = [
        'file_validate_extensions' => [
          'zip',
        ],
      ];
      if (!($finfo = file_save_upload('upload', $validators, NULL, 0, FileSystemInterface::EXISTS_REPLACE))) {

        // Failed to upload the file. file_save_upload() calls
        // \Drupal\Core\Messenger\MessengerInterface::addError() on failure.
        return;
      }
      $local_cache = $finfo
        ->getFileUri();
    }

    // Only execute the below if a file was uploaded.
    if (isset($local_cache)) {
      $directory = $this
        ->extractDirectory();
      try {
        $archive = $this
          ->archiveExtract($local_cache, $directory);
      } catch (\Exception $e) {
        $this
          ->messenger()
          ->addError($e
          ->getMessage());
        return;
      }
      $files = $archive
        ->listContents();
      if (!$files) {
        $form_state
          ->setError($field, $this
          ->t('Provided archive contains no files.'));
        return;
      }
      $destination = 'public://' . $path;
      $this->fileSystem
        ->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY);

      // Copy the files to the correct location.
      $success_count = 0;
      foreach ($files as $file) {

        // Handle exceptions when copy does not happen correctly.
        try {
          $success = $this->fileSystem
            ->copy($directory . '/' . $file, $destination, FileSystemInterface::EXISTS_REPLACE);
        } catch (FileException $e) {
          $success = FALSE;
        }
        $uri = $destination . '/' . $file;
        if ($success) {
          $success_count++;

          // Handle exceptions when file contents are not saved correctly into
          // destination.
          try {

            // Rewrite the paths of the JSON files.
            if (preg_match('/\\.json$/', $file)) {
              $file_contents = file_get_contents($this->fileSystem
                ->realpath($uri));
              $find = preg_quote('"\\/android-chrome', '/');
              $replace = '"' . str_replace('/', '\\/', _responsive_favicons_normalise_path('/android-chrome'));
              $file_contents = preg_replace('/' . $find . '/', $replace, $file_contents);
              $this->fileSystem
                ->saveData($file_contents, $uri, FileSystemInterface::EXISTS_REPLACE);
            }
            elseif (preg_match('/\\.xml$/', $file)) {
              $file_contents = file_get_contents($this->fileSystem
                ->realpath($uri));
              $find = preg_quote('"/mstile', '/');
              $replace = '"' . _responsive_favicons_normalise_path('/mstile');
              $file_contents = preg_replace('/' . $find . '/', $replace, $file_contents);
              $this->fileSystem
                ->saveData($file_contents, $uri, FileSystemInterface::EXISTS_REPLACE);
            }
            elseif (preg_match('/\\.webmanifest$/', $file)) {
              $file_contents = file_get_contents($this->fileSystem
                ->realpath($uri));
              $find = preg_quote('"/android-chrome', '/');
              $replace = '"' . _responsive_favicons_normalise_path('/android-chrome');
              $file_contents = preg_replace('/' . $find . '/', $replace, $file_contents);
              $this->fileSystem
                ->saveData($file_contents, $uri, FileSystemInterface::EXISTS_REPLACE);
            }
          } catch (FileWriteException $e) {
            $this
              ->messenger()
              ->addError($this
              ->t('The file could not be created.'));
          } catch (FileException $e) {
            $this
              ->messenger()
              ->addError($e
              ->getMessage());
          }
        }
      }
      if ($success_count > 0) {
        $this
          ->messenger()
          ->addStatus($this
          ->formatPlural($success_count, 'Uploaded 1 favicon file successfully.', 'Uploaded @count favicon files successfully.'));
      }
    }
  }

  // Save the settings.
  $config
    ->save();
  parent::submitForm($form, $form_state);
}