function FileExampleSubmitHandlerHelper::handleFileDelete

Submit handler to delete a file.

Parameters

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

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

File

modules/file_example/src/FileExampleSubmitHandlerHelper.php, line 328

Class

FileExampleSubmitHandlerHelper
A submit handler helper class for the file_example module.

Namespace

Drupal\file_example

Code

public function handleFileDelete(array &$form, FormStateInterface $form_state) {
  $form_values = $form_state->getValues();
  $uri = $form_values['fileops_file'];
  // Since we don't know if the file is managed or not, look in the database
  // to see. Normally, code would be working with either managed or unmanaged
  // files, so this is not a typical situation.
  $file_object = $this->fileHelper
    ->getManagedFile($uri);
  // If a managed file, use file_delete().
  if (!empty($file_object)) {
    // While file_delete should return FALSE on failure,
    // it can currently throw an exception on certain cache states.
    try {
      // This no longer returns a result code.  If things go bad,
      // it will throw an exception:
      $file_object->delete();
      $this->messenger
        ->addMessage($this->t('Successfully deleted managed file %uri', [
        '%uri' => $uri,
      ]));
      $this->stateHelper
        ->setDefaultFile($uri);
    } catch (\Exception $e) {
      $this->messenger
        ->addMessage($this->t('Failed deleting managed file %uri. Result was %result', [
        '%uri' => $uri,
        '%result' => print_r($e->getMessage(), TRUE),
      ]), 'error');
    }
  }
  else {
    $result = $this->fileSystem
      ->delete($uri);
    if ($result !== TRUE) {
      $this->messenger
        ->addError($this->t('Failed deleting unmanaged file %uri', [
        '%uri' => $uri,
      ]));
    }
    else {
      $this->messenger
        ->addMessage($this->t('Successfully deleted unmanaged file %uri', [
        '%uri' => $uri,
      ]));
      $this->stateHelper
        ->setDefaultFile($uri);
    }
  }
}