<?php

namespace Drupal\Tests\netforum\Traits;

use Drupal\Core\Config\Config;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\StorageInterface;

/**
 * Reusable configuration operations for tests. Make sure to call
 * configureNetForumConfig() in setUp().
 */
trait NetForumConfigTrait {

  private ConfigFactoryInterface $configFactory;

  private StorageInterface $configStorage;

  private function configureNetForumConfig(ConfigFactoryInterface $configFactory, StorageInterface $configStorage): void {
    $this->configFactory = $configFactory;
    $this->configStorage = $configStorage;
  }

  /**
   * Reset configuration to the defaults included with the module.
   */
  private function resetConfiguration(): void {
    $currentConfig = $this->getEditableConfiguration();
    $defaultSettings = $this->configStorage->read('netforum.settings');
    if ($defaultSettings === FALSE) {
      throw new \RuntimeException('Could not read default configuration.');
    }

    $currentConfig->delete();
    $currentConfig->setData($defaultSettings);
    $currentConfig->save();
  }

  private function getEditableConfiguration(): Config {
    return $this->configFactory->getEditable('netforum.settings');
  }

}
