View source
<?php
declare (strict_types=1);
namespace Drupal\ckeditor5\Plugin\Validation\Constraint;
use Drupal\ckeditor5\HTMLRestrictions;
use Drupal\ckeditor5\Plugin\CKEditor5PluginDefinition;
use Drupal\ckeditor5\Plugin\CKEditor5PluginElementsSubsetInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\editor\EditorInterface;
use Drupal\filter\FilterFormatInterface;
use Drupal\filter\Plugin\Filter\FilterAutoP;
use Drupal\filter\Plugin\Filter\FilterUrl;
use Drupal\filter\Plugin\FilterInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class FundamentalCompatibilityConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
use PluginManagerDependentValidatorTrait;
use TextEditorObjectDependentValidatorTrait;
const FUNDAMENTAL_CKEDITOR5_PLUGINS = [
'ckeditor5_essentials',
'ckeditor5_paragraph',
];
public function validate($toolbar_item, Constraint $constraint) {
if (!$constraint instanceof FundamentalCompatibilityConstraint) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\FundamentalCompatibility');
}
$text_editor = $this
->createTextEditorObjectFromContext();
$this
->checkNoMarkupFilters($text_editor
->getFilterFormat(), $constraint);
if ($this->context
->getViolations()
->count() > 0) {
return;
}
$this
->checkHtmlRestrictionsAreCompatible($text_editor
->getFilterFormat(), $constraint);
if ($this->context
->getViolations()
->count() > 0) {
return;
}
$this
->checkAllHtmlTagsAreCreatable($text_editor, $constraint);
$this
->checkHtmlRestrictionsMatch($text_editor, $constraint);
}
private function checkNoMarkupFilters(FilterFormatInterface $text_format, FundamentalCompatibilityConstraint $constraint) : void {
$markup_filters = static::getFiltersInFormatOfType($text_format, FilterInterface::TYPE_MARKUP_LANGUAGE);
foreach ($markup_filters as $markup_filter) {
if ($markup_filter instanceof FilterAutoP || $markup_filter instanceof FilterUrl) {
continue;
}
$this->context
->buildViolation($constraint->noMarkupFiltersMessage)
->setParameter('%filter_label', (string) $markup_filter
->getLabel())
->setParameter('%filter_plugin_id', $markup_filter
->getPluginId())
->addViolation();
}
}
private function checkHtmlRestrictionsAreCompatible(FilterFormatInterface $text_format, FundamentalCompatibilityConstraint $constraint) : void {
$fundamental = new HTMLRestrictions($this->pluginManager
->getProvidedElements(self::FUNDAMENTAL_CKEDITOR5_PLUGINS));
$html_restrictions = $text_format
->getHtmlRestrictions();
if (!isset($html_restrictions['allowed'])) {
return;
}
if (!$fundamental
->diff(HTMLRestrictions::fromTextFormat($text_format))
->allowsNothing()) {
$offending_filter = static::findHtmlRestrictorFilterNotAllowingTags($text_format, $fundamental);
$this->context
->buildViolation($constraint->nonAllowedElementsMessage)
->setParameter('%filter_label', (string) $offending_filter
->getLabel())
->setParameter('%filter_plugin_id', $offending_filter
->getPluginId())
->addViolation();
}
}
private function checkHtmlRestrictionsMatch(EditorInterface $text_editor, FundamentalCompatibilityConstraint $constraint) : void {
$html_restrictor_filters = static::getFiltersInFormatOfType($text_editor
->getFilterFormat(), FilterInterface::TYPE_HTML_RESTRICTOR);
$enabled_plugins = array_keys($this->pluginManager
->getEnabledDefinitions($text_editor));
$provided = $this->pluginManager
->getProvidedElements($enabled_plugins, $text_editor);
foreach ($html_restrictor_filters as $filter_plugin_id => $filter) {
$allowed = HTMLRestrictions::fromFilterPluginInstance($filter);
$provided = new HTMLRestrictions($provided);
$diff_allowed = $allowed
->diff($provided);
$diff_elements = $provided
->diff($allowed);
if (!$diff_allowed
->allowsNothing()) {
$this->context
->buildViolation($constraint->notSupportedElementsMessage)
->setParameter('@list', implode(' ', $provided
->toCKEditor5ElementsArray()))
->setParameter('@diff', implode(' ', $diff_allowed
->toCKEditor5ElementsArray()))
->atPath("filters.{$filter_plugin_id}")
->addViolation();
}
if (!$diff_elements
->allowsNothing()) {
$this->context
->buildViolation($constraint->missingElementsMessage)
->setParameter('@list', implode(' ', $provided
->toCKEditor5ElementsArray()))
->setParameter('@diff', implode(' ', $diff_elements
->toCKEditor5ElementsArray()))
->atPath("filters.{$filter_plugin_id}")
->addViolation();
}
}
}
private function checkAllHtmlTagsAreCreatable(EditorInterface $text_editor, FundamentalCompatibilityConstraint $constraint) : void {
$enabled_definitions = $this->pluginManager
->getEnabledDefinitions($text_editor);
$enabled_plugins = array_keys($enabled_definitions);
if (in_array('ckeditor5_arbitraryHtmlSupport', $enabled_plugins, TRUE)) {
return;
}
$tags_and_attributes = new HTMLRestrictions($this->pluginManager
->getProvidedElements($enabled_plugins, $text_editor));
$creatable_tags = new HTMLRestrictions($this->pluginManager
->getProvidedElements($enabled_plugins, $text_editor, FALSE, TRUE));
$needed_tags = $tags_and_attributes
->extractPlainTagsSubset();
$non_creatable_tags = $needed_tags
->diff($creatable_tags);
if (!$non_creatable_tags
->allowsNothing()) {
foreach ($non_creatable_tags
->toCKEditor5ElementsArray() as $non_creatable_tag) {
$needle = HTMLRestrictions::fromString($non_creatable_tag);
$matching_plugins = array_filter($enabled_definitions, function (CKEditor5PluginDefinition $d) use ($needle, $text_editor) {
if (!$d
->hasElements()) {
return FALSE;
}
$haystack = new HTMLRestrictions($this->pluginManager
->getProvidedElements([
$d
->id(),
], $text_editor, FALSE, FALSE));
return !$haystack
->extractPlainTagsSubset()
->intersect($needle)
->allowsNothing();
});
assert(count($matching_plugins) === 1);
$plugin_definition = reset($matching_plugins);
assert($plugin_definition instanceof CKEditor5PluginDefinition);
$provided_elements = new HTMLRestrictions($this->pluginManager
->getProvidedElements([
$plugin_definition
->id(),
], $text_editor, FALSE, FALSE));
$attributes_on_tag = $provided_elements
->intersect(new HTMLRestrictions(array_fill_keys(array_keys($needle
->getAllowedElements()), TRUE)));
$violation = $this->context
->buildViolation($constraint->nonCreatableTagMessage)
->setParameter('@non_creatable_tag', $non_creatable_tag)
->setParameter('%plugin', $plugin_definition
->label())
->setParameter('@attributes_on_tag', implode(', ', $attributes_on_tag
->toCKEditor5ElementsArray()));
if (is_a($plugin_definition
->getClass(), CKEditor5PluginElementsSubsetInterface::class, TRUE)) {
$violation
->atPath(sprintf('settings.plugins.%s', $plugin_definition
->id()));
}
elseif ($plugin_definition
->hasToolbarItems()) {
$toolbar_items = $plugin_definition
->getToolbarItems();
$active_toolbar_items = array_intersect($text_editor
->getSettings()['toolbar']['items'], array_keys($toolbar_items));
$violation
->atPath(sprintf('settings.toolbar.items.%d', array_keys($active_toolbar_items)[0]));
}
$violation
->addViolation();
}
}
}
private static function getFiltersInFormatOfType(FilterFormatInterface $text_format, int $filter_type, callable $extra_requirements = NULL) : iterable {
assert(in_array($filter_type, [
FilterInterface::TYPE_MARKUP_LANGUAGE,
FilterInterface::TYPE_HTML_RESTRICTOR,
FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE,
FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE,
]));
foreach ($text_format
->filters() as $id => $filter) {
if ($filter->status && $filter
->getType() === $filter_type && ($extra_requirements === NULL || $extra_requirements($filter))) {
(yield $id => $filter);
}
}
}
private static function findHtmlRestrictorFilterNotAllowingTags(FilterFormatInterface $text_format, HTMLRestrictions $required) : FilterInterface {
$filters = static::getFiltersInFormatOfType($text_format, FilterInterface::TYPE_HTML_RESTRICTOR, function (FilterInterface $filter) {
return $filter
->getHTMLRestrictions() !== FALSE;
});
foreach ($filters as $filter) {
if (!$required
->diff(HTMLRestrictions::fromFilterPluginInstance($filter))
->allowsNothing()) {
return $filter;
}
}
throw new \InvalidArgumentException('This text format does not have a "tags allowed" restriction that excludes the required tags.');
}
}