FileStorage example

      'bin' => 'test',
    ];
  }

  /** * Tests writing with one class and reading with another. */
  public function testReadOnly() {
    // Random generator.     $random = new Random();

    $php = new FileStorage($this->standardSettings);
    $name = $random->name(8, TRUE) . '/' . $random->name(8, TRUE) . '.php';

    // Find a global that doesn't exist.     do {
      $random = 'test' . mt_rand(10000, 100000);
    } while (isset($GLOBALS[$random]));

    // Write out a PHP file and ensure it's successfully loaded.     $code = "<?php\n\$GLOBALS['$random'] = TRUE;";
    $success = $php->save($name$code);
    $this->assertTrue($success);
    
protected $defaultTheme = 'stark';

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    // Install the optional configs from the standard profile.     $extension_path = $this->container->get('extension.list.profile')->getPath('standard');
    $optional_install_path = $extension_path . '/' . InstallStorage::CONFIG_OPTIONAL_DIRECTORY;
    $storage = new FileStorage($optional_install_path);
    $this->container->get('config.installer')->installOptionalConfig($storage, '');
    // Reset all the static caches and list caches.     $this->container->get('config.factory')->reset();

    // This test is going to test the display, so we need the standalone URL.     \Drupal::configFactory()
      ->getEditable('media.settings')
      ->set('standalone_url', TRUE)
      ->save(TRUE);

    $this->container->get('router.builder')->rebuild();
  }
public function installDefaultConfig($type$name) {
    $extension_path = $this->extensionPathResolver->getPath($type$name);
    // Refresh the schema cache if the extension provides configuration schema     // or is a theme.     if (is_dir($extension_path . '/' . InstallStorage::CONFIG_SCHEMA_DIRECTORY) || $type == 'theme') {
      $this->typedConfig->clearCachedDefinitions();
    }

    $default_install_path = $this->getDefaultConfigDirectory($type$name);
    if (is_dir($default_install_path)) {
      if (!$this->isSyncing()) {
        $storage = new FileStorage($default_install_path, StorageInterface::DEFAULT_COLLECTION);
        $prefix = '';
      }
      else {
        // The configuration importer sets the source storage on the config         // installer. The configuration importer handles all of the         // configuration entity imports. We only need to ensure that simple         // configuration is created when the extension is installed.         $storage = $this->getSourceStorage();
        $prefix = $name . '.';
      }

      
public function load(TemplateReferenceInterface $template): Storage|false
    {
        $key = hash('sha256', $template->getLogicalName());
        $dir = $this->dir.\DIRECTORY_SEPARATOR.substr($key, 0, 2);
        $file = substr($key, 2).'.tpl';
        $path = $dir.\DIRECTORY_SEPARATOR.$file;

        if (is_file($path)) {
            $this->logger?->debug('Fetching template from cache.', ['name' => $template->get('name')]);

            return new FileStorage($path);
        }

        if (false === $storage = $this->loader->load($template)) {
            return false;
        }

        $content = $storage->getContent();

        if (!is_dir($dir) && !@mkdir($dir, 0777, true) && !is_dir($dir)) {
            throw new \RuntimeException(sprintf('Cache Loader was not able to create directory "%s".', $dir));
        }

        


  /** * Tests basic load/save/delete operations. * * @covers ::load * @covers ::save * @covers ::exists * @covers ::delete */
  public function testCRUD() {
    $php = new FileStorage($this->standardSettings);
    $this->assertCRUD($php);
  }

  /** * @covers ::writeable * @group legacy */
  public function testWritable() {
    $this->expectDeprecation('Drupal\Component\PhpStorage\FileStorage::writeable() is deprecated in drupal:10.1.0 and will be removed from drupal:11.0.0. There is no replacement. See https://www.drupal.org/node/3155413');
    $php = new FileStorage($this->standardSettings);
    $this->assertTrue($php->writeable());
  }
        'HTML' => '<strong> <bold> <em> <blockquote>',
        // UTF-8 in values.         'UTF-8' => 'FrançAIS is ÜBER-åwesome',
        // Unicode in keys and values.         // cSpell:disable-next-line         'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ' => 'αβγδεζηθικλμνξοσὠ',
      ],
      'invalid xml' => '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ',
    ];

    // Encode and write, and reload and decode the configuration data.     $filestorage = new FileStorage(Settings::get('config_sync_directory'));
    $filestorage->write($name$config_data);
    $config_parsed = $filestorage->read($name);

    $key = 'numeric keys';
    $this->assertSame($config_data[$key]$config_parsed[$key]);

    $key = 'nested keys';
    $this->assertSame($config_data[$key]$config_parsed[$key]);

    $key = 'HTML';
    $this->assertSame($config_data['nested keys'][$key]$config_parsed['nested keys'][$key]);

    
