sirv-8.x-3.0-beta4/src/Form/SirvSettingsForm.php
src/Form/SirvSettingsForm.php
<?php
namespace Drupal\sirv\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Defines a form to enter Sirv settings.
*/
class SirvSettingsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'sirv_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'sirv.settings',
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
$config = $this->config('sirv.settings');
$form['domain'] = [
'#type' => 'textfield',
'#title' => $this->t('Domain'),
'#description' => $this->t('The domain used to serve images from Sirv. (Example: example.com)'),
'#default_value' => $config->get('domain'),
'#required' => TRUE,
'#field_prefix' => 'https://',
];
$form['directory'] = [
'#type' => 'textfield',
'#title' => $this->t('Directory'),
'#description' => $this->t("An optional path to a subdirectory within your Sirv account where files will be stored. Do not include leading or trailing slashes. This feature is incompatible with Sirv's auto-fetch functionality."),
'#default_value' => $config->get('directory'),
];
$form['strip_base_path'] = [
'#type' => 'checkbox',
'#title' => $this->t('Strip base path'),
'#description' => $this->t('If selected, the path to an image will be shortened by stripping the stream wrapper’s base path. For example, for the “public” stream wrapper, if the actual path to the file on the site’s server were %path_actual, the path used for the Sirv URL would be %path_shortened.', [
'%path_actual' => 'sites/default/files/images/image.jpg',
'%path_shortened' => 'images/image.jpg',
]),
'#default_value' => $config->get('strip_base_path') ?? TRUE,
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Ensure that a valid domain was entered.
$domain = $form_state->getValue(['domain']);
if ($domain !== parse_url('https://' . $domain, PHP_URL_HOST)) {
$form_state->setErrorByName('domain', $this->t('Enter a valid domain.'));
}
// Ensure that a valid directory path was entered.
$directory = $form_state->getValue(['directory']);
if (!empty($directory) && '/' . $directory !== parse_url('https://example.com/' . $directory, PHP_URL_PATH)) {
$form_state->setErrorByName('directory', $this->t('Enter a valid directory path.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$this->config('sirv.settings')
->set('domain', $values['domain'])
->set('directory', trim($values['directory'], "/ \t\n\r\0\x0B"))
->set('strip_base_path', $values['strip_base_path'])
->save();
parent::submitForm($form, $form_state);
}
}
