Unverified Commit 305c1074 authored by Alex Pott's avatar Alex Pott
Browse files

task: #3568124 Deprecate remaining functions in media.module

By: nicxvan
By: claudiu.cristea
By: longwave
parent 23ddf6a9
Loading
Loading
Loading
Loading
+15 −113
Changes for core/modules/media/media.module: 15 added lines, 113 removed lines.
Original line number Diff line number Diff line
@@ -6,6 +6,7 @@

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\media\Hook\MediaHooks;

/**
 * Returns the appropriate URL to add media for the current user.
@@ -20,8 +21,14 @@
 *
 * @internal
 *   This function is internal and may be removed in a minor release.
 *
 * @deprecated in drupal:11.4.0 and is removed from drupal:12.0.0. There is no
 *   replacement.
 *
 * @see https://www.drupal.org/node/3566774
 */
function _media_get_add_url($allowed_bundles) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:11.4.0 and is removed from drupal:12.0.0. There is no replacement. See https://www.drupal.org/node/3566774', E_USER_DEPRECATED);
  $access_handler = \Drupal::entityTypeManager()->getAccessControlHandler('media');
  $create_bundles = array_filter($allowed_bundles, [$access_handler, 'createAccess']);

@@ -38,119 +45,14 @@ function _media_get_add_url($allowed_bundles) {

/**
 * Validate callback to ensure filter order and allowed_html are compatible.
 *
 * @deprecated in drupal:11.4.0 and is removed from drupal:12.0.0. Use
 *   MediaHooks::formatEditFormValidate() instead.
 *
 * @see https://www.drupal.org/node/3566774
 * @see \Drupal\media\Hook\MediaHooks::formatEditFormValidate()
 */
function media_filter_format_edit_form_validate($form, FormStateInterface $form_state): void {
  if ($form_state->getTriggeringElement()['#name'] !== 'op') {
    return;
  }

  $allowed_html_path = [
    'filters',
    'filter_html',
    'settings',
    'allowed_html',
  ];

  $filter_html_settings_path = [
    'filters',
    'filter_html',
    'settings',
  ];

  $filter_html_enabled = $form_state->getValue([
    'filters',
    'filter_html',
    'status',
  ]);

  $media_embed_enabled = $form_state->getValue([
    'filters',
    'media_embed',
    'status',
  ]);

  if (!$media_embed_enabled) {
    return;
  }

  $get_filter_label = function ($filter_plugin_id) use ($form) {
    return (string) $form['filters']['order'][$filter_plugin_id]['filter']['#markup'];
  };

  if ($filter_html_enabled && $form_state->getValue($allowed_html_path)) {
    /** @var \Drupal\filter\Entity\FilterFormat $filter_format */
    $filter_format = $form_state->getFormObject()->getEntity();

    $filter_html = clone $filter_format->filters()->get('filter_html');
    $filter_html->setConfiguration(['settings' => $form_state->getValue($filter_html_settings_path)]);
    $restrictions = $filter_html->getHTMLRestrictions();
    $allowed = $restrictions['allowed'];

    // Require `<drupal-media>` HTML tag if filter_html is enabled.
    if (!isset($allowed['drupal-media'])) {
      $form_state->setError($form['filters']['settings']['filter_html']['allowed_html'], t('The %media-embed-filter-label filter requires <code>&lt;drupal-media&gt;</code> among the allowed HTML tags.', [
        '%media-embed-filter-label' => $get_filter_label('media_embed'),
      ]));
    }
    else {
      $required_attributes = [
        'data-entity-type',
        'data-entity-uuid',
      ];

      // If there are no attributes, the allowed item is set to FALSE,
      // otherwise, it is set to an array.
      if ($allowed['drupal-media'] === FALSE) {
        $missing_attributes = $required_attributes;
      }
      else {
        $missing_attributes = array_diff($required_attributes, array_keys($allowed['drupal-media']));
      }

      if ($missing_attributes) {
        $form_state->setError($form['filters']['settings']['filter_html']['allowed_html'], t('The <code>&lt;drupal-media&gt;</code> tag in the allowed HTML tags is missing the following attributes: <code>%list</code>.', [
          '%list' => implode(', ', $missing_attributes),
        ]));
      }
    }
  }

  $filters = $form_state->getValue('filters');

  // The "media_embed" filter must run after "filter_align", "filter_caption",
  // and "filter_html_image_secure".
  $precedents = [
    'filter_align',
    'filter_caption',
    'filter_html_image_secure',
  ];

  $error_filters = [];
  foreach ($precedents as $filter_name) {
    // A filter that should run before media embed filter.
    $precedent = $filters[$filter_name];

    if (empty($precedent['status']) || !isset($precedent['weight'])) {
      continue;
    }

    if ($precedent['weight'] >= $filters['media_embed']['weight']) {
      $error_filters[$filter_name] = $get_filter_label($filter_name);
    }
  }

  if (!empty($error_filters)) {
    $error_message = \Drupal::translation()->formatPlural(
      count($error_filters),
      'The %media-embed-filter-label filter needs to be placed after the %filter filter.',
      'The %media-embed-filter-label filter needs to be placed after the following filters: %filters.',
      [
        '%media-embed-filter-label' => $get_filter_label('media_embed'),
        '%filter' => reset($error_filters),
        '%filters' => implode(', ', $error_filters),
      ]
    );

    $form_state->setErrorByName('filters', $error_message);
  }
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:11.4.0 and is removed from drupal:12.0.0. Use \Drupal\media\Hook\MediaHooks::formatEditFormValidate() instead. See https://www.drupal.org/node/3566774', E_USER_DEPRECATED);
  \Drupal::service(MediaHooks::class)->formatEditFormValidate($form, $form_state);
}
+151 −3
Changes for core/modules/media/src/Hook/MediaHooks.php: 151 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -174,7 +174,7 @@ public function fieldWidgetCompleteFormAlter(array &$field_widget_complete_form,
    // which bundles are available to be created or referenced.
    $settings = $context['items']->getFieldDefinition()->getSetting('handler_settings');
    $allowed_bundles = !empty($settings['target_bundles']) ? $settings['target_bundles'] : [];
    $add_url = _media_get_add_url($allowed_bundles);
    $add_url = $this->addUrl($allowed_bundles);
    if ($add_url) {
      $elements['#media_help']['#media_add_help'] = $this->t('Create your media on the <a href=":add_page" target="_blank">media add page</a> (opens a new window), then add it by name to the field below.', [':add_page' => $add_url]);
    }
@@ -238,7 +238,7 @@ public function formFilterFormatEditFormAlter(array &$form, FormStateInterface $
    // are added automatically by CKEditor 5. The validator would conflict with
    // the automatic addition of those allowed tags.
    if ($form_state->getValue('editor') !== 'ckeditor5') {
      $form['#validate'][] = 'media_filter_format_edit_form_validate';
      $form['#validate'][] = self::class . ':formatEditFormValidate';
    }
  }

@@ -252,7 +252,7 @@ public function formFilterFormatAddFormAlter(array &$form, FormStateInterface $f
    // are added automatically by CKEditor 5. The validator would conflict with
    // the automatic addition of those allowed tags.
    if ($form_state->getValue('editor') !== 'ckeditor5') {
      $form['#validate'][] = 'media_filter_format_edit_form_validate';
      $form['#validate'][] = self::class . ':formatEditFormValidate';
    }
  }

@@ -299,4 +299,152 @@ public function fieldTypeCategoryInfoAlter(&$definitions): void {
    }
  }

  /**
   * Returns the appropriate URL to add media for the current user.
   *
   * @todo Remove in https://www.drupal.org/project/drupal/issues/2938116
   *
   * @param string[] $allowed_bundles
   *   An array of bundles that should be checked for create access.
   *
   * @return string|false
   *   The URL to add media, or FALSE if the user cannot create any media.
   *
   * @internal
   *   This function is internal and may be removed in a minor release.
   */
  protected function addUrl(array $allowed_bundles): string|false {
    $access_handler = \Drupal::entityTypeManager()->getAccessControlHandler('media');
    $create_bundles = array_filter($allowed_bundles, [$access_handler, 'createAccess']);

    // Add a section about how to create media if the user has access to do so.
    if (count($create_bundles) === 1) {
      return Url::fromRoute('entity.media.add_form', ['media_type' => reset($create_bundles)])->toString();
    }
    elseif (count($create_bundles) > 1) {
      return Url::fromRoute('entity.media.add_page')->toString();
    }

    return FALSE;
  }

  /**
   * Validate callback to ensure filter order and allowed_html are compatible.
   */
  public function formatEditFormValidate(array $form, FormStateInterface $form_state): void {
    if ($form_state->getTriggeringElement()['#name'] !== 'op') {
      return;
    }

    $allowed_html_path = [
      'filters',
      'filter_html',
      'settings',
      'allowed_html',
    ];

    $filter_html_settings_path = [
      'filters',
      'filter_html',
      'settings',
    ];

    $filter_html_enabled = $form_state->getValue([
      'filters',
      'filter_html',
      'status',
    ]);

    $media_embed_enabled = $form_state->getValue([
      'filters',
      'media_embed',
      'status',
    ]);

    if (!$media_embed_enabled) {
      return;
    }

    $get_filter_label = function ($filter_plugin_id) use ($form) {
      return (string) $form['filters']['order'][$filter_plugin_id]['filter']['#markup'];
    };

    if ($filter_html_enabled && $form_state->getValue($allowed_html_path)) {
      /** @var \Drupal\filter\Entity\FilterFormat $filter_format */
      $filter_format = $form_state->getFormObject()->getEntity();

      $filter_html = clone $filter_format->filters()->get('filter_html');
      $filter_html->setConfiguration(['settings' => $form_state->getValue($filter_html_settings_path)]);
      $restrictions = $filter_html->getHTMLRestrictions();
      $allowed = $restrictions['allowed'];

      // Require `<drupal-media>` HTML tag if filter_html is enabled.
      if (!isset($allowed['drupal-media'])) {
        $form_state->setError($form['filters']['settings']['filter_html']['allowed_html'], $this->t('The %media-embed-filter-label filter requires <code>&lt;drupal-media&gt;</code> among the allowed HTML tags.', [
          '%media-embed-filter-label' => $get_filter_label('media_embed'),
        ]));
      }
      else {
        $required_attributes = [
          'data-entity-type',
          'data-entity-uuid',
        ];

        // If there are no attributes, the allowed item is set to FALSE,
        // otherwise, it is set to an array.
        if ($allowed['drupal-media'] === FALSE) {
          $missing_attributes = $required_attributes;
        }
        else {
          $missing_attributes = array_diff($required_attributes, array_keys($allowed['drupal-media']));
        }

        if ($missing_attributes) {
          $form_state->setError($form['filters']['settings']['filter_html']['allowed_html'], $this->t('The <code>&lt;drupal-media&gt;</code> tag in the allowed HTML tags is missing the following attributes: <code>%list</code>.', [
            '%list' => implode(', ', $missing_attributes),
          ]));
        }
      }
    }

    $filters = $form_state->getValue('filters');

    // The "media_embed" filter must run after "filter_align", "filter_caption",
    // and "filter_html_image_secure".
    $precedents = [
      'filter_align',
      'filter_caption',
      'filter_html_image_secure',
    ];

    $error_filters = [];
    foreach ($precedents as $filter_name) {
      // A filter that should run before media embed filter.
      $precedent = $filters[$filter_name];

      if (empty($precedent['status']) || !isset($precedent['weight'])) {
        continue;
      }

      if ($precedent['weight'] >= $filters['media_embed']['weight']) {
        $error_filters[$filter_name] = $get_filter_label($filter_name);
      }
    }

    if (!empty($error_filters)) {
      $error_message = \Drupal::translation()->formatPlural(
        count($error_filters),
        'The %media-embed-filter-label filter needs to be placed after the %filter filter.',
        'The %media-embed-filter-label filter needs to be placed after the following filters: %filters.',
        [
          '%media-embed-filter-label' => $get_filter_label('media_embed'),
          '%filter' => reset($error_filters),
          '%filters' => implode(', ', $error_filters),
        ]
      );

      $form_state->setErrorByName('filters', $error_message);
    }
  }

}
+3 −2
Changes for core/modules/media/tests/src/FunctionalJavascript/MediaEmbedFilterConfigurationUiAddTest.php: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -4,7 +4,8 @@

