This tutorial code shares how to share a file entity programmatically in Drupal. You should work with the Object-oriented way like this (use the following methods in your class):

use Drupal\Core\File\FileSystemInterface; // on top

Class ....

  /**
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The file system manager.
   */
  public function __construct(FileSystemInterface $file_system) {
    $this->fileSystem = $file_system;
  }

  public function HowToSaveAFile($data, $destination) {
    if (!$this->fileSystem->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
      return FALSE;
    }

    $this->fileSystem->saveData($data, $destination, FileSystemInterface::EXISTS_REPLACE);
    $new_file = File::create(['uri' => $file->uri]);
    $new_file->setOwnerId(1);
    $new_file->setPermanent();
    $new_file->save();

    return $new_file;
  }

 

 

Saved you some valuable time?

Buy me a drink 🍺