You are here

class Settings in Instagram API 8

Implements the Instagram api Settings form.

Hierarchy

Expanded class hierarchy of Settings

See also

\Drupal\Core\Form\FormBase

1 string reference to 'Settings'
instagram_api.routing.yml in ./instagram_api.routing.yml
instagram_api.routing.yml

File

src/Form/Settings.php, line 18

Namespace

Drupal\instagram_api\Form
View source
class Settings extends ConfigFormBase {

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * Settings constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config Factory.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   Date Formatter.
   */
  public function __construct(ConfigFactoryInterface $config_factory, DateFormatterInterface $date_formatter) {
    parent::__construct($config_factory);
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('date.formatter'));
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('instagram_api.settings');
    $form['client'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Client Settings'),
    ];
    $form['client']['help'] = [
      '#type' => '#markup',
      '#markup' => $this
        ->t('To get your Client ID, you need to register your application on @link.', [
        '@link' => Link::fromTextAndUrl('https://www.instagram.com/developer/clients/manage/', Url::fromUri('https://www.instagram.com/developer/clients/manage/'))
          ->toString(),
      ]),
    ];
    $form['client']['client_id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Client ID'),
      '#default_value' => $config
        ->get('client_id'),
    ];
    $form['client']['client_secret'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Client Secret'),
      '#default_value' => $config
        ->get('client_secret'),
    ];
    if ($config
      ->get('client_id') != '' && $config
      ->get('client_secret') != '') {
      $options = [
        'attributes' => [
          'target' => '_blank',
        ],
      ];
      $form['client']['access_token'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Access Token'),
        '#default_value' => $config
          ->get('access_token'),
        '#description' => $this
          ->t('To get your Access Token, @link.', [
          '@link' => Link::fromTextAndUrl('click here', Url::fromUri($this
            ->accessUrl(), $options))
            ->toString(),
        ]),
      ];
    }
    $form['caching'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Instagram API Caching'),
      '#open' => TRUE,
      '#description' => $this
        ->t('API caching is recommended for all websites.'),
    ];

    // Identical options to the ones for block caching.
    // @see \Drupal\Core\Block\BlockBase::buildConfigurationForm()
    $period = [
      0,
      60,
      180,
      300,
      600,
      900,
      1800,
      2700,
      3600,
      10800,
      21600,
      32400,
      43200,
      86400,
    ];
    $period = array_map([
      $this->dateFormatter,
      'formatInterval',
    ], array_combine($period, $period));
    $period[0] = '<' . $this
      ->t('no caching') . '>';
    $form['caching']['api_cache_maximum_age'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('API cache maximum age'),
      '#default_value' => $config
        ->get('api_cache_maximum_age'),
      '#options' => $period,
      '#description' => $this
        ->t('The maximum time a API request can be cached by Drupal.'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->config('instagram_api.settings')
      ->set('client_id', $form_state
      ->getValue('client_id'))
      ->set('client_secret', $form_state
      ->getValue('client_secret'))
      ->set('access_token', $form_state
      ->getValue('access_token'))
      ->set('api_cache_maximum_age', $form_state
      ->getValue('api_cache_maximum_age'))
      ->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * Generate the Access Url.
   *
   * @return string
   *   URL.
   */
  private function accessUrl() {
    $config = $this
      ->config('instagram_api.settings');
    $redirectUrl = Url::fromUri('internal:/instagram_api/callback', [
      'absolute' => TRUE,
    ])
      ->toString();
    $urlBase = $config
      ->get('api_uri') . 'authorize';
    $query = [
      'client_id' => $config
        ->get('client_id'),
      'response_type' => 'code',
      'redirect_uri' => $redirectUrl,
    ];
    $url = Url::fromUri($urlBase, [
      'query' => $query,
      'absolute' => TRUE,
    ])
      ->toString();
    return $url;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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.
Settings::$dateFormatter protected property The date formatter service.
Settings::accessUrl private function Generate the Access Url.
Settings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
Settings::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
Settings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
Settings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
Settings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
Settings::__construct public function Settings constructor. Overrides ConfigFormBase::__construct
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.