You are here

class AdminSettingsForm in Acquia Lift Connector 8

Same name and namespace in other branches
  1. 8.4 src/Form/AdminSettingsForm.php \Drupal\acquia_lift\Form\AdminSettingsForm
  2. 8.3 src/Form/AdminSettingsForm.php \Drupal\acquia_lift\Form\AdminSettingsForm

Defines a form that configures settings.

Hierarchy

Expanded class hierarchy of AdminSettingsForm

1 string reference to 'AdminSettingsForm'
acquia_lift.routing.yml in ./acquia_lift.routing.yml
acquia_lift.routing.yml

File

src/Form/AdminSettingsForm.php, line 25
Contains \Drupal\acquia_lift\Form\AdminSettingsForm.

Namespace

Drupal\acquia_lift\Form
View source
class AdminSettingsForm extends ConfigFormBase {

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  private $entityManager;

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

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

  /**
   * Constructs an AdminSettingsForm object.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   */
  public function __construct(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $form['credential'] = $this
      ->buildCredentialForm();

    // Data collection settings.
    $form['data_collection_settings'] = [
      '#type' => 'vertical_tabs',
      '#title' => t('Data collection settings'),
    ];
    $form['identity'] = $this
      ->buildIdentityForm();
    $form['field_mappings'] = $this
      ->buildFieldMappingsForm();
    $form['visibility'] = $this
      ->buildVisibilityForm();
    $form['thumbnail_url'] = $this
      ->buildThumbnailUrlForm();
    return parent::buildForm($form, $form_state);
  }

  /**
   * Build credential form.
   *
   * @return array
   *   Credential form.
   */
  private function buildCredentialForm() {
    $credential_settings = $this
      ->config('acquia_lift.settings')
      ->get('credential');
    $form = [
      '#title' => t('Credential'),
      '#type' => 'details',
      '#tree' => TRUE,
      '#open' => SettingsHelper::isInvalidCredential($credential_settings),
    ];
    $form['account_name'] = [
      '#type' => 'textfield',
      '#title' => t('Account Name'),
      '#default_value' => $credential_settings['account_name'],
      '#required' => TRUE,
    ];
    $form['customer_site'] = [
      '#type' => 'textfield',
      '#title' => t('Customer Site'),
      '#default_value' => $credential_settings['customer_site'],
    ];
    $form['api_url'] = [
      '#type' => 'textfield',
      '#title' => t('API URL'),
      '#field_prefix' => 'http(s)://',
      '#default_value' => $credential_settings['api_url'],
      '#required' => TRUE,
    ];
    $form['access_key'] = [
      '#type' => 'textfield',
      '#title' => t('API Access Key'),
      '#default_value' => $credential_settings['access_key'],
      '#required' => TRUE,
    ];
    $form['secret_key'] = [
      '#type' => 'password',
      '#title' => t('API Secret Key'),
      '#default_value' => $credential_settings['secret_key'],
      '#required' => empty($credential_settings['secret_key']),
      '#description' => !empty($credential_settings['secret_key']) ? t('Only necessary if updating') : '',
    ];
    $form['js_path'] = [
      '#type' => 'textfield',
      '#title' => t('JavaScript Path'),
      '#field_prefix' => 'http(s)://',
      '#default_value' => $credential_settings['js_path'],
      '#required' => TRUE,
    ];
    return $form;
  }

  /**
   * Build identity form.
   *
   * @return array
   *   Identity form.
   */
  private function buildIdentityForm() {
    $identity_settings = $this
      ->config('acquia_lift.settings')
      ->get('identity');
    $form = [
      '#title' => t('Identity'),
      '#type' => 'details',
      '#tree' => TRUE,
      '#group' => 'data_collection_settings',
    ];

    //    $form['capture_identity'] = [
    //      '#type' => 'checkbox',
    //      '#title' => t('Capture identity on login / register'),
    //      '#default_value' => $identity_settings['capture_identity'],
    //    ];
    $form['identity_parameter'] = [
      '#type' => 'textfield',
      '#title' => t('Identity Parameter'),
      '#default_value' => $identity_settings['identity_parameter'],
    ];
    $form['identity_type_parameter'] = [
      '#type' => 'textfield',
      '#title' => t('Identity Type Parameter'),
      '#default_value' => $identity_settings['identity_type_parameter'],
      '#states' => [
        'visible' => [
          ':input[name="identity[identity_parameter]"]' => [
            '!value' => '',
          ],
        ],
      ],
    ];
    $form['default_identity_type'] = [
      '#type' => 'textfield',
      '#title' => t('Default Identity Type'),
      '#default_value' => $identity_settings['default_identity_type'],
      '#placeholder' => SettingsHelper::DEFAULT_IDENTITY_TYPE_DEFAULT,
    ];
    return $form;
  }