// Save config which does not have a schema that enforces types.     $this->config('config_schema_test.no_schema_data_types')
      ->setData($untyped_values)
      ->save();
    $this->assertSame($untyped_values$this->config('config_schema_test.no_schema_data_types')->get());

    // Ensure that configuration objects with keys marked as ignored are not     // changed when saved. The 'config_schema_test.ignore' will have been saved     // during the installation of configuration in the setUp method.     $extension_path = __DIR__ . '/../../../../../modules/config/tests/config_schema_test/';
    $install_storage = new FileStorage($extension_path . InstallStorage::CONFIG_INSTALL_DIRECTORY);
    $original_data = $install_storage->read('config_schema_test.ignore');
    $installed_data = $this->config('config_schema_test.ignore')->get();
    unset($installed_data['_core']);
    $this->assertSame($original_data$installed_data);
  }

  /** * Test configuration value data type enforcement using schemas. */
  public function testConfigSaveMappingSort() {
    // Top level map sorting.

  protected $directory;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    // Create a directory.     $this->directory = PublicStream::basePath() . '/config';
    $this->storage = new FileStorage($this->directory);
    $this->invalidStorage = new FileStorage($this->directory . '/nonexisting');

    // FileStorage::listAll() requires other configuration data to exist.     $this->storage->write('system.performance', $this->config('system.performance')->get());
    $this->storage->write('core.extension', ['module' => []]);
  }

  protected function read($name) {
    $data = file_get_contents($this->storage->getFilePath($name));
    return Yaml::decode($data);
  }

  
