You are here

class OEmbedForm in Media Directories 8

Same name and namespace in other branches
  1. 3.x modules/media_directories_ui/src/Form/OEmbedForm.php \Drupal\media_directories_ui\Form\OEmbedForm
  2. 2.x modules/media_directories_ui/src/Form/OEmbedForm.php \Drupal\media_directories_ui\Form\OEmbedForm

A form to add remote content using OEmbed resources.

Hierarchy

Expanded class hierarchy of OEmbedForm

1 file declares its use of OEmbedForm
media_directories_ui.module in modules/media_directories_ui/media_directories_ui.module
Main module file.

File

modules/media_directories_ui/src/Form/OEmbedForm.php, line 21

Namespace

Drupal\media_directories_ui\Form
View source
class OEmbedForm extends AddMediaFormBase {

  /**
   * The oEmbed URL resolver service.
   *
   * @var \Drupal\media\OEmbed\UrlResolverInterface
   */
  protected $urlResolver;

  /**
   * The oEmbed resource fetcher service.
   *
   * @var \Drupal\media\OEmbed\ResourceFetcherInterface
   */
  protected $resourceFetcher;

  /**
   * Constructs a new OEmbedForm.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Utility\Token $token
   *   The token service.
   * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
   *   The theme manager.
   * @param \Drupal\media\OEmbed\UrlResolverInterface $url_resolver
   *   The oEmbed URL resolver service.
   * @param \Drupal\media\OEmbed\ResourceFetcherInterface $resource_fetcher
   *   The oEmbed resource fetcher service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, AccountProxyInterface $current_user, Token $token, ThemeManagerInterface $theme_manager, UrlResolverInterface $url_resolver, ResourceFetcherInterface $resource_fetcher) {
    parent::__construct($entity_type_manager, $current_user, $token, $theme_manager);
    $this->urlResolver = $url_resolver;
    $this->resourceFetcher = $resource_fetcher;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('current_user'), $container
      ->get('token'), $container
      ->get('theme.manager'), $container
      ->get('media.oembed.url_resolver'), $container
      ->get('media.oembed.resource_fetcher'));
  }

  /**
   * {@inheritdoc}
   */
  protected function getMediaType(FormStateInterface $form_state) {
    $media_type = parent::getMediaType($form_state);
    if (!$media_type
      ->getSource() instanceof OEmbedInterface) {
      throw new \InvalidArgumentException('Can only add media types which use an oEmbed source plugin.');
    }
    return $media_type;
  }