  /**
   * Build field mappings form.
   *
   * @return array
   *   Field mappings form.
   */
  private function buildFieldMappingsForm() {
    $field_mappings_settings = $this
      ->config('acquia_lift.settings')
      ->get('field_mappings');
    $field_names = $this
      ->getTaxonomyTermFieldNames();
    $form = [
      '#title' => t('Field Mappings'),
      '#type' => 'details',
      '#tree' => TRUE,
      '#group' => 'data_collection_settings',
    ];
    $form['content_section'] = [
      '#type' => 'select',
      '#title' => t('Content Section'),
      '#empty_value' => '',
      '#options' => $field_names,
      '#default_value' => $field_mappings_settings['content_section'],
    ];
    $form['content_keywords'] = [
      '#type' => 'select',
      '#title' => t('Content Keywords'),
      '#empty_value' => '',
      '#options' => $field_names,
      '#default_value' => $field_mappings_settings['content_keywords'],
    ];
    $form['persona'] = [
      '#type' => 'select',
      '#title' => t('Persona'),
      '#empty_value' => '',
      '#options' => $field_names,
      '#default_value' => $field_mappings_settings['persona'],
    ];
    return $form;
  }

  /**
   * Get a list of Field names that are targeting type Taxonomy Terms.
   *
   * @return array
   *   An array of field names.
   */
  private function getTaxonomyTermFieldNames() {
    $definitions = $this->entityManager
      ->getFieldStorageDefinitions('node');
    $field_names = [];
    foreach ($definitions as $field_name => $field_storage) {
      if ($field_storage
        ->getType() != 'entity_reference' || $field_storage
        ->getSetting('target_type') !== 'taxonomy_term') {
        continue;
      }
      $field_names[$field_name] = $field_name;
    }
    return $field_names;
  }

  /**
   * Build visibility form.
   *
   * @return array
   *   Visibility form.
   */
  private function buildVisibilityForm() {
    $visibility_settings = $this
      ->config('acquia_lift.settings')
      ->get('visibility');
    $form = [
      '#title' => t('Visibility'),
      '#type' => 'details',
      '#tree' => TRUE,
      '#group' => 'data_collection_settings',
    ];
    $form['path_patterns'] = [
      '#type' => 'textarea',
      '#title' => t('Path patterns'),
      '#description' => t('Lift will skip data collection on those URLs and their aliases.'),
      '#default_value' => $visibility_settings['path_patterns'],
    ];
    return $form;
  }

  /**
   * Display thumbnail URL form.
   *
   * @return array
   *   Thumbnail URL form.
   */
  private function buildThumbnailUrlForm() {
    $form = [
      '#title' => t('Thumbnail URL'),
      '#type' => 'details',
      '#tree' => TRUE,
      '#group' => 'data_collection_settings',
    ];
    $form['link_list'] = [
      '#type' => 'markup',
      '#markup' => '<div>' . t('There are no content types. Please create a content type first.') . '</div>',
    ];
    $node_types = NodeType::loadMultiple();
    if (empty($node_types)) {
      return $form;
    }
    $links = [];
    $link_attributes = [
      'attributes' => [
        'target' => '_blank',
      ],
      'fragment' => 'edit-acquia-lift',
    ];
    foreach ($node_types as $node_type) {
      $url = Url::fromRoute('entity.node_type.edit_form', [
        'node_type' => $node_type
          ->id(),
      ], $link_attributes);
      $links[] = '<p>' . Link::fromTextAndUrl($node_type
        ->label(), $url)
        ->toString() . '</p>';
    }
    $form['link_list']['#markup'] = t('Configure thumbnail URLs on each content type\'s edit page (in a new window):');
    $form['link_list']['#markup'] .= implode('', $links);
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $settings = $this
      ->config('acquia_lift.settings');
    $values = $form_state
      ->getValues();
    $this
      ->setCredentialValues($settings, $values['credential']);
    $this
      ->setIdentityValues($settings, $values['identity']);
    $this
      ->setFieldMappingsValues($settings, $values['field_mappings']);
    $this
      ->setVisibilityValues($settings, $values['visibility']);
    $settings
      ->save();
    drupal_flush_all_caches();
    parent::submitForm($form, $form_state);
  }

