You are here

class SettingsForm in Instagram Feeds 8

Defines an Instagram Feeds configuration form.

Hierarchy

Expanded class hierarchy of SettingsForm

1 string reference to 'SettingsForm'
instagram_feeds.routing.yml in ./instagram_feeds.routing.yml
instagram_feeds.routing.yml

File

src/Form/SettingsForm.php, line 12

Namespace

Drupal\instagram_feeds\Form
View source
class SettingsForm extends ConfigFormBase {
  const SETTINGS = 'instagram_feeds.settings';

  /**
   * Token descriptions.
   *
   * @var array
   */
  private $tokenDescription;

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      self::SETTINGS,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config(self::SETTINGS);
    $base_field = [
      '#type' => 'textfield',
      '#required' => TRUE,
    ];
    $form['client_id'] = [
      '#title' => $this
        ->t('Instagram App (Client) ID'),
      '#default_value' => $config
        ->get('client_id'),
    ] + $base_field;
    $form['client_secret'] = [
      '#title' => $this
        ->t('Instagram App (Client) Secret'),
      '#default_value' => $config
        ->get('client_secret'),
      '#description' => $this
        ->t('You may want to setup this via settings.php, that\'s why it is not required here.'),
      '#required' => FALSE,
    ] + $base_field;
    $form['refresh_frequency'] = [
      '#type' => 'select',
      '#options' => $this
        ->getRefreshFrequencyOptions(),
      '#title' => $this
        ->t('Long-Lived Token Refresh Frequency'),
      '#description' => $this
        ->t('The long-lived token is valid only 60 days. After it was expired it is no longer possible to refresh it. Also it cannot be refreshed more often than once per 24 hours.'),
      '#field_prefix' => $this
        ->t('Refresh every'),
      '#field_suffix' => $this
        ->t('by Cron'),
      '#default_value' => $config
        ->get('refresh_frequency'),
    ];
    $scheme_options = \Drupal::service('stream_wrapper_manager')
      ->getNames(StreamWrapperInterface::WRITE_VISIBLE);
    $form['avatar_uri_scheme'] = [
      '#type' => 'radios',
      '#title' => t('Avatar upload destination'),
      '#options' => $scheme_options,
      '#default_value' => $config
        ->get('avatar_uri_scheme'),
      '#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
    ] + $base_field;
    $form['avatar_directory'] = [
      '#title' => $this
        ->t('Avatar directory'),
      '#description' => $this
        ->t('Where to store avatars, for example: "instagram_avatars".'),
      '#default_value' => $config
        ->get('avatar_directory'),
      '#element_validate' => [
        '\\Drupal\\file\\Plugin\\Field\\FieldType\\FileItem::validateDirectory',
      ],
    ] + $base_field + $this
      ->getTokenDescription();
    $form['mapping'] = $this
      ->buildMappingForm($form, $form_state, 'mapping');
    return parent::buildForm($form, $form_state);
  }

  /**
   * Form builder for mapping between media entity and Instagram post.
   *
   * @param array $form
   *   Form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state object.
   * @param string $field_name
   *   Parent field name to build the form tree.
   *
   * @return array
   *   Fields mapping form element array.
   */
  protected function buildMappingForm(array $form, FormStateInterface $form_state, $field_name) : array {
    $config = $this
      ->config(self::SETTINGS);
    $element = [
      '#title' => $this
        ->t('Fields Mapping'),
      '#type' => 'details',
      '#description' => $this
        ->t('Fields mapping between supported Media types and data from Instagram API.'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];
    $media_types = $this
      ->getInstagramMediaTypes();

    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager */
    $entity_field_manager = \Drupal::service('entity_field.manager');

    /** @var \Drupal\media\MediaTypeInterface $media_type */
    foreach ($media_types as $media_type_id => $media_type) {
      $element[$media_type_id] = [
        '#type' => 'details',
        '#title' => $media_type
          ->label(),
        '#open' => count($media_types) === 1,
        '#tree' => TRUE,
      ];
      $source_field_name = $media_type
        ->getSource()
        ->getSourceFieldDefinition($media_type)
        ->getName();
      $source_plugin = $media_type
        ->getSource()
        ->getPluginId();
      foreach ($entity_field_manager
        ->getFieldDefinitions('media', $media_type_id) as $field_definition) {
        if ($field_definition
          ->getName() == $source_field_name) {
          switch ($source_plugin) {
            case 'image':
              $element[$media_type_id][$field_definition
                ->getName()] = [
                '#type' => 'item',
                '#field_prefix' => $field_definition
                  ->getLabel() . ': ',
                '#parents' => [],
                '#field_suffix' => $this
                  ->getInstagramApiFields()['image'],
              ];
              break;
            case 'instagram':
              $element[$media_type_id][$field_definition
                ->getName()] = [
                '#type' => 'item',
                '#field_prefix' => $field_definition
                  ->getLabel() . ': ',
                '#parents' => [],
                '#field_suffix' => $this
                  ->getInstagramApiFields()['permalink'],
              ];
              break;
          }
        }
        elseif ($this
          ->isMappableFeild($field_definition)) {
          $element[$media_type_id][$field_definition
            ->getName()] = [
            '#type' => 'select',
            '#options' => $this
              ->getInstagramApiFields($field_definition
              ->getType()),
            '#empty_option' => $this
              ->t('- Skip -'),
            '#field_prefix' => $field_definition
              ->getLabel(),
            '#default_value' => $config
              ->get('mapping.' . $media_type_id . '.' . $field_definition
              ->getName()),
          ];
        }
        elseif ($field_definition
          ->getName() == 'name') {
          $element[$media_type_id]['name'] = [
            '#type' => 'textfield',
            '#field_prefix' => $this
              ->t('Media entity name'),
            '#required' => TRUE,
            '#default_value' => $config
              ->get('mapping.' . $media_type_id . '.name'),
          ] + $this
            ->getTokenDescription();
        }
      }
    }
    return $element;
  }

  /**
   * Returns form element array with token suggestions.
   *
   * @param array $types
   *   The list of allowed token types. If empty, all global types will
   *   be allowed.
   *
   * @return array
   *   Array to join with element with tokens support.
   */
  public function getTokenDescription(array $types = [
    'site',
    'random',
    'current-date',
    'current-user',
    'instagram-account',
    'instagram-post',
  ]) {
    sort($types);
    $key = md5(serialize($types));
    if (!isset($this->tokenDescription[$key])) {
      $this
        ->setTokenDescription($types);
    }
    return $this->tokenDescription[$key];
  }

  /**
   * Creates element array keys with token suggestions.
   *
   * @param array $types
   *   The list of allowed token types. If empty, all global types will
   *   be allowed.
   *
   * @return $this
   */
  protected function setTokenDescription(array $types = []) {
    sort($types);
    $key = md5(serialize($types));
    $this->tokenDescription[$key] = [];
    if (\Drupal::moduleHandler()
      ->moduleExists('token')) {
      $token_tree = [
        '#theme' => 'token_tree_link',
        '#token_types' => $types,
        '#global_types' => count($types) ? FALSE : TRUE,
        '#click_insert' => TRUE,
      ];
      $this->tokenDescription[$key] = [
        '#field_suffix' => $this
          ->t('This field supports tokens. @browse_tokens_link', [
          '@browse_tokens_link' => \Drupal::service('renderer')
            ->render($token_tree),
        ]),
        '#element_validate' => [
          'token_element_validate',
        ],
        '#token_types' => $types,
      ];
    }
    return $this;
  }

  /**
   * Checks if media entity field can be mapped with Instagram data.
   *
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   Media entity field definition.
   *
   * @return bool
   *   TRUE if field can be mapped with Instagram data, FALSE otherwise.
   */
  protected function isMappableFeild($field_definition) : bool {
    if ($field_definition
      ->isInternal() || $field_definition
      ->isReadOnly() || !$field_definition
      ->isDisplayConfigurable('view')) {
      return FALSE;
    }
    $prohibited_types = [
      'boolean',
      'changed',
      'language',
    ];
    if (in_array($field_definition
      ->getType(), $prohibited_types)) {
      return FALSE;
    }
    if ('entity_reference' == $field_definition
      ->getType() && 'taxonomy_term' != $field_definition
      ->getSetting('target_type')) {
      return FALSE;
    }
    if (in_array($field_definition
      ->getName(), [
      'name',
      'created',
    ])) {
      return FALSE;
    }
    return TRUE;
  }

  /**
   * Gets all available for import Instagram post fields.
   *
   * @param string $field_type
   *   Optional field type to return only supported Instagram fields for.
   *
   * @return array
   *   The select field options list.
   */
  protected function getInstagramApiFields($field_type = '') : array {
    $options = [
      'id' => $this
        ->t('Post ID'),
      'caption' => $this
        ->t('Caption'),
      'username' => $this
        ->t('Owner username'),
      'media_type' => $this
        ->t('Media type (image, video or gallery)'),
      'media_url' => $this
        ->t('Media URL'),
      'permalink' => $this
        ->t('Permalink'),
      'image' => $this
        ->t('Image'),
      'thumbnail_url' => $this
        ->t('Thumbnail URL'),
      'timestamp' => $this
        ->t('UNIX timestamp'),
      'date' => $this
        ->t('Date'),
      'full_name' => $this
        ->t('Owner full name'),
      'avatar' => $this
        ->t('Avatar'),
      'tags' => $this
        ->t('Hash tags'),
    ];
    $strings = [
      'id',
      'username',
      'media_type',
      'media_url',
      'permalink',
      'thumbnail_url',
      'full_name',
      'tags',
    ];
    switch ($field_type) {
      case 'image':
        return array_intersect_key($options, array_fill_keys([
          'avatar',
        ], '1'));
      case 'string':
        return array_intersect_key($options, array_fill_keys($strings, '1'));
      case 'string_long':
        return array_intersect_key($options, array_fill_keys([
          'caption',
        ] + $strings, '1'));
      case 'timestamp':
        return array_intersect_key($options, array_fill_keys([
          'timestamp',
        ], '1'));
      case 'datetime':
        return array_intersect_key($options, array_fill_keys([
          'date',
        ], '1'));
      case 'entity_reference':
        return array_intersect_key($options, array_fill_keys([
          'tags',
        ], '1'));
      case 'ingeger':
        return array_intersect_key($options, array_fill_keys([
          'id',
        ], '1'));
      default:
        return $options;
    }
  }

  /**
   * Gets Media types with Instagram source.
   *
   * @return \Drupal\media\MediaTypeInterface[]
   *   Media Types options for Select form element.
   */
  protected function getInstagramMediaTypes() : array {
    $options = [];
    $media_types = \Drupal::entityTypeManager()
      ->getStorage('media_type')
      ->loadMultiple();
    foreach ($media_types as $media_type) {

      /** @var \Drupal\media\MediaTypeInterface $media_type */
      if (in_array($media_type
        ->getSource()
        ->getPluginId(), [
        'instagram',
        'image',
      ])) {
        $options[$media_type
          ->id()] = $media_type;
      }
    }
    return $options;
  }

  /**
   * Get options for the Long-Lived Token Refresh Frequency field.
   *
   * @return array
   *   The list of time intervals where keys are time in seconds.
   */
  protected function getRefreshFrequencyOptions() {
    $days = [
      2,
      5,
      7,
      10,
      14,
      30,
      45,
      59,
    ];

    /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
    $date_formatter = \Drupal::service('date.formatter');
    $period = array_map(function ($val) {
      return $val * 86400;
    }, $days);
    return array_map([
      $date_formatter,
      'formatInterval',
    ], array_combine($period, $period));
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state
      ->cleanValues();
    $this
      ->config(self::SETTINGS)
      ->setData(array_filter($form_state
      ->getValues()))
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
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.
SettingsForm::$tokenDescription private property Token descriptions.
SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SettingsForm::buildMappingForm protected function Form builder for mapping between media entity and Instagram post.
SettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SettingsForm::getInstagramApiFields protected function Gets all available for import Instagram post fields.
SettingsForm::getInstagramMediaTypes protected function Gets Media types with Instagram source.
SettingsForm::getRefreshFrequencyOptions protected function Get options for the Long-Lived Token Refresh Frequency field.
SettingsForm::getTokenDescription public function Returns form element array with token suggestions.
SettingsForm::isMappableFeild protected function Checks if media entity field can be mapped with Instagram data.
SettingsForm::SETTINGS constant
SettingsForm::setTokenDescription protected function Creates element array keys with token suggestions.
SettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
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.