You are here

public function FileSystem::delete in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::delete()

Deletes a file without database changes or hook invocations.

This function should be used when the file to be deleted does not have an entry recorded in the files table.

Parameters

string $path: A string containing a file path or (streamwrapper) URI.

Throws

\Drupal\Core\File\Exception\FileException Implementation may throw FileException or its subtype on failure.

Overrides FileSystemInterface::delete

1 call to FileSystem::delete()
FileSystem::deleteRecursive in core/lib/Drupal/Core/File/FileSystem.php
Deletes all files and directories in the specified filepath recursively.

File

core/lib/Drupal/Core/File/FileSystem.php, line 323

Class

FileSystem
Provides helpers to operate on files and stream wrappers.

Namespace

Drupal\Core\File

Code

public function delete($path) {
  if (is_file($path)) {
    if (!$this
      ->unlink($path)) {
      $this->logger
        ->error("Failed to unlink file '%path'.", [
        '%path' => $path,
      ]);
      throw new FileException("Failed to unlink file '{$path}'.");
    }
    return TRUE;
  }
  if (is_dir($path)) {
    $this->logger
      ->error("Cannot delete '%path' because it is a directory. Use deleteRecursive() instead.", [
      '%path' => $path,
    ]);
    throw new NotRegularFileException("Cannot delete '{$path}' because it is a directory. Use deleteRecursive() instead.");
  }

  // Return TRUE for non-existent file, but log that nothing was actually
  // deleted, as the current state is the intended result.
  if (!file_exists($path)) {
    $this->logger
      ->notice('The file %path was not deleted because it does not exist.', [
      '%path' => $path,
    ]);
    return TRUE;
  }

  // We cannot handle anything other than files and directories.
  // Throw an exception for everything else (sockets, symbolic links, etc).
  $this->logger
    ->error("The file '%path' is not of a recognized type so it was not deleted.", [
    '%path' => $path,
  ]);
  throw new NotRegularFileException("The file '{$path}' is not of a recognized type so it was not deleted.");
}