  /**
   * Set credential values.
   *
   * @param \Drupal\Core\Config\Config $settings
   *   Acquia Lift config settings.
   * @param array $values
   *   Credential values.
   */
  private function setCredentialValues(Config $settings, array $values) {
    $settings
      ->set('credential.account_name', $values['account_name']);
    $settings
      ->set('credential.customer_site', $values['customer_site']);
    $settings
      ->set('credential.api_url', $this
      ->removeProtocal($values['api_url']));
    $settings
      ->set('credential.access_key', $values['access_key']);
    if (!empty($values['secret_key'])) {
      $settings
        ->set('credential.secret_key', $values['secret_key']);
    }
    $settings
      ->set('credential.js_path', $this
      ->removeProtocal($values['js_path']));
  }

  /**
   * Remove the protocal from an URL string.
   *
   * @param string $url
   *   URL.
   *
   * @return string
   *   Same URL as input except with the 'http://' and 'https://' trimmed.
   */
  private function removeProtocal($url) {
    return preg_replace('~^https?://~', '', $url);
  }

  /**
   * Set identity values.
   *
   * @param \Drupal\Core\Config\Config $settings
   *   Acquia Lift config settings.
   * @param array $values
   *   Identity values.
   */
  private function setIdentityValues(Config $settings, array $values) {

    //    $settings->set('identity.capture_identity', $values['capture_identity']);
    $settings
      ->set('identity.identity_parameter', $values['identity_parameter']);
    $settings
      ->set('identity.identity_type_parameter', $values['identity_type_parameter']);
    $settings
      ->set('identity.default_identity_type', $values['default_identity_type']);
  }

  /**
   * Set field mapping values.
   *
   * @param \Drupal\Core\Config\Config $settings
   *   Acquia Lift config settings.
   * @param array $values
   *   Field mappings values.
   */
  private function setFieldMappingsValues(Config $settings, array $values) {
    $settings
      ->set('field_mappings.content_section', $values['content_section']);
    $settings
      ->set('field_mappings.content_keywords', $values['content_keywords']);
    $settings
      ->set('field_mappings.persona', $values['persona']);
  }

  /**
   * Set visibility values.
   *
   * @param \Drupal\Core\Config\Config $settings
   *   Acquia Lift config settings.
   * @param array $values
   *   Visibility values.
   */
  private function setVisibilityValues(Config $settings, array $values) {
    $settings
      ->set('visibility.path_patterns', $values['path_patterns']);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AdminSettingsForm::$entityManager private property The entity manager.
AdminSettingsForm::buildCredentialForm private function Build credential form.
AdminSettingsForm::buildFieldMappingsForm private function Build field mappings form.
AdminSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
AdminSettingsForm::buildIdentityForm private function Build identity form.
AdminSettingsForm::buildThumbnailUrlForm private function Display thumbnail URL form.
AdminSettingsForm::buildVisibilityForm private function Build visibility form.
AdminSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
AdminSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
AdminSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AdminSettingsForm::getTaxonomyTermFieldNames private function Get a list of Field names that are targeting type Taxonomy Terms.
AdminSettingsForm::removeProtocal private function Remove the protocal from an URL string.
AdminSettingsForm::setCredentialValues private function Set credential values.
AdminSettingsForm::setFieldMappingsValues private function Set field mapping values.
AdminSettingsForm::setIdentityValues private function Set identity values.
AdminSettingsForm::setVisibilityValues private function Set visibility values.
AdminSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
AdminSettingsForm::__construct public function Constructs an AdminSettingsForm object. Overrides ConfigFormBase::__construct
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::$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.
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.
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.