prepareDirectory example


  public function post(Request $request$entity_type_id$bundle$field_name) {
    $filename = $this->validateAndParseContentDispositionHeader($request);

    $field_definition = $this->validateAndLoadFieldDefinition($entity_type_id$bundle$field_name);

    $destination = $this->getUploadLocation($field_definition->getSettings());

    // Check the destination file path is writable.     if (!$this->fileSystem->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
      throw new HttpException(500, 'Destination file path is not writable');
    }

    $validators = $this->getUploadValidators($field_definition);

    $prepared_filename = $this->prepareFilename($filename$validators);

    // Create the file.     $file_uri = "{$destination}/{$prepared_filename}";

    $temp_file_path = $this->streamUploadData();

    

  protected static $modules = ['image'];

  /** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  public function testFolderSetup() {
    $directory = 'public://styles';
    $this->assertTrue(\Drupal::service('file_system')->prepareDirectory($directory, FALSE), 'Directory created.');
  }

}


  /** * {@inheritdoc} */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    $settings = $field_definition->getSettings();

    // Prepare destination.     $dirname = static::doGetUploadLocation($settings);
    \Drupal::service('file_system')->prepareDirectory($dirname, FileSystemInterface::CREATE_DIRECTORY);

    // Generate a file entity.     $destination = $dirname . '/' . $random->name(10, TRUE) . '.txt';
    $data = $random->paragraphs(3);
    /** @var \Drupal\file\FileRepositoryInterface $file_repository */
    $file_repository = \Drupal::service('file.repository');
    $file = $file_repository->writeData($data$destination, FileSystemInterface::EXISTS_ERROR);
    $values = [
      'target_id' => $file->id(),
      'display' => (int) $settings['display_default'],
      'description' => $random->sentences(10),
    ];

  public function handleFileUploadForField(FieldDefinitionInterface $field_definition$filename, AccountInterface $owner) {
    assert(is_a($field_definition->getClass(), FileFieldItemList::class, TRUE));
    $settings = $field_definition->getSettings();
    $destination = $this->getUploadLocation($settings);

    // Check the destination file path is writable.     if (!$this->fileSystem->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
      throw new HttpException(500, 'Destination file path is not writable');
    }

    $validators = $this->getUploadValidators($field_definition);

    $prepared_filename = $this->prepareFilename($filename$validators);

    // Create the file.     $file_uri = "{$destination}/{$prepared_filename}";
    if ($destination === $settings['uri_scheme'] . '://') {
      $file_uri = "{$destination}{$prepared_filename}";
    }
->save();
  }

  /** * Sets the value of the default translations directory. * * @param string $path * Path of the translations directory relative to the drupal installation * directory. */
  protected function setTranslationsDirectory($path) {
    \Drupal::service('file_system')->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY);
    $this->config('locale.settings')->set('translation.path', $path)->save();
  }

  /** * Adds a language. * * @param string $langcode * The language code of the language to add. */
  protected function addLanguage($langcode) {
    $edit = ['predefined_langcode' => $langcode];
    

  public static function getFileExtension() {
    return 'yml';
  }

  /** * Check if the directory exists and create it if not. */
  protected function ensureStorage() {
    $dir = $this->getCollectionDirectory();
    $success = $this->getFileSystem()->prepareDirectory($dir, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
    // Only create .htaccess file in root directory.     if ($dir == $this->directory) {
      $success = $success && FileSecurity::writeHtaccess($this->directory);
    }
    if (!$success) {
      throw new StorageException('Failed to create config directory ' . $dir);
    }
    return $this;
  }

  /** * {@inheritdoc} */
return $form;
  }

  /** * {@inheritdoc} */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Process the upload and perform validation. Note: we're using the     // form value for the $replace parameter.     if (!$form_state->isValueEmpty('file_subdir')) {
      $destination = 'temporary://' . $form_state->getValue('file_subdir');
      \Drupal::service('file_system')->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY);
    }
    else {
      $destination = FALSE;
    }

    // Preset custom error message if requested.     if ($form_state->getValue('error_message')) {
      $this->messenger->addError($form_state->getValue('error_message'));
    }

    // Setup validators.

  public function doImageStyleUrlAndPathTests($scheme$clean_url = TRUE, $extra_slash = FALSE, $langcode = FALSE) {
    $this->prepareRequestForGenerator($clean_url);

    // Make the default scheme neither "public" nor "private" to verify the     // functions work for other than the default scheme.     $this->config('system.file')->set('default_scheme', 'temporary')->save();

    // Create the directories for the styles.     $directory = $scheme . '://styles/' . $this->style->id();
    $status = \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
    $this->assertNotFalse($status, 'Created the directory for the generated images for the test style.');

    // Override the language to build the URL for the correct language.     if ($langcode) {
      $language_manager = \Drupal::service('language_manager');
      $language = $language_manager->getLanguage($langcode);
      $language_manager->setConfigOverrideLanguage($language);
    }

    // Create a working copy of the file.     $files = $this->drupalGetTestFiles('image');
    
