You are here

class CredentialForm in Acquia Connector 8

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

Form for Acquia Credentials.

Hierarchy

Expanded class hierarchy of CredentialForm

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

File

src/Form/CredentialForm.php, line 18

Namespace

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

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

  /**
   * Constructs a \Drupal\system\ConfigFormBase object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\acquia_connector\Client $client
   *   The Acquia client.
   */
  public function __construct(ConfigFactoryInterface $config_factory, Client $client) {
    $this->configFactory = $config_factory;
    $this->client = $client;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $storage = new Storage();
    $form['#prefix'] = $this
      ->t('Enter your product keys from your <a href=":net">application overview</a> or <a href=":url">log in</a> to connect your site to Acquia Insight.', [
      ':net' => Url::fromUri('https://cloud.acquia.com')
        ->getUri(),
      ':url' => Url::fromRoute('acquia_connector.setup')
        ->toString(),
    ]);
    $form['acquia_identifier'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Identifier'),
      '#default_value' => $storage
        ->getIdentifier(),
      '#required' => TRUE,
    ];
    $form['acquia_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Network key'),
      '#default_value' => $storage
        ->getKey(),
      '#required' => TRUE,
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Connect'),
    ];
    $form['actions']['signup'] = [
      '#markup' => $this
        ->t('Need a subscription? <a href=":url">Get one</a>.', [
        ':url' => Url::fromUri('https://www.acquia.com/acquia-cloud-free')
          ->getUri(),
      ]),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    try {
      $response = $this->client
        ->nspiCall('/agent-api/subscription', [
        'identifier' => trim($form_state
          ->getValue('acquia_identifier')),
      ], trim($form_state
        ->getValue('acquia_key')));
    } catch (ConnectorException $e) {

      // Set form error to prevent switching to the next page.
      if ($e
        ->isCustomized()) {

        // Allow to connect with expired subscription.
        if ($e
          ->getCustomMessage('code') == Subscription::EXPIRED) {
          $form_state
            ->setValue('subscription', 'Expired subscription.');
          return;
        }
        acquia_connector_report_restapi_error($e
          ->getCustomMessage('code'), $e
          ->getCustomMessage());
        $form_state
          ->setErrorByName('');
      }
      else {
        $form_state
          ->setErrorByName('', $this
          ->t('Server error, please submit again.'));
      }
      return;
    }
    $response = $response['result'];
    if (empty($response['body']['subscription_name'])) {
      $form_state
        ->setErrorByName('acquia_identifier', $this
        ->t('No subscriptions were found.'));
    }
    else {
      $form_state
        ->setValue('subscription', $response['body']['subscription_name']);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('acquia_connector.settings');
    $config
      ->set('subscription_name', $form_state
      ->getValue('subscription'))
      ->save();
    $storage = new Storage();
    $storage
      ->setKey($form_state
      ->getValue('acquia_key'));
    $storage
      ->setIdentifier($form_state
      ->getValue('acquia_identifier'));

    // Check subscription and send a heartbeat to Acquia via XML-RPC.
    // Our status gets updated locally via the return data.
    $subscription = new Subscription();
    $subscription_data = $subscription
      ->update();

    // Redirect to the path without the suffix.
    $form_state
      ->setRedirect('acquia_connector.settings');
    drupal_flush_all_caches();
    if ($subscription_data['active']) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('<h3>Connection successful!</h3>You are now connected to Acquia Cloud. Please enter a name for your site to begin sending profile data.'));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
CredentialForm::$client protected property The Acquia client.
CredentialForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
CredentialForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
CredentialForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
CredentialForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CredentialForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
CredentialForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
CredentialForm::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
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::$configFactory protected property The config factory. 1
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.
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.
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.