You are here

class ZoneSelectionForm in CloudFlare 8

Class ZoneSelectionForm.

@package Drupal\cloudflare\Form

Hierarchy

Expanded class hierarchy of ZoneSelectionForm

File

src/Form/ZoneSelectionForm.php, line 23

Namespace

Drupal\cloudflare\Form
View source
class ZoneSelectionForm extends FormBase implements ContainerInjectionInterface {

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

  /**
   * Wrapper to access the CloudFlare zone api.
   *
   * @var \Drupal\cloudflare\CloudFlareZoneInterface
   */
  protected $zoneApi;

  /**
   * A logger instance for CloudFlare.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * List of the zones for the current Api credentials.
   *
   * @var array
   */
  protected $zones;

  /**
   * Boolean indicates if CloudFlare dependencies have been met.
   *
   * @var bool
   */
  protected $cloudFlareComposerDependenciesMet;

  /**
   * Tracks if the current CloudFlare account has multiple zones.
   *
   * @var bool
   */
  protected $hasMultipleZones;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    // This is a hack because could not get custom ServiceProvider to work.
    // this to work: https://www.drupal.org/node/2026959
    $has_zone_mock = $container
      ->has('cloudflare.zonemock');
    return new static($container
      ->get('config.factory'), $has_zone_mock ? $container
      ->get('cloudflare.zonemock') : $container
      ->get('cloudflare.zone'), $container
      ->get('logger.factory')
      ->get('cloudflare'), $container
      ->get('cloudflare.composer_dependency_check')
      ->check());
  }

  /**
   * Constructs a new ZoneSelectionForm.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\cloudflare\CloudFlareZoneInterface $zone_api
   *   ZoneApi instance for accessing api.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param bool $composer_dependencies_met
   *   Checks that the composer dependencies for CloudFlare are met.
   */
  public function __construct(ConfigFactoryInterface $config_factory, CloudFlareZoneInterface $zone_api, LoggerInterface $logger, $composer_dependencies_met) {
    $this->configFactory = $config_factory;
    $this->config = $config_factory
      ->getEditable('cloudflare.settings');
    $this->zoneApi = $zone_api;
    $this->logger = $logger;
    $this->cloudFlareComposerDependenciesMet = $composer_dependencies_met;
    $this->hasZoneId = !empty($this->config
      ->get('zone_id'));
    $this->hasValidCredentials = $this->config
      ->get('valid_credentials') === TRUE;

    // This test should be unnecessary since this form should only ever be
    // reached when the 2 conditions are met. It's being done from an abundance
    // of caution.
    if ($this->hasValidCredentials && $this->cloudFlareComposerDependenciesMet) {
      try {
        $this->zones = $this->zoneApi
          ->listZones();
        $this->hasMultipleZones = count($this->zones) > 1;
      } catch (CloudFlareTimeoutException $e) {
        $this
          ->messenger()
          ->addError($this
          ->t('Unable to connect to CloudFlare. You will not be able to change the selected Zone.'));
      }
    }
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    return $this
      ->buildZoneSelectSection();
  }

  /**
   * Builds zone selection section for inclusion in the settings form.
   *
   * @return array
   *   Form Api render array with selection section.
   */
  protected function buildZoneSelectSection() {
    $section = [];
    $section['zone_selection_fieldset'] = [
      '#type' => 'fieldset',
      '#weight' => 0,
    ];
    if (!$this->hasMultipleZones && $this->hasValidCredentials) {

      // It is possible to authenticate with the API without having configured a
      // domain in the CloudFlare console. This prevents a fatal error where
      // zones[0]->getZoneId() is called on a NULL reference.
      if (empty($this->zones)) {
        $add_site_link = Link::fromTextAndUrl($this
          ->t('add a site'), Url::fromUri('https://www.cloudflare.com/a/setup'));
        $section['zone_selection_fieldset']['zone_selection'] = [
          '#markup' => $this
            ->t('<p>Your CloudFlare account does not have any zones configured. Verify your API details or !add_site_link via the console.</p>', [
            '!add_site_link' => $add_site_link
              ->toString(),
          ]),
        ];
        return $section;
      }
      $zone_id = $this->zones[0]
        ->getZoneId();
      $this->config
        ->set('zone_id', $zone_id)
        ->save();
      $section['zone_selection_fieldset']['zone_selection'] = [
        '#markup' => $this
          ->t('<p>Your CloudFlare account has a single zone which has been automatically selected for you.  Simply click "Finish" to save your settings.</p>'),
      ];
      return $section;
    }
    $listing = $this
      ->buildZoneListing();
    $section['zone_selection_fieldset']['zone_selection'] = $listing;
    return $section;
  }

  /**
   * Builds a form render array for zone selection.
   *
   * @return array
   *   Form Api Render array for zone select.
   */
  public function buildZoneListing() {
    $form_select_field = [];
    $zone_select = [];
    foreach ($this->zones as $zone) {
      $zone_select[$zone
        ->getZoneId()] = $zone
        ->getName();
    }
    $form_select_field = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Zone'),
      '#disabled' => FALSE,
      '#options' => $zone_select,
      '#description' => $this
        ->t('Use the autocomplete to select your zone (top level domain for the site). The zone ID corresponding to the domain will then be saved in the field.'),
      '#default_value' => $this->config
        ->get('zone_id'),
      '#empty_option' => '- None -',
      '#empty_value' => '0',
      '#autocomplete_route_name' => 'cloudflare.zone_autocomplete',
    ];
    return $form_select_field;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($this->hasMultipleZones) {
      $zone_id = $form_state
        ->getValue('zone_selection');
      $this->config
        ->set('zone_id', $zone_id)
        ->save();
    }
    $form_state
      ->setRedirect('cloudflare.admin_settings_form');
  }

  /**
   * Retrieves suggestions for zone autocompletion.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response containing autocomplete suggestions.
   */
  public function autocompleteZone(Request $request) {
    $zone_autocomplete_text = $request->query
      ->get('q');
    $matches = [];

    // Tracks if the current CloudFlare account has multiple zones.

    /** @var \CloudFlarePhpSdk\ApiTypes\Zone\Zone $zone */
    foreach ($this->zoneApi
      ->listZones() as $zone) {
      if (stripos($zone
        ->getName(), $zone_autocomplete_text) === 0) {
        $matches[] = [
          'value' => $zone
            ->getZoneId(),
          'label' => $zone
            ->getName(),
        ];
      }
    }
    return new JsonResponse($matches);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::config protected function Retrieves a configuration object.
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.
ZoneSelectionForm::$cloudFlareComposerDependenciesMet protected property Boolean indicates if CloudFlare dependencies have been met.
ZoneSelectionForm::$configFactory protected property The configuration factory. Overrides FormBase::$configFactory
ZoneSelectionForm::$hasMultipleZones protected property Tracks if the current CloudFlare account has multiple zones.
ZoneSelectionForm::$logger protected property A logger instance for CloudFlare.
ZoneSelectionForm::$zoneApi protected property Wrapper to access the CloudFlare zone api.
ZoneSelectionForm::$zones protected property List of the zones for the current Api credentials.
ZoneSelectionForm::autocompleteZone public function Retrieves suggestions for zone autocompletion.
ZoneSelectionForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ZoneSelectionForm::buildZoneListing public function Builds a form render array for zone selection.
ZoneSelectionForm::buildZoneSelectSection protected function Builds zone selection section for inclusion in the settings form.
ZoneSelectionForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ZoneSelectionForm::getEditableConfigNames protected function
ZoneSelectionForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ZoneSelectionForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ZoneSelectionForm::__construct public function Constructs a new ZoneSelectionForm.