You are here

public function CropWidgetForm::validateForm in Image Widget Crop 8.2

Same name and namespace in other branches
  1. 8 src/Form/CropWidgetForm.php \Drupal\image_widget_crop\Form\CropWidgetForm::validateForm()

Validation for cropper library.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Throws

\GuzzleHttp\Exception\GuzzleException

Overrides FormBase::validateForm

File

src/Form/CropWidgetForm.php, line 225

Class

CropWidgetForm
Configure ImageWidgetCrop general settings for this site.

Namespace

Drupal\image_widget_crop\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  if (!empty($form_state
    ->getValue('library_url')) || !empty($form_state
    ->getValue('css_url'))) {
    $files = [
      'library' => $form_state
        ->getValue('library_url'),
      'css' => $form_state
        ->getValue('css_url'),
    ];
    if (empty($files['library']) || empty($files['css'])) {
      $form_state
        ->setErrorByName('plugin', $this
        ->t('Please provide both a library and a CSS file when using custom URLs.'));
    }
    else {
      foreach ($files as $type => $file) {

        // Verify that both files exist.
        $is_local = parse_url($file, PHP_URL_SCHEME) === NULL && strpos($file, '//') !== 0;
        if ($is_local && !file_exists($file)) {
          $form_state
            ->setErrorByName($type . '_url', $this
            ->t('The provided local file does not exist.'));
        }
        elseif (!$is_local) {
          try {
            $result = $this->httpClient
              ->request('GET', $file);
            if ($result
              ->getStatusCode() != 200) {
              throw new \Exception($result
                ->getReasonPhrase(), 1);
            }
          } catch (\Exception $e) {
            $form_state
              ->setErrorByName($type . '_url', $this
              ->t('The remote URL for the library does not appear to be valid: @message.', [
              '@message' => $e
                ->getMessage(),
            ]));
          }
        }
      }
    }
  }
}