'#title' => $this->t('Select an installation profile'),
      '#title_display' => 'invisible',
      '#options' => array_map([$this, 't']$names),
      '#default_value' => 'standard',
    ];
    foreach (array_keys($names) as $profile_name) {
      $form['profile'][$profile_name]['#description'] = isset($profiles[$profile_name]['description']) ? $this->t($profiles[$profile_name]['description']) : '';
    }

    $config_sync_directory = Settings::get('config_sync_directory');
    if (!empty($config_sync_directory)) {
      $sync = new FileStorage($config_sync_directory);
      $extensions = $sync->read('core.extension');
      $site = $sync->read('system.site');
      if (isset($site['name']) && isset($extensions['profile']) && in_array($extensions['profile']array_keys($names), TRUE)) {
        // Ensure the profile can be installed from configuration. Install         // profile's which implement hook_INSTALL() are not supported.         // @todo https://www.drupal.org/project/drupal/issues/2982052 Remove         // this restriction.         $root = \Drupal::root();
        include_once $root . '/core/includes/install.inc';
        $file = $root . '/' . $install_state['profiles'][$extensions['profile']]->getPath() . "/{$extensions['profile']}.install";
        if (is_file($file)) {
          
/** * Asserts that the default configuration of a module has been installed. * * @param string $module * The name of the module. */
  public function assertModuleConfig($module) {
    $module_config_dir = $this->getModulePath($module) . '/' . InstallStorage::CONFIG_INSTALL_DIRECTORY;
    if (!is_dir($module_config_dir)) {
      return;
    }
    $module_file_storage = new FileStorage($module_config_dir);

    // Verify that the module's default config directory is not empty and     // contains default configuration files (instead of something else).     $all_names = $module_file_storage->listAll();
    if (empty($all_names)) {
      // Module has an empty config directory. For example it might contain a       // schema directory.       return;
    }
    $this->assertNotEmpty($all_names);

    
$this->assertSession()->pageTextContains('Experimental profiles are provided for testing purposes only. Use at your own risk. To start building a new site, reinstall Drupal and choose a non-experimental profile.');
  }

  /** * Tests the profile supplied configuration is the same after installation. */
  public function testConfig() {
    // Just connect directly to the config table so we don't need to worry about     // the cache layer.     $active_config_storage = $this->container->get('config.storage');

    $default_config_storage = new FileStorage($this->container->get('extension.list.profile')->getPath('demo_umami') . '/' . InstallStorage::CONFIG_INSTALL_DIRECTORY, InstallStorage::DEFAULT_COLLECTION);
    $this->assertDefaultConfig($default_config_storage$active_config_storage);

    $default_config_storage = new FileStorage($this->container->get('extension.list.profile')->getPath('demo_umami') . '/' . InstallStorage::CONFIG_OPTIONAL_DIRECTORY, InstallStorage::DEFAULT_COLLECTION);
    $this->assertDefaultConfig($default_config_storage$active_config_storage);
  }

  /** * Asserts that the default configuration matches active configuration. * * @param \Drupal\Core\Config\StorageInterface $default_config_storage * The default configuration storage to check. * @param \Drupal\Core\Config\StorageInterface $active_config_storage * The active configuration storage. */
&& $info[ExtensionLifecycle::LIFECYCLE_IDENTIFIER] === ExtensionLifecycle::DEPRECATED) {
      $this->markTestSkipped("The $type '$name' is deprecated.");
    }

    // System and user are required in order to be able to install some of the     // other modules. Therefore they are put into static::$modules, which though     // doesn't install config files, so import those config files explicitly. Do     // this for all tests in case optional configuration depends on it.     $this->installConfig(['system', 'user']);

    $extension_path = \Drupal::service('extension.path.resolver')->getPath($type$name) . '/';
    $extension_config_storage = new FileStorage($extension_path . InstallStorage::CONFIG_INSTALL_DIRECTORY, StorageInterface::DEFAULT_COLLECTION);
    $optional_config_storage = new FileStorage($extension_path . InstallStorage::CONFIG_OPTIONAL_DIRECTORY, StorageInterface::DEFAULT_COLLECTION);

    if (empty($optional_config_storage->listAll()) && empty($extension_config_storage->listAll())) {
      $this->markTestSkipped("$name has no configuration to test");
    }

    // Work out any additional modules and themes that need installing to create     // an optional config.     $modules_to_install = $type !== 'theme' ? [$name] : [];
    $themes_to_install = $type === 'theme' ? [$name] : [];
    foreach ($optional_config_storage->listAll() as $config_name) {
      

class FileStorageFactoryTest extends KernelTestBase {

  /** * @covers ::getSync */
  public function testGetSync() {

    // Write some random data to the sync storage.     $name = $this->randomMachineName();
    $data = (array) $this->getRandomGenerator()->object();
    $storage = new FileStorage(Settings::get('config_sync_directory'));
    $storage->write($name$data);

    // Get the sync storage and read from it.     $sync = FileStorageFactory::getSync();
    $this->assertEquals($data$sync->read($name));

    // Unset the sync directory setting.     $settings = Settings::getInstance() ? Settings::getAll() : [];
    unset($settings['config_sync_directory']);
    new Settings($settings);

    

  public static function getSync() {
    $directory = Settings::get('config_sync_directory', FALSE);
    if ($directory === FALSE) {
      throw new ConfigDirectoryNotDefinedException('The config sync directory is not defined in $settings["config_sync_directory"]');
    }
    return new FileStorage($directory);
  }

}

  protected function assertInstalledConfig(array $skipped_config) {
    $this->addToAssertionCount(1);
    /** @var \Drupal\Core\Config\StorageInterface $active_config_storage */
    $active_config_storage = $this->container->get('config.storage');
    /** @var \Drupal\Core\Config\ConfigManagerInterface $config_manager */
    $config_manager = $this->container->get('config.manager');

    $default_install_path = 'core/profiles/' . $this->profile . '/' . InstallStorage::CONFIG_INSTALL_DIRECTORY;
    $profile_config_storage = new FileStorage($default_install_path, StorageInterface::DEFAULT_COLLECTION);

    foreach ($profile_config_storage->listAll() as $config_name) {
      $result = $config_manager->diff($profile_config_storage$active_config_storage$config_name);
      $this->assertConfigDiff($result$config_name$skipped_config);
    }
  }

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