Settings example

    $this->drupalGet('form-test/object-builder');

    $this->assertSession()->titleEquals('Test dynamic title | Drupal');
    $this->assertSession()->elementTextEquals('xpath', '//h1[@class="page-title"]', 'Test dynamic title');

    // Set some custom translated strings.     $settings_key = 'locale_custom_strings_en';

    // Update in-memory settings directly.     $settings = Settings::getAll();
    $settings[$settings_key] = ['' => ['Static title' => 'Static title translated']];
    new Settings($settings);

    // Rewrites the settings.php.     $this->writeSettings([
      'settings' => [
        $settings_key => (object) [
          'value' => $settings[$settings_key],
          'required' => TRUE,
        ],
      ],
    ]);

    
->onlyMethods(['get'])
      ->getMock();

    $this->sessionMetadata = $this->getMockBuilder('Drupal\Core\Session\MetadataBag')
      ->disableOriginalConstructor()
      ->getMock();

    $settings = [
      'hash_salt' => $this->randomMachineName(),
    ];

    new Settings($settings);

    $this->generator = new CsrfTokenGenerator($this->privateKey, $this->sessionMetadata);
  }

  /** * Set up default expectations on the mocks. */
  protected function setupDefaultExpectations() {
    $key = Crypt::randomBytesBase64();
    $this->privateKey->expects($this->any())
      ->method('get')
      
class DatabaseBackendFactoryTest extends UnitTestCase {

  /** * @covers ::__construct * @covers ::get * @dataProvider getProvider */
  public function testGet(array $settings$expected_max_rows_foo$expected_max_rows_bar) {
    $database_backend_factory = new DatabaseBackendFactory(
      $this->prophesize(Connection::class)->reveal(),
      $this->prophesize(CacheTagsChecksumInterface::class)->reveal(),
      new Settings($settings)
    );

    $this->assertSame($expected_max_rows_foo$database_backend_factory->get('foo')->getMaxRows());
    $this->assertSame($expected_max_rows_bar$database_backend_factory->get('bar')->getMaxRows());
  }

  public function getProvider() {
    return [
      'default' => [
        [],
        DatabaseBackend::DEFAULT_MAX_ROWS,
        

  protected LoggerInterface $logger;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    $this->mockConfigFactory = $this->getConfigFactoryStub(['update.settings' => ['fetch_url' => 'http://www.example.com']]);
    $this->mockHttpClient = $this->createMock('\GuzzleHttp\ClientInterface');
    $settings = new Settings([]);
    $this->logger = new TestLogger();
    $this->updateFetcher = new UpdateFetcher($this->mockConfigFactory, $this->mockHttpClient, $settings$this->logger);
    $this->testProject = [
      'name' => 'update_test',
      'project_type' => '',
      'info' => [
        'version' => '',
        'project status url' => 'https://www.example.com',
      ],
      'includes' => ['module1' => 'Module 1', 'module2' => 'Module 2'],
    ];
  }

class UpdateRegistryTest extends UnitTestCase {

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

    $settings = [];
    $settings['extension_discovery_scan_tests'] = TRUE;
    new Settings($settings);
  }

  /** * Sets up some extensions with some update functions. */
  protected function setupBasicExtensions() {
    $info_a = <<<'EOS' type: module name: Module A core_version_requirement: '*' EOS;

    

  protected function rebootAndPrepareSettings() {
    // Reboot the container so that different services are injected and the new     // settings are picked.     $kernel = $this->container->get('kernel');
    $kernel->shutdown();
    $kernel->boot();
    $settings = Settings::getAll();
    $settings['locale_custom_strings_de'] = ['' => ['Example @number' => 'Example @number translated']];
    // Recreate the settings static.     new Settings($settings);
  }

}

class CacheFactoryTest extends UnitTestCase {

  /** * Tests that the cache factory falls back to the built-in default service. * * @covers ::__construct * @covers ::get */
  public function testCacheFactoryWithDefaultSettings() {
    $settings = new Settings([]);
    $cache_factory = new CacheFactory($settings);

    $container = new ContainerBuilder();
    $cache_factory->setContainer($container);

    $builtin_default_backend_factory = $this->createMock('\Drupal\Core\Cache\CacheFactoryInterface');
    $container->set('cache.backend.database', $builtin_default_backend_factory);

    $render_bin = $this->createMock('\Drupal\Core\Cache\CacheBackendInterface');
    $builtin_default_backend_factory->expects($this->once())
      ->method('get')
      
$this->assertEquals($this->formState->get('example')$cached_form_state->get('example'));

    // Restore user account.     $account_switcher->switchBack();
  }

  /** * Tests the form cache with an overridden cache expiration. */
  public function testCacheCustomExpiration() {
    // Override form cache expiration so that the cached form expired yesterday.     new Settings(['form_cache_expiration' => -1 * (24 * 60 * 60), 'hash_salt' => $this->randomMachineName()]);
    \Drupal::formBuilder()->setCache($this->formBuildId, $this->form, $this->formState);

    $cached_form_state = new FormState();
    $this->assertNull(\Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state), 'Expired form not returned from cache');
  }

}
'#type' => 'inline_template',
      '#template' => 'test-with-context <label>{{ unsafe_content }}</label>',
      '#context' => ['unsafe_content' => $unsafe_string],
    ];
    $this->assertSame('test-with-context <label>' . Html::escape($unsafe_string) . '</label>', (string) $renderer->renderRoot($element));

    // Enable twig_auto_reload and twig_debug.     $settings = Settings::getAll();
    $settings['twig_debug'] = TRUE;
    $settings['twig_auto_reload'] = TRUE;

    new Settings($settings);
    $this->container = \Drupal::service('kernel')->rebuildContainer();
    \Drupal::setContainer($this->container);

    $element = [];
    $element['test'] = [
      '#type' => 'inline_template',
      '#template' => 'test-with-context {{ llama }}',
      '#context' => ['llama' => 'muuh'],
    ];
    $element_copy = $element;
    // Render it twice so that twig caching is triggered.
$buffer .= self::exportSettingsToPhp($setting, '$' . $name);
      }

      // Write the new settings file.       if (file_put_contents($settings_file$buffer) === FALSE) {
        throw new \Exception("Failed to modify '$settings_file'. Verify the file permissions.");
      }
      // In case any $settings variables were written, import them into the       // Settings singleton.       if (!empty($settings_settings)) {
        $old_settings = Settings::getAll();
        new Settings($settings_settings + $old_settings);
      }
      // The existing settings.php file might have been included already. In       // case an opcode cache is enabled, the rewritten contents of the file       // will not be reflected in this process. Ensure to invalidate the file       // in case an opcode cache is enabled.       OpCodeCache::invalidate(DRUPAL_ROOT . '/' . $settings_file);
    }
    else {
      throw new \Exception("Failed to open '$settings_file'. Verify the file permissions.");
    }
  }

  
