You are here

public function PoolForm::validateForm in CMS Content Sync 8

Same name and namespace in other branches
  1. 2.1.x src/Form/PoolForm.php \Drupal\cms_content_sync\Form\PoolForm::validateForm()
  2. 2.0.x src/Form/PoolForm.php \Drupal\cms_content_sync\Form\PoolForm::validateForm()

Validate format of input fields and make sure the Sync Core backend is accessible to actually update it.

Overrides FormBase::validateForm

File

src/Form/PoolForm.php, line 196

Class

PoolForm
Form handler for the Pool add and edit forms.

Namespace

Drupal\cms_content_sync\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  $step = $this
    ->getLastFormStep($form_state);
  $url = $form_state
    ->getValue('backend_url');
  $client = SyncCoreFactory::getSyncCore($url);
  $allowed_length = 0;
  try {
    $client
      ->getReportingService()
      ->getStatus();

    // In MongoDB (used by the Sync Core, the name of the database + collection name mustn't be longer than 120 characters)
    $longest_entity_name = 0;
    $bundleInfoService = \Drupal::service('entity_type.bundle.info');
    $entity_types = $bundleInfoService
      ->getAllBundleInfo();
    foreach ($entity_types as $type_key => $entity_type) {
      foreach ($entity_type as $entity_bundle_name => $entity_bundle) {
        $length = strlen($type_key) + strlen($entity_bundle_name) + 1;
        if ($length > $longest_entity_name) {
          $longest_entity_name = $length;
        }
      }
    }
    $allowed_length = 120 - 7;

    // Full name is formatted like this: [database].drupal-[pool]-[site]-[entity]-[bundle].
    $allowed_length = $allowed_length - 6 - 1 - 1 - 1 - $longest_entity_name - 1;
  } catch (SyncCoreException $e) {
    $form_state
      ->setErrorByName('backend_url', $this
      ->t('The Sync Core is not accessible (did not respond with 200 OK). Please configure your outbound traffic to allow traffic to the Sync Core. The error message is @message', [
      '@message' => $e
        ->getMessage(),
    ]));
  }
  if (self::STEP_POOL === $step) {
    $api = $form_state
      ->getValue('id');
    if (!preg_match('@^([a-z0-9\\-_]+)$@', $api)) {
      $form_state
        ->setErrorByName('id', $this
        ->t('Please only use letters, numbers and dashes.'));
    }
    if ('drupal' == $api || 'api-unify' == $api) {
      $form_state
        ->setErrorByName('api', $this
        ->t('This name is reserved.'));
    }
    $site_id = $form_state
      ->getValue('site_id');
    $length = strlen($api) + strlen($site_id);
    if ($length > $allowed_length) {
      $form_state
        ->setErrorByName('id', $this
        ->t('The Pool machine name + site id combined mustn\'t be longer than @allowed characters.', [
        '@allowed' => $allowed_length,
      ]));
    }
  }
}