namespace Drupal\Tests\media\FunctionalJavascript;

use PHPUnit\Framework\Attributes\CoversFunction;
use Drupal\media\Hook\MediaHooks;
use PHPUnit\Framework\Attributes\CoversMethod;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
@@ -14,7 +15,7 @@
 */
#[Group('media')]
#[Group('#slow')]
#[CoversFunction('media_filter_format_edit_form_validate')]
#[CoversMethod(MediaHooks::class, 'formatEditFormValidate')]
#[RunTestsInSeparateProcesses]
class MediaEmbedFilterConfigurationUiAddTest extends MediaEmbedFilterTestBase {

+3 −2
Changes for core/modules/media/tests/src/FunctionalJavascript/MediaEmbedFilterConfigurationUiEditTest.php: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -4,7 +4,8 @@

namespace Drupal\Tests\media\FunctionalJavascript;

use PHPUnit\Framework\Attributes\CoversFunction;
use Drupal\media\Hook\MediaHooks;
use PHPUnit\Framework\Attributes\CoversMethod;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
@@ -14,7 +15,7 @@
 */
#[Group('media')]
#[Group('#slow')]
#[CoversFunction('media_filter_format_edit_form_validate')]
#[CoversMethod(MediaHooks::class, 'formatEditFormValidate')]
#[RunTestsInSeparateProcesses]
class MediaEmbedFilterConfigurationUiEditTest extends MediaEmbedFilterTestBase {