  /**
   * {@inheritdoc}
   */
  protected function buildInputElement(array $form, FormStateInterface $form_state) {
    $form['#attributes']['class'][] = 'media-library-add-form--oembed';
    $media_type = $this
      ->getMediaType($form_state);
    $providers = $media_type
      ->getSource()
      ->getProviders();

    // Add a container to group the input elements for styling purposes.
    $form['container'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'media-library-add-form__input-wrapper',
        ],
      ],
    ];
    $form['container']['url'] = [
      '#type' => 'url',
      '#title' => $this
        ->t('Add @type via URL', [
        '@type' => $this
          ->getMediaType($form_state)
          ->label(),
      ]),
      '#description' => $this
        ->t('Allowed providers: @providers.', [
        '@providers' => implode(', ', $providers),
      ]),
      '#required' => TRUE,
      '#attributes' => [
        'placeholder' => 'https://',
        'class' => [
          'media-library-add-form-oembed-url',
        ],
      ],
    ];
    $form['container']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Add'),
      '#button_type' => 'primary',
      '#validate' => [
        '::validateUrl',
      ],
      '#submit' => [
        '::addButtonSubmit',
      ],
      // @todo Move validation in https://www.drupal.org/node/2988215
      '#ajax' => [
        'callback' => '::updateFormCallback',
        'wrapper' => 'media-library-wrapper',
        // Add a fixed URL to post the form since AJAX forms are automatically
        // posted to <current> instead of $form['#action'].
        // @todo Remove when https://www.drupal.org/project/drupal/issues/2504115
        //   is fixed.
        'url' => Url::fromRoute('media_directories_ui.media.add'),
        'options' => [
          'query' => [
            'media_type' => $form_state
              ->get('media_type') ? $form_state
              ->get('media_type')
              ->id() : $form_state
              ->get('selected_type'),
            FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
          ],
        ],
      ],
      '#attributes' => [
        'class' => [
          'media-library-add-form-oembed-submit',
        ],
      ],
    ];
    return $form;
  }

  /**
   * Validates the oEmbed URL.
   *
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   */
  public function validateUrl(array &$form, FormStateInterface $form_state) {
    $url = $form_state
      ->getValue('url');
    if ($url) {
      try {
        $resource_url = $this->urlResolver
          ->getResourceUrl($url);
        $this->resourceFetcher
          ->fetchResource($resource_url);
      } catch (ResourceException $e) {
        $form_state
          ->setErrorByName('url', $e
          ->getMessage());
      }
    }
  }

  /**
   * Submit handler for the add button.
   *
   * @param array $form
   *   The form render array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function addButtonSubmit(array $form, FormStateInterface $form_state) {
    $this
      ->processInputValues([
      $form_state
        ->getValue('url'),
    ], $form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AddMediaFormBase::$currentUser protected property Current user service.
AddMediaFormBase::$entityTypeManager protected property Entity type manager service.
AddMediaFormBase::$themeManager protected property The theme manager.
AddMediaFormBase::$token protected property The token replacement instance.
AddMediaFormBase::buildActions protected function Returns an array of supported actions for the form. 1
AddMediaFormBase::buildEntityFormElement protected function Builds the sub-form for setting required fields on a new media item. 1
AddMediaFormBase::buildForm public function Form constructor. Overrides FormInterface::buildForm 1
AddMediaFormBase::createFileItem protected function Create a file field item.
AddMediaFormBase::createMediaFromValue protected function Creates a new, unsaved media item from a source field value.
AddMediaFormBase::getCardinality protected function Get the current cardinality from the form state.
AddMediaFormBase::getDirectory protected function Gets the current active directory from the form state.
AddMediaFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 2
AddMediaFormBase::getSelectionMode protected function Get the current selection mode from the form state.
AddMediaFormBase::getSourceFieldName protected function Returns the name of the source field for a media type. 1
AddMediaFormBase::getTargetBundles protected function Get the allowed target bundles from the form state. 1
AddMediaFormBase::getUploadLocation protected function Determines the URI for a file field.
AddMediaFormBase::getUploadValidators protected function Returns the upload validators for a field.
AddMediaFormBase::hideExtraSourceFieldComponents public static function Processes an image or file source field element.
AddMediaFormBase::processInputValues protected function Creates media items from source field input values. 1
AddMediaFormBase::removeButtonSubmit public function Submit handler for the remove button.
AddMediaFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm 1
AddMediaFormBase::updateFormCallback public function AJAX callback to update the entire form based on source field input. 1
AddMediaFormBase::updateLibrary public function AJAX callback to send the new media item(s) to the media library.
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::config protected function Retrieves a configuration object.
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.
OEmbedForm::$resourceFetcher protected property The oEmbed resource fetcher service.
OEmbedForm::$urlResolver protected property The oEmbed URL resolver service.
OEmbedForm::addButtonSubmit public function Submit handler for the add button.
OEmbedForm::buildInputElement protected function Inheriting classes need to build the desired input element. Overrides AddMediaFormBase::buildInputElement
OEmbedForm::create public static function Instantiates a new instance of this class. Overrides AddMediaFormBase::create
OEmbedForm::getMediaType protected function Get the media type from the form state. Overrides AddMediaFormBase::getMediaType
OEmbedForm::validateUrl public function Validates the oEmbed URL.
OEmbedForm::__construct public function Constructs a new OEmbedForm. Overrides AddMediaFormBase::__construct
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.
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.