protected function setUp(): void {
    parent::setUp();

    $this->installConfig(['system']);

    // Set the image factory service.     $this->imageFactory = $this->container->get('image.factory');
    $this->assertEquals('gd', $this->imageFactory->getToolkitId(), 'The image factory is set to use the \'gd\' image toolkit.');

    // Prepare a directory for test file results.     $this->directory = 'public://imagetest';
    \Drupal::service('file_system')->prepareDirectory($this->directory, FileSystemInterface::CREATE_DIRECTORY);
  }

  /** * Assert two colors are equal by RGBA, net of full transparency. * * @param int[] $expected * The expected RGBA array. * @param int[] $actual * The actual RGBA array. * @param int $tolerance * The acceptable difference between the colors. * @param string $message * The assertion message. */
/** * Initialize various configurations post-installation. * * @param \Symfony\Component\DependencyInjection\ContainerInterface $container * The container. */
  protected function initConfig(ContainerInterface $container) {
    $config = $container->get('config.factory');

    // Manually create the private directory.     \Drupal::service('file_system')->prepareDirectory($this->privateFilesDirectory, FileSystemInterface::CREATE_DIRECTORY);

    // Manually configure the test mail collector implementation to prevent     // tests from sending out emails and collect them in state instead.     // While this should be enforced via settings.php prior to installation,     // some tests expect to be able to test mail system implementations.     $config->getEditable('system.mail')
      ->set('interface.default', 'test_mail_collector')
      ->save();

    // By default, verbosely display all errors and disable all production     // environment optimizations for all tests to avoid needless overhead and
    $filename = $file_extension . '_' . Crypt::hashBase64($data) . '.' . $file_extension;
    $uri = $path . '/' . $filename;
    return $this->dumpToUri($data$file_extension$uri);
  }

  /** * {@inheritdoc} */
  public function dumpToUri(string $data, string $file_extension, string $uri): string {
    $path = 'assets://' . $file_extension;
    // Create the CSS or JS file.     $this->fileSystem->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY);
    try {
      if (!file_exists($uri) && !$this->fileSystem->saveData($data$uri, FileSystemInterface::EXISTS_REPLACE)) {
        return FALSE;
      }
    }
    catch (FileException $e) {
      return FALSE;
    }
    // If CSS/JS gzip compression is enabled and the zlib extension is available     // then create a gzipped version of this file. This file is served     // conditionally to browsers that accept gzip using .htaccess rules.
/** * Create a random config sync directory. * * @return string * The path to the generated config sync directory. */
  protected function createRandomConfigDirectory() {
    $config_sync_directory = $this->sitePath . '/files/config_' . Crypt::randomBytesBase64(55) . '/sync';
    // This should never fail, it is created here inside the public files     // directory, which has already been verified to be writable itself.     if (\Drupal::service('file_system')->prepareDirectory($config_sync_directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
      // Put a README.txt into the sync config directory. This is required so       // that they can later be added to git. Since this directory is       // auto-created, we have to write out the README rather than just adding       // it to the drupal core repo.       $text = 'This directory contains configuration to be imported into your Drupal site. To make this configuration active, visit admin/config/development/configuration/sync.' . ' For information about deploying configuration between servers, see https://www.drupal.org/documentation/administer/config';
      file_put_contents($config_sync_directory . '/README.txt', $text);
    }

    return $config_sync_directory;
  }

}
// We are going to set a missing zlib requirement property for usage     // during the performUpgrade() and tearDown() methods. Also set that the     // tests failed.     if (!$this->zlibInstalled) {
      parent::setUp();
      return;
    }
    $this->installDrupal();

    // Add the config directories to settings.php.     $sync_directory = Settings::get('config_sync_directory');
    \Drupal::service('file_system')->prepareDirectory($sync_directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);

    // Ensure the default temp directory exist and is writable. The configured     // temp directory may be removed during update.     \Drupal::service('file_system')->prepareDirectory($this->tempFilesDirectory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);

    // Set the container. parent::rebuildAll() would normally do this, but this     // not safe to do here, because the database has not been updated yet.     $this->container = \Drupal::getContainer();

    $this->replaceUser1();

    
// If the start and end file is exactly the same, there is nothing to do.     if ($this->isLocationUnchanged($source$destination)) {
      return $destination;
    }

    // Check if a writable directory exists, and if not try to create it.     $dir = $this->getDirectory($destination);
    // If the directory exists and is writable, avoid     // \Drupal\Core\File\FileSystemInterface::prepareDirectory() call and write     // the file to destination.     if (!is_dir($dir) || !is_writable($dir)) {
      if (!$this->fileSystem->prepareDirectory($dir, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
        throw new MigrateException("Could not create or write to directory '$dir'");
      }
    }

    $final_destination = $this->writeFile($source$destination$this->configuration['file_exists']);
    if ($final_destination) {
      return $final_destination;
    }
    throw new MigrateException("File $source could not be copied to $destination");
  }

  

  public function validateForm(array &$form, FormStateInterface $form_state) {}

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Process the upload and perform validation. Note: we're using the     // form value for the $replace parameter.     if (!$form_state->isValueEmpty('file_subdir')) {
      $destination = 'temporary://' . $form_state->getValue('file_subdir');
      \Drupal::service('file_system')->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY);
    }
    else {
      $destination = FALSE;
    }

    // Setup validators.     $validators = [];
    if ($form_state->getValue('is_image_file')) {
      $validators['file_validate_is_image'] = [];
    }

    
Home | Imprint | This part of the site doesn't use cookies.