/** * @coversDefaultClass \Drupal\Core\Session\MetadataBag * @group Session */
class MetadataBagTest extends UnitTestCase {

  /** * @covers ::stampNew */
  public function testStampNew() {
    $metadata = new MetadataBag(new Settings([]));
    $metadata->setCsrfTokenSeed('a_cryptographically_secure_long_random_string_should_used_here');
    $metadata->stampNew();
    $this->assertNotEquals('a_cryptographically_secure_long_random_string_should_used_here', $metadata->getCsrfTokenSeed());
  }

}
/** * Tests writable files remain writable when directory hardening is disabled. */
  public function testSitesDirectoryHardeningConfig() {
    $site_path = $this->kernel->getSitePath();
    $settings_file = $this->settingsFile($site_path);

    // Disable permissions enforcement.     $settings = Settings::getAll();
    $settings['skip_permissions_hardening'] = TRUE;
    new Settings($settings);
    $this->assertTrue(Settings::get('skip_permissions_hardening'), 'Able to set skip permissions hardening to true.');
    $this->makeWritable($site_path);

    // Manually trigger the requirements check.     $requirements = $this->checkSystemRequirements();
    $this->assertEquals(REQUIREMENT_WARNING, $requirements['configuration_files']['severity'], 'Warning severity is properly set.');
    $this->assertEquals('Protection disabled', (string) $requirements['configuration_files']['value']);
    $description = strip_tags(\Drupal::service('renderer')->renderPlain($requirements['configuration_files']['description']));
    $this->assertStringContainsString('settings.php is not protected from modifications and poses a security risk.', $description);
    $this->assertStringContainsString('services.yml is not protected from modifications and poses a security risk.', $description);

    

class YamlTest extends UnitTestCase {

  /** * Tests that the overridden serializer is called. * * @covers ::getSerializer * @runInSeparateProcess */
  public function testGetSerialization() {
    new Settings(['yaml_parser_class' => YamlParserProxy::class]);

    $this->assertEquals(YamlParserProxy::class, Settings::get('yaml_parser_class'));

    $mock = $this->getMockBuilder(YamlTestMockInterface::class)
      ->onlyMethods(['decode'])
      ->getMock();
    $mock
      ->expects($this->once())
      ->method('decode');
    YamlParserProxy::setMock($mock);
    Yaml::decode('---');

    
$this->moduleData = [
      'system' => new Extension($this->root, 'module', 'core/modules/system/system.info.yml', 'system.module'),
    ];
  }

  /** * {@inheritdoc} */
  public function boot() {
    // Ensure that required Settings exist.     if (!Settings::getAll()) {
      new Settings([
        'hash_salt' => 'run-tests',
        'container_yamls' => [],
        // If there is no settings.php, then there is no parent site. In turn,         // there is no public files directory; use a custom public files path.         'file_public_path' => 'sites/default/files',
      ]);
    }

    // Remove Drupal's error/exception handlers; they are designed for HTML     // and there is no storage nor a (watchdog) logger here.     restore_error_handler();
    

    protected function resolveAlbumData(array $data$album)
    {
        $settings = $album->getSettings();

        if (!$settings) {
            $settings = new Settings();
            $settings->setAlbum($album);
        }
        // Validate album name         if (empty($data['text'])) {
            throw new Exception('No valid album name passed!');
        }
        $data['name'] = $data['text'];

        $data['parent'] = null;
        if (!empty($data['parentId']) && $data['parentId'] !== 'root') {
            $parent = $this->getManager()->find(Album::class$data['parentId']);
            
Home | Imprint | This part of the site doesn't use cookies.