You are here

class SettingsForm in Acquia Connector 8.2

Same name and namespace in other branches
  1. 8 src/Form/SettingsForm.php \Drupal\acquia_connector\Form\SettingsForm
  2. 3.x src/Form/SettingsForm.php \Drupal\acquia_connector\Form\SettingsForm

Acquia Connector Settings.

@package Drupal\acquia_connector\Form

Hierarchy

Expanded class hierarchy of SettingsForm

1 string reference to 'SettingsForm'
acquia_connector.routing.yml in ./acquia_connector.routing.yml
acquia_connector.routing.yml

File

src/Form/SettingsForm.php, line 24

Namespace

Drupal\acquia_connector\Form
View source
class SettingsForm extends ConfigFormBase {

  /**
   * The config factory interface.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The private key.
   *
   * @var \Drupal\Core\PrivateKey
   */
  protected $privateKey;

  /**
   * The Acquia connector client.
   *
   * @var \Drupal\acquia_connector\Client
   */
  protected $client;

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\State
   */
  protected $state;

  /**
   * The spi backend.
   *
   * @var \Drupal\acquia_connector\Controller\SpiController
   */
  protected $spiController;

  /**
   * Constructs a \Drupal\aggregator\SettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\PrivateKey $private_key
   *   The private key.
   * @param \Drupal\acquia_connector\Client $client
   *   The Acquia client.
   * @param \Drupal\Core\State\State $state
   *   The State handler.
   * @param \Drupal\acquia_connector\Controller\SpiController $spi_controller
   *   SPI backend.
   */
  public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, PrivateKey $private_key, Client $client, State $state, SpiController $spi_controller) {
    parent::__construct($config_factory);
    $this->moduleHandler = $module_handler;
    $this->privateKey = $private_key;
    $this->client = $client;
    $this->state = $state;
    $this->spiController = $spi_controller;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('module_handler'), $container
      ->get('private_key'), $container
      ->get('acquia_connector.client'), $container
      ->get('state'), $container
      ->get('acquia_connector.spi'));
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'acquia_connector.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'acquia_connector_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('acquia_connector.settings');
    $storage = new Storage();
    $identifier = $storage
      ->getIdentifier();
    $key = $storage
      ->getKey();
    $subscription = $config
      ->get('subscription_name');
    if (empty($identifier) && empty($key)) {
      return new RedirectResponse((string) \Drupal::service('url_generator')
        ->generateFromRoute('acquia_connector.start'));
    }

    // Check our connection to the Acquia and validate credentials.
    try {
      $this->client
        ->getSubscription($identifier, $key);
    } catch (ConnectorException $e) {
      $error_message = acquia_connector_connection_error_message($e
        ->getCustomMessage('code', FALSE));
      $ssl_available = in_array('ssl', stream_get_transports(), TRUE) && !defined('ACQUIA_CONNECTOR_TEST_ACQUIA_DEVELOPMENT_NOSSL') && $config
        ->get('spi.ssl_verify');
      if (empty($error_message) && $ssl_available) {
        $error_message = $this
          ->t('There was an error in validating your subscription credentials. You may want to try disabling SSL peer verification by setting the variable acquia_connector.settings:spi.ssl_verify to false.');
      }
      $this
        ->messenger()
        ->addError($error_message);
    }
    $form['connected'] = [
      '#markup' => $this
        ->t('<h3>Connected to Acquia</h3>'),
    ];
    if (!empty($subscription)) {
      $form['subscription'] = [
        '#markup' => $this
          ->t('Subscription: @sub <a href=":url">change</a>', [
          '@sub' => $subscription,
          ':url' => (string) \Drupal::service('url_generator')
            ->generateFromRoute('acquia_connector.setup'),
        ]),
      ];
    }
    $form['identification'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Site Identification'),
      '#collapsible' => FALSE,
    ];
    $form['identification']['description']['#markup'] = $this
      ->t('Provide a name for this site to uniquely identify it on Acquia Cloud.');
    $form['identification']['description']['#weight'] = -2;
    $form['identification']['site'] = [
      '#prefix' => '<div class="acquia-identification">',
      '#suffix' => '</div>',
      '#weight' => -1,
    ];
    $form['identification']['site']['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#maxlength' => 255,
      '#required' => TRUE,
      '#default_value' => $this->state
        ->get('spi.site_name') ?? $this->spiController
        ->getAcquiaHostedName(),
    ];
    if (!empty($form['identification']['site']['name']['#default_value']) && $this->spiController
      ->checkAcquiaHosted()) {
      $form['identification']['site']['name']['#disabled'] = TRUE;
    }
    if ($this->spiController
      ->checkAcquiaHosted()) {
      $form['identification']['#description'] = $this
        ->t('Acquia hosted sites are automatically provided with a machine name.');
    }
    $form['identification']['site']['machine_name'] = [
      '#type' => 'machine_name',
      '#title' => $this
        ->t('Machine name'),
      '#maxlength' => 255,
      '#required' => TRUE,
      '#machine_name' => [
        'exists' => [
          $this,
          'exists',
        ],
        'source' => [
          'identification',
          'site',
          'name',
        ],
      ],
      '#default_value' => $this->state
        ->get('spi.site_machine_name'),
    ];
    if ($this->spiController
      ->checkAcquiaHosted()) {
      $form['identification']['site']['machine_name']['#default_value'] = $this->state
        ->get('spi.site_machine_name') ?: $this->spiController
        ->getAcquiaHostedMachineName();
      $form['identification']['site']['machine_name']['#disabled'] = TRUE;
    }
    $form['connection'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Acquia Subscription Settings'),
      '#collapsible' => FALSE,
    ];

    // Help documentation is local unless the Help module is disabled.
    if ($this->moduleHandler
      ->moduleExists('help')) {
      $help_url = Url::fromRoute('help.page', [
        'name' => 'acquia_connector',
      ])
        ->toString();
    }
    else {
      $help_url = Url::fromUri('https://docs.acquia.com/acquia-cloud/insight/install/')
        ->getUri();
    }
    if (!empty($identifier) && !empty($key)) {
      $form['connection']['spi'] = [
        '#prefix' => '<div class="acquia-spi">',
        '#suffix' => '</div>',
        '#weight' => 0,
      ];
      $form['connection']['description']['#markup'] = $this
        ->t('Allow collection and examination of the following items. <a href=":url">Learn more</a>.', [
        ':url' => $help_url,
      ]);
      $form['connection']['description']['#weight'] = '-1';
      $form['connection']['spi']['admin_priv'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Admin privileges'),
        '#default_value' => $config
          ->get('spi.admin_priv'),
      ];
      $form['connection']['spi']['send_node_user'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Nodes and users'),
        '#default_value' => $config
          ->get('spi.send_node_user'),
      ];
      $form['connection']['spi']['send_watchdog'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Watchdog logs'),
        '#default_value' => $config
          ->get('spi.send_watchdog'),
      ];
      $form['connection']['acquia_dynamic_banner'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Receive updates from Acquia Subscription'),
        '#default_value' => $config
          ->get('spi.dynamic_banner'),
      ];
      $form['connection']['alter_variables'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Allow Insight to update list of approved variables.'),
        '#default_value' => (int) $config
          ->get('spi.set_variables_override'),
        '#description' => $this
          ->t('Insight can set variables on your site to recommended values at your approval, but only from a specific list of variables. Check this box to allow Insight to update the list of approved variables. <a href=":url">Learn more</a>.', [
          ':url' => $help_url,
        ]),
      ];
      $use_cron = $config
        ->get('spi.use_cron');
      $form['connection']['use_cron'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Send via Drupal cron'),
        '#default_value' => $use_cron,
      ];
      $form['#attached']['library'][] = 'acquia_connector/acquia_connector.form';
      $key = sha1($this->privateKey
        ->get());

      // phpcs:ignore
      $url = Url::fromRoute('acquia_connector.send', [], [
        'query' => [
          'key' => $key,
        ],
        'absolute' => TRUE,
      ])
        ->toString();
      $form['connection']['use_cron_url'] = [
        '#type' => 'container',
        '#children' => $this
          ->t("Enter the following URL in your server's crontab to send SPI data:<br /><em>:url</em>", [
          ':url' => $url,
        ]),
        '#states' => [
          'visible' => [
            ':input[name="use_cron"]' => [
              'checked' => FALSE,
            ],
          ],
        ],
      ];
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * Determines if the machine name already exists.
   *
   * @return bool
   *   FALSE.
   */
  public function exists() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->configFactory()
      ->getEditable('acquia_connector.settings');
    $values = $form_state
      ->getValues();
    $this->state
      ->set('spi.site_name', $values['name']);
    $config
      ->set('spi.dynamic_banner', $values['acquia_dynamic_banner'])
      ->set('spi.admin_priv', $values['admin_priv'])
      ->set('spi.send_node_user', $values['send_node_user'])
      ->set('spi.send_watchdog', $values['send_watchdog'])
      ->set('spi.use_cron', $values['use_cron'])
      ->set('spi.set_variables_override', $values['alter_variables'])
      ->save();

    // If the machine name changed, send information so we know if it is a dupe.
    if ($values['machine_name'] != $this->state
      ->get('spi.site_machine_name')) {
      $this->state
        ->set('spi.site_machine_name', $values['machine_name']);
      $response = \Drupal::service('acquia_connector.spi')
        ->sendFullSpi(ACQUIA_CONNECTOR_ACQUIA_SPI_METHOD_CREDS);
      \Drupal::service('acquia_connector.spi')
        ->spiProcessMessages($response);
    }
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
SettingsForm::$client protected property The Acquia connector client.
SettingsForm::$configFactory protected property The config factory interface. Overrides FormBase::$configFactory
SettingsForm::$moduleHandler protected property The module handler.
SettingsForm::$privateKey protected property The private key.
SettingsForm::$spiController protected property The spi backend.
SettingsForm::$state protected property The state service.
SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
SettingsForm::exists public function Determines if the machine name already exists.
SettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SettingsForm::__construct public function Constructs a \Drupal\aggregator\SettingsForm object. Overrides ConfigFormBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.