upgrades core to 8.4.2

This commit is contained in:
Bachir Soussi Chiadmi
2017-11-14 16:09:54 +01:00
parent bd60eff9b3
commit c2b4e25be4
3504 changed files with 140306 additions and 38684 deletions
@@ -4,60 +4,56 @@ dependencies:
module:
- content_moderation
id: editorial
label: 'Editorial workflow'
states:
archived:
label: Archived
weight: 5
draft:
label: Draft
weight: -5
published:
label: Published
weight: 0
transitions:
archive:
label: Archive
from:
- published
to: archived
weight: 2
archived_draft:
label: 'Restore to Draft'
from:
- archived
to: draft
weight: 3
archived_published:
label: Restore
from:
- archived
to: published
weight: 4
create_new_draft:
label: 'Create New Draft'
from:
- draft
- published
to: draft
weight: 0
publish:
label: Publish
from:
- draft
- published
to: published
weight: 1
label: 'Editorial'
type: content_moderation
type_settings:
states:
archived:
label: Archived
weight: 5
published: false
default_revision: true
draft:
label: Draft
published: false
default_revision: false
weight: -5
published:
label: Published
published: true
default_revision: true
weight: 0
transitions:
archive:
label: Archive
from:
- published
to: archived
weight: 2
archived_draft:
label: 'Restore to Draft'
from:
- archived
to: draft
weight: 3
archived_published:
label: Restore
from:
- archived
to: published
weight: 4
create_new_draft:
label: 'Create New Draft'
to: draft
weight: 0
from:
- draft
- published
publish:
label: Publish
to: published
weight: 1
from:
- draft
- published
entity_types: { }
@@ -1,27 +1,29 @@
views.filter.latest_revision:
type: views_filter
label: 'Latest revision'
content_moderation.state:
type: workflows.state
mapping:
value:
type: string
label: 'Value'
published:
type: boolean
label: 'Is published'
default_revision:
type: boolean
label: 'Is default revision'
workflow.type_settings.content_moderation:
type: mapping
mapping:
states:
type: sequence
label: 'Additional state configuration for content moderation'
label: 'Content moderation states'
orderby: key
sequence:
type: mapping
type: content_moderation.state
label: 'States'
mapping:
published:
type: boolean
label: 'Is published'
default_revision:
type: boolean
label: 'Is default revision'
transitions:
type: sequence
orderby: key
sequence:
type: workflows.transition
label: 'Transitions'
entity_types:
type: sequence
label: 'Entity types'
@@ -0,0 +1,23 @@
<?php
/**
* @file
* API documentation for Content Moderation module.
*/
/**
* @defgroup content_moderation_plugin Content Moderation Workflow Type Plugin
* @{
* The Workflow Type plugin implemented by Content Moderation links revisionable
* entities to workflows.
*
* In the Content Moderation Workflow Type Plugin, one method requires the
* entity object to be passed in as a parameter, even though the interface
* defined by Workflows module doesn't require this:
* @code
* $workflow_type_plugin->getInitialState($entity);
* @endcode
* This is used to determine the initial moderation state based on the
* publishing status of the entity.
* @}
*/
@@ -8,8 +8,8 @@ configure: entity.workflow.collection
dependencies:
- workflows
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
# Information added by Drupal.org packaging script on 2017-11-03
version: '8.4.2'
core: '8.x'
project: 'drupal'
datestamp: 1502903957
datestamp: 1509719929
@@ -0,0 +1,16 @@
<?php
/**
* @file
* Install, update and uninstall functions for the Content Moderation module.
*/
/**
* Remove the 'content_revision_tracker' table.
*/
function content_moderation_update_8401() {
$database_schema = \Drupal::database()->schema();
if ($database_schema->tableExists('content_revision_tracker')) {
$database_schema->dropTable('content_revision_tracker');
}
}
@@ -13,12 +13,14 @@ use Drupal\content_moderation\Plugin\Action\ModerationOptOutUnpublishNode;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\workflows\WorkflowInterface;
use Drupal\node\NodeInterface;
use Drupal\node\Plugin\Action\PublishNode;
use Drupal\node\Plugin\Action\UnpublishNode;
use Drupal\workflows\Entity\Workflow;
@@ -62,15 +64,6 @@ function content_moderation_entity_type_alter(array &$entity_types) {
->entityTypeAlter($entity_types);
}
/**
* Implements hook_entity_operation().
*/
function content_moderation_entity_operation(EntityInterface $entity) {
return \Drupal::service('class_resolver')
->getInstanceFromDefinition(EntityTypeInfo::class)
->entityOperation($entity);
}
/**
* Implements hook_entity_presave().
*/
@@ -98,6 +91,33 @@ function content_moderation_entity_update(EntityInterface $entity) {
->entityUpdate($entity);
}
/**
* Implements hook_entity_delete().
*/
function content_moderation_entity_delete(EntityInterface $entity) {
return \Drupal::service('class_resolver')
->getInstanceFromDefinition(EntityOperations::class)
->entityDelete($entity);
}
/**
* Implements hook_entity_revision_delete().
*/
function content_moderation_entity_revision_delete(EntityInterface $entity) {
return \Drupal::service('class_resolver')
->getInstanceFromDefinition(EntityOperations::class)
->entityRevisionDelete($entity);
}
/**
* Implements hook_entity_translation_delete().
*/
function content_moderation_entity_translation_delete(EntityInterface $translation) {
return \Drupal::service('class_resolver')
->getInstanceFromDefinition(EntityOperations::class)
->entityTranslationDelete($translation);
}
/**
* Implements hook_form_alter().
*/
@@ -109,9 +129,6 @@ function content_moderation_form_alter(&$form, FormStateInterface $form_state, $
/**
* Implements hook_preprocess_HOOK().
*
* Many default node templates rely on $page to determine whether to output the
* node title as part of the node content.
*/
function content_moderation_preprocess_node(&$variables) {
\Drupal::service('class_resolver')
@@ -138,34 +155,34 @@ function content_moderation_entity_view(array &$build, EntityInterface $entity,
}
/**
* Implements hook_node_access().
* Implements hook_entity_access().
*
* Nodes in particular should be viewable if unpublished and the user has
* the appropriate permission. This permission is therefore effectively
* mandatory for any user that wants to moderate things.
* Entities should be viewable if unpublished and the user has the appropriate
* permission. This permission is therefore effectively mandatory for any user
* that wants to moderate things.
*/
function content_moderation_node_access(NodeInterface $node, $operation, AccountInterface $account) {
function content_moderation_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\content_moderation\ModerationInformationInterface $moderation_info */
$moderation_info = Drupal::service('content_moderation.moderation_information');
$access_result = NULL;
if ($operation === 'view') {
$access_result = (!$node->isPublished())
$access_result = (($entity instanceof EntityPublishedInterface) && !$entity->isPublished())
? AccessResult::allowedIfHasPermission($account, 'view any unpublished content')
: AccessResult::neutral();
$access_result->addCacheableDependency($node);
$access_result->addCacheableDependency($entity);
}
elseif ($operation === 'update' && $moderation_info->isModeratedEntity($node) && $node->moderation_state) {
elseif ($operation === 'update' && $moderation_info->isModeratedEntity($entity) && $entity->moderation_state) {
/** @var \Drupal\content_moderation\StateTransitionValidation $transition_validation */
$transition_validation = \Drupal::service('content_moderation.state_transition_validation');
$valid_transition_targets = $transition_validation->getValidTransitions($node, $account);
$valid_transition_targets = $transition_validation->getValidTransitions($entity, $account);
$access_result = $valid_transition_targets ? AccessResult::neutral() : AccessResult::forbidden();
$access_result->addCacheableDependency($node);
$access_result->addCacheableDependency($entity);
$access_result->addCacheableDependency($account);
$workflow = \Drupal::service('content_moderation.moderation_information')->getWorkflowForEntity($node);
$workflow = $moderation_info->getWorkflowForEntity($entity);
$access_result->addCacheableDependency($workflow);
foreach ($valid_transition_targets as $valid_transition_target) {
$access_result->addCacheableDependency($valid_transition_target);
@@ -175,6 +192,27 @@ function content_moderation_node_access(NodeInterface $node, $operation, Account
return $access_result;
}
/**
* Implements hook_entity_field_access().
*/
function content_moderation_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
if ($items && $operation === 'edit') {
/** @var \Drupal\content_moderation\ModerationInformationInterface $moderation_info */
$moderation_info = Drupal::service('content_moderation.moderation_information');
$entity_type = \Drupal::entityTypeManager()->getDefinition($field_definition->getTargetEntityTypeId());
$entity = $items->getEntity();
// Deny edit access to the published field if the entity is being moderated.
if ($entity_type->hasKey('published') && $moderation_info->isModeratedEntity($entity) && $entity->moderation_state && $field_definition->getName() == $entity_type->getKey('published')) {
return AccessResult::forbidden();
}
}
return AccessResult::neutral();
}
/**
* Implements hook_theme().
*/
@@ -217,6 +255,20 @@ function content_moderation_entity_bundle_info_alter(&$bundles) {
}
}
/**
* Implements hook_entity_bundle_delete().
*/
function content_moderation_entity_bundle_delete($entity_type_id, $bundle_id) {
// Remove non-configuration based bundles from content moderation based
// workflows when they are removed.
foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
if ($workflow->getTypePlugin()->appliesToEntityTypeAndBundle($entity_type_id, $bundle_id)) {
$workflow->getTypePlugin()->removeEntityTypeAndBundle($entity_type_id, $bundle_id);
$workflow->save();
}
}
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
@@ -232,5 +284,19 @@ function content_moderation_workflow_insert(WorkflowInterface $entity) {
* Implements hook_ENTITY_TYPE_update().
*/
function content_moderation_workflow_update(WorkflowInterface $entity) {
content_moderation_workflow_insert($entity);
// Clear bundle cache so workflow gets added or removed from the bundle
// information.
\Drupal::service('entity_type.bundle.info')->clearCachedBundles();
// Clear field cache so extra field is added or removed.
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
}
/**
* Implements hook_rest_resource_alter().
*/
function content_moderation_rest_resource_alter(&$definitions) {
// ContentModerationState is an internal entity type. Therefore it should not
// be exposed via REST.
// @see \Drupal\content_moderation\ContentModerationStateAccessControlHandler
unset($definitions['entity:content_moderation_state']);
}
@@ -1,19 +1,9 @@
view any unpublished content:
title: 'View any unpublished content'
description: 'This permission is necessary for any users that may moderate content.'
view content moderation:
title: 'View content moderation'
description: 'View content moderation.'
'administer content moderation':
title: 'Administer content moderation'
description: 'Administer workflows on content entities.'
'restrict access': TRUE
view latest version:
title: 'View the latest version'
description: 'View the latest version of an entity. (Also requires "View any unpublished content" permission)'
description: 'Requires the "View any unpublished content" permission'
permission_callbacks:
- \Drupal\content_moderation\Permissions::transitionPermissions
@@ -0,0 +1,7 @@
content_moderation.workflow_type_edit_form:
path: '/admin/config/workflow/workflows/manage/{workflow}/type/{entity_type_id}'
defaults:
_form: '\Drupal\content_moderation\Form\ContentModerationConfigureEntityTypesForm'
_title_callback: '\Drupal\content_moderation\Form\ContentModerationConfigureEntityTypesForm::getTitle'
requirements:
_permission: 'administer workflows'
@@ -15,8 +15,8 @@ services:
arguments: ['@content_moderation.moderation_information']
tags:
- { name: access_check, applies_to: _content_moderation_latest_version }
content_moderation.revision_tracker:
class: Drupal\content_moderation\RevisionTracker
arguments: ['@database']
content_moderation.config_import_subscriber:
class: Drupal\content_moderation\EventSubscriber\ConfigImportSubscriber
arguments: ['@config.manager', '@entity_type.manager']
tags:
- { name: backend_overridable }
- { name: event_subscriber }
@@ -16,13 +16,6 @@ function content_moderation_views_data() {
return _content_moderation_views_data_object()->getViewsData();
}
/**
* Implements hook_views_data_alter().
*/
function content_moderation_views_data_alter(array &$data) {
_content_moderation_views_data_object()->alterViewsData($data);
}
/**
* Creates a ViewsData object to respond to views hooks.
*
@@ -8,12 +8,35 @@ ul.entity-moderation-form {
display: flex;
-webkit-flex-wrap: wrap; /* Safari */
flex-wrap: wrap;
-webkit-justify-content: space-around; /* Safari */
justify-content: space-around;
-webkit-align-items: flex-end; /* Safari */
align-items: flex-end;
-webkit-align-items: flex-start; /* Safari */
align-items: flex-start;
}
ul.entity-moderation-form li {
margin-right: 2em;
display: table;
}
ul.entity-moderation-form li:last-child {
-webkit-align-self: flex-end; /* Safari */
align-self: flex-end;
margin-right: 0;
}
ul.entity-moderation-form .form-item {
margin-top: 1em;
margin-bottom: 1em;
}
ul.entity-moderation-form .form-item label {
padding-bottom: 0.25em;
display: table;
}
ul.entity-moderation-form input[type=submit] {
margin-bottom: 1.2em;
}
ul.entity-moderation-form .btn {
margin-bottom: 1.1em;
}
@@ -3,5 +3,8 @@
* Theme styles for the content_moderation module.
*/
ul.entity-moderation-form {
border-bottom: 1px solid gray;
border: 1px dashed #bbb;
margin: 2em 0em;
background: #fff;
padding-left: 1em;
}
@@ -2,6 +2,7 @@
namespace Drupal\content_moderation\Access;
use Drupal\Core\Access\AccessException;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\Access\AccessInterface;
@@ -34,7 +35,7 @@ class LatestRevisionCheck implements AccessInterface {
}
/**
* Checks that there is a forward revision available.
* Checks that there is a pending revision available.
*
* This checker assumes the presence of an '_entity_access' requirement key
* in the same form as used by EntityAccessCheck.
@@ -54,7 +55,7 @@ class LatestRevisionCheck implements AccessInterface {
public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
// This tab should not show up unless there's a reason to show it.
$entity = $this->loadEntity($route, $route_match);
if ($this->moderationInfo->hasForwardRevision($entity)) {
if ($this->moderationInfo->hasPendingRevision($entity)) {
// Check the global permissions first.
$access_result = AccessResult::allowedIfHasPermissions($account, ['view latest version', 'view any unpublished content']);
if (!$access_result->isAllowed()) {
@@ -81,10 +82,8 @@ class LatestRevisionCheck implements AccessInterface {
* @return \Drupal\Core\Entity\ContentEntityInterface
* returns the Entity in question.
*
* @throws \Exception
* A generic exception is thrown if the entity couldn't be loaded. This
* almost always implies a developer error, so it should get turned into
* an HTTP 500.
* @throws \Drupal\Core\Access\AccessException
* An AccessException is thrown if the entity couldn't be loaded.
*/
protected function loadEntity(Route $route, RouteMatchInterface $route_match) {
$entity_type = $route->getOption('_content_moderation_entity_type');
@@ -94,7 +93,7 @@ class LatestRevisionCheck implements AccessInterface {
return $entity;
}
}
throw new \Exception(sprintf('%s is not a valid entity route. The LatestRevisionCheck access checker may only be used with a route that has a single entity parameter.', $route_match->getRouteName()));
throw new AccessException(sprintf('%s is not a valid entity route. The LatestRevisionCheck access checker may only be used with a route that has a single entity parameter.', $route_match->getRouteName()));
}
}
@@ -9,13 +9,15 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Determines whether a route is the "Latest version" tab of a node.
*
* @internal
*/
class ContentPreprocess implements ContainerInjectionInterface {
/**
* The route match service.
*
* @var \Drupal\Core\Routing\RouteMatchInterface $routeMatch
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
@@ -39,10 +41,10 @@ class ContentPreprocess implements ContainerInjectionInterface {
}
/**
* Wrapper for hook_preprocess_HOOK().
*
* @param array $variables
* Theme variables to preprocess.
*
* @see hook_preprocess_HOOK()
*/
public function preprocessNode(array &$variables) {
// Set the 'page' template variable when the node is being displayed on the
@@ -2,8 +2,8 @@
namespace Drupal\content_moderation\Entity;
use Drupal\content_moderation\ContentModerationStateInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\TypedData\TranslatableInterface;
@@ -39,6 +39,11 @@ use Drupal\user\UserInterface;
* "langcode" = "langcode",
* }
* )
*
* @internal
* This entity is marked internal because it should not be used directly to
* alter the moderation state of an entity. Instead, the computed
* moderation_state field should be set on the entity directly.
*/
class ContentModerationState extends ContentEntityBase implements ContentModerationStateInterface {
@@ -61,7 +66,6 @@ class ContentModerationState extends ContentEntityBase implements ContentModerat
->setDescription(t('The workflow the moderation state is in.'))
->setSetting('target_type', 'workflow')
->setRequired(TRUE)
->setTranslatable(TRUE)
->setRevisionable(TRUE);
$fields['moderation_state'] = BaseFieldDefinition::create('string')
@@ -137,6 +141,44 @@ class ContentModerationState extends ContentEntityBase implements ContentModerat
$content_moderation_state->realSave();
}
/**
* Loads a content moderation state entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* A moderated entity object.
*
* @return \Drupal\content_moderation\Entity\ContentModerationStateInterface|null
* The related content moderation state or NULL if none could be found.
*
* @internal
* This method should only be called by code directly handling the
* ContentModerationState entity objects.
*/
public static function loadFromModeratedEntity(EntityInterface $entity) {
$content_moderation_state = NULL;
$moderation_info = \Drupal::service('content_moderation.moderation_information');
if ($moderation_info->isModeratedEntity($entity)) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$storage = \Drupal::entityTypeManager()->getStorage('content_moderation_state');
$ids = $storage->getQuery()
->condition('content_entity_type_id', $entity->getEntityTypeId())
->condition('content_entity_id', $entity->id())
->condition('workflow', $moderation_info->getWorkflowForEntity($entity)->id())
->condition('content_entity_revision_id', $entity->getLoadedRevisionId())
->allRevisions()
->execute();
if ($ids) {
/** @var \Drupal\content_moderation\Entity\ContentModerationStateInterface $content_moderation_state */
$content_moderation_state = $storage->loadRevision(key($ids));
}
}
return $content_moderation_state;
}
/**
* Default value callback for the 'uid' base field definition.
*
@@ -0,0 +1,18 @@
<?php
namespace Drupal\content_moderation\Entity;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\user\EntityOwnerInterface;
/**
* An interface for Content moderation state entity.
*
* Content moderation state entities track the moderation state of other content
* entities.
*
* @internal
*/
interface ContentModerationStateInterface extends ContentEntityInterface, EntityOwnerInterface {
}
@@ -6,6 +6,8 @@ use Drupal\Core\Form\FormStateInterface;
/**
* Customizations for block content entities.
*
* @internal
*/
class BlockContentModerationHandler extends ModerationHandler {
@@ -13,9 +15,9 @@ class BlockContentModerationHandler extends ModerationHandler {
* {@inheritdoc}
*/
public function enforceRevisionsEntityFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
$form['revision_information']['revision']['#default_value'] = TRUE;
$form['revision_information']['revision']['#disabled'] = TRUE;
$form['revision_information']['revision']['#description'] = $this->t('Revisions must be required when moderation is enabled.');
$form['revision']['#default_value'] = TRUE;
$form['revision']['#disabled'] = TRUE;
$form['revision']['#description'] = $this->t('Revisions must be required when moderation is enabled.');
}
/**
@@ -14,6 +14,8 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
* Common customizations for most/all entities.
*
* This class is intended primarily as a base class.
*
* @internal
*/
class ModerationHandler implements ModerationHandlerInterface, EntityHandlerInterface {
@@ -33,6 +35,11 @@ class ModerationHandler implements ModerationHandlerInterface, EntityHandlerInte
// This is probably not necessary if configuration is setup correctly.
$entity->setNewRevision(TRUE);
$entity->isDefaultRevision($default_revision);
if ($entity->hasField('revision_translation_affected')) {
// @todo remove this when revision and translation issues have been
// resolved. https://www.drupal.org/node/2860097
$entity->set('revision_translation_affected', TRUE);
}
// Update publishing status if it can be updated and if it needs updating.
if (($entity instanceof EntityPublishedInterface) && $entity->isPublished() !== $published_state) {
@@ -11,6 +11,8 @@ use Drupal\Core\Form\FormStateInterface;
* Much of the logic contained in this handler is an indication of flaws
* in the Entity API that are insufficiently standardized between entity types.
* Hopefully over time functionality can be removed from this interface.
*
* @internal
*/
interface ModerationHandlerInterface {
@@ -9,6 +9,8 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Customizations for node entities.
*
* @internal
*/
class NodeModerationHandler extends ModerationHandler {
@@ -51,14 +53,9 @@ class NodeModerationHandler extends ModerationHandler {
* {@inheritdoc}
*/
public function enforceRevisionsBundleFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
/* @var \Drupal\node\Entity\NodeType $entity */
$entity = $form_state->getFormObject()->getEntity();
if ($this->moderationInfo->getWorkflowForEntity($entity)) {
// Force the revision checkbox on.
$form['workflow']['options']['#default_value']['revision'] = 'revision';
$form['workflow']['options']['revision']['#disabled'] = TRUE;
}
// Force the revision checkbox on.
$form['workflow']['options']['#default_value']['revision'] = 'revision';
$form['workflow']['options']['revision']['#disabled'] = TRUE;
}
}
@@ -0,0 +1,123 @@
<?php
namespace Drupal\content_moderation\Entity\Routing;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Entity\Routing\EntityRouteProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Dynamic route provider for the Content moderation module.
*
* Provides the following routes:
* - The latest version tab, showing the latest revision of an entity, not the
* default one.
*
* @internal
*/
class EntityModerationRouteProvider implements EntityRouteProviderInterface, EntityHandlerInterface {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* Constructs a new DefaultHtmlRouteProvider.
*
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_manager
* The entity manager.
*/
public function __construct(EntityFieldManagerInterface $entity_manager) {
$this->entityFieldManager = $entity_manager;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$container->get('entity_field.manager')
);
}
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = new RouteCollection();
if ($moderation_route = $this->getLatestVersionRoute($entity_type)) {
$entity_type_id = $entity_type->id();
$collection->add("entity.{$entity_type_id}.latest_version", $moderation_route);
}
return $collection;
}
/**
* Gets the moderation-form route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getLatestVersionRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('latest-version') && $entity_type->hasViewBuilderClass()) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('latest-version'));
$route
->addDefaults([
'_entity_view' => "{$entity_type_id}.full",
'_title_callback' => '\Drupal\Core\Entity\Controller\EntityController::title',
])
// If the entity type is a node, unpublished content will be visible
// if the user has the "view all unpublished content" permission.
->setRequirement('_entity_access', "{$entity_type_id}.view")
->setRequirement('_content_moderation_latest_version', 'TRUE')
->setOption('_content_moderation_entity_type', $entity_type_id)
->setOption('parameters', [
$entity_type_id => [
'type' => 'entity:' . $entity_type_id,
'load_pending_revision' => 1,
],
]);
// Entity types with serial IDs can specify this in their route
// requirements, improving the matching process.
if ($this->getEntityTypeIdKeyType($entity_type) === 'integer') {
$route->setRequirement($entity_type_id, '\d+');
}
return $route;
}
}
/**
* Gets the type of the ID key for a given entity type.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* An entity type.
*
* @return string|null
* The type of the ID key for a given entity type, or NULL if the entity
* type does not support fields.
*/
protected function getEntityTypeIdKeyType(EntityTypeInterface $entity_type) {
if (!$entity_type->entityClassImplements(FieldableEntityInterface::class)) {
return NULL;
}
$field_storage_definitions = $this->entityFieldManager->getFieldStorageDefinitions($entity_type->id());
return $field_storage_definitions[$entity_type->getKey('id')]->getType();
}
}
@@ -3,19 +3,20 @@
namespace Drupal\content_moderation;
use Drupal\content_moderation\Entity\ContentModerationState as ContentModerationStateEntity;
use Drupal\content_moderation\Entity\ContentModerationStateInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\content_moderation\Form\EntityModerationForm;
use Drupal\workflows\WorkflowInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines a class for reacting to entity events.
*
* @internal
*/
class EntityOperations implements ContainerInjectionInterface {
@@ -40,13 +41,6 @@ class EntityOperations implements ContainerInjectionInterface {
*/
protected $formBuilder;
/**
* The Revision Tracker service.
*
* @var \Drupal\content_moderation\RevisionTrackerInterface
*/
protected $tracker;
/**
* The entity bundle information service.
*
@@ -63,16 +57,13 @@ class EntityOperations implements ContainerInjectionInterface {
* Entity type manager service.
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder.
* @param \Drupal\content_moderation\RevisionTrackerInterface $tracker
* The revision tracker.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* The entity bundle information service.
*/
public function __construct(ModerationInformationInterface $moderation_info, EntityTypeManagerInterface $entity_type_manager, FormBuilderInterface $form_builder, RevisionTrackerInterface $tracker, EntityTypeBundleInfoInterface $bundle_info) {
public function __construct(ModerationInformationInterface $moderation_info, EntityTypeManagerInterface $entity_type_manager, FormBuilderInterface $form_builder, EntityTypeBundleInfoInterface $bundle_info) {
$this->moderationInfo = $moderation_info;
$this->entityTypeManager = $entity_type_manager;
$this->formBuilder = $form_builder;
$this->tracker = $tracker;
$this->bundleInfo = $bundle_info;
}
@@ -84,7 +75,6 @@ class EntityOperations implements ContainerInjectionInterface {
$container->get('content_moderation.moderation_information'),
$container->get('entity_type.manager'),
$container->get('form_builder'),
$container->get('content_moderation.revision_tracker'),
$container->get('entity_type.bundle.info')
);
}
@@ -94,6 +84,8 @@ class EntityOperations implements ContainerInjectionInterface {
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being saved.
*
* @see hook_entity_presave()
*/
public function entityPresave(EntityInterface $entity) {
if (!$this->moderationInfo->isModeratedEntity($entity)) {
@@ -103,23 +95,24 @@ class EntityOperations implements ContainerInjectionInterface {
if ($entity->moderation_state->value) {
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
/** @var \Drupal\content_moderation\ContentModerationState $current_state */
$current_state = $workflow->getState($entity->moderation_state->value);
$current_state = $workflow->getTypePlugin()
->getState($entity->moderation_state->value);
// This entity is default if it is new, a new translation, the default
// revision, or the default revision is not published.
$update_default_revision = $entity->isNew()
|| $entity->isNewTranslation()
|| $current_state->isDefaultRevisionState()
|| !$this->isDefaultRevisionPublished($entity, $workflow);
|| !$this->moderationInfo->isDefaultRevisionPublished($entity);
// Fire per-entity-type logic for handling the save process.
$this->entityTypeManager->getHandler($entity->getEntityTypeId(), 'moderation')->onPresave($entity, $update_default_revision, $current_state->isPublishedState());
$this->entityTypeManager
->getHandler($entity->getEntityTypeId(), 'moderation')
->onPresave($entity, $update_default_revision, $current_state->isPublishedState());
}
}
/**
* Hook bridge.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity that was just saved.
*
@@ -128,13 +121,10 @@ class EntityOperations implements ContainerInjectionInterface {
public function entityInsert(EntityInterface $entity) {
if ($this->moderationInfo->isModeratedEntity($entity)) {
$this->updateOrCreateFromEntity($entity);
$this->setLatestRevision($entity);
}
}
/**
* Hook bridge.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity that was just saved.
*
@@ -143,7 +133,6 @@ class EntityOperations implements ContainerInjectionInterface {
public function entityUpdate(EntityInterface $entity) {
if ($this->moderationInfo->isModeratedEntity($entity)) {
$this->updateOrCreateFromEntity($entity);
$this->setLatestRevision($entity);
}
}
@@ -154,31 +143,19 @@ class EntityOperations implements ContainerInjectionInterface {
* The entity to update or create a moderation state for.
*/
protected function updateOrCreateFromEntity(EntityInterface $entity) {
$moderation_state = $entity->moderation_state->value;
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if (!$moderation_state) {
$moderation_state = $workflow->getTypePlugin()->getInitialState($workflow, $entity)->id();
}
// @todo what if $entity->moderation_state is null at this point?
$entity_type_id = $entity->getEntityTypeId();
$entity_id = $entity->id();
$entity_revision_id = $entity->getRevisionId();
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
$content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($entity);
$storage = $this->entityTypeManager->getStorage('content_moderation_state');
$entities = $storage->loadByProperties([
'content_entity_type_id' => $entity_type_id,
'content_entity_id' => $entity_id,
'workflow' => $workflow->id(),
]);
/** @var \Drupal\content_moderation\ContentModerationStateInterface $content_moderation_state */
$content_moderation_state = reset($entities);
if (!($content_moderation_state instanceof ContentModerationStateInterface)) {
$storage = $this->entityTypeManager->getStorage('content_moderation_state');
$content_moderation_state = $storage->create([
'content_entity_type_id' => $entity_type_id,
'content_entity_id' => $entity_id,
'content_entity_type_id' => $entity->getEntityTypeId(),
'content_entity_id' => $entity->id(),
// Make sure that the moderation state entity has the same language code
// as the moderated entity.
'langcode' => $entity->language()->getId(),
]);
$content_moderation_state->workflow->target_id = $workflow->id();
}
@@ -200,32 +177,70 @@ class EntityOperations implements ContainerInjectionInterface {
}
// Create the ContentModerationState entity for the inserted entity.
$moderation_state = $entity->moderation_state->value;
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if (!$moderation_state) {
$moderation_state = $workflow->getTypePlugin()->getInitialState($entity)->id();
}
// @todo what if $entity->moderation_state is null at this point?
$content_moderation_state->set('content_entity_revision_id', $entity_revision_id);
$content_moderation_state->set('moderation_state', $moderation_state);
ContentModerationStateEntity::updateOrCreateFromEntity($content_moderation_state);
}
/**
* Set the latest revision.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The content entity to create content_moderation_state entity for.
* The entity being deleted.
*
* @see hook_entity_delete()
*/
protected function setLatestRevision(EntityInterface $entity) {
public function entityDelete(EntityInterface $entity) {
$content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($entity);
if ($content_moderation_state) {
$content_moderation_state->delete();
}
}
/**
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity revision being deleted.
*
* @see hook_entity_revision_delete()
*/
public function entityRevisionDelete(EntityInterface $entity) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$this->tracker->setLatestRevision(
$entity->getEntityTypeId(),
$entity->id(),
$entity->language()->getId(),
$entity->getRevisionId()
);
if (!$entity->isDefaultRevision()) {
$content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($entity);
if ($content_moderation_state) {
$this->entityTypeManager
->getStorage('content_moderation_state')
->deleteRevision($content_moderation_state->getRevisionId());
}
}
}
/**
* @param \Drupal\Core\Entity\EntityInterface $translation
* The entity translation being deleted.
*
* @see hook_entity_translation_delete()
*/
public function entityTranslationDelete(EntityInterface $translation) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $translation */
if (!$translation->isDefaultTranslation()) {
$langcode = $translation->language()->getId();
$content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($translation);
if ($content_moderation_state && $content_moderation_state->hasTranslation($langcode)) {
$content_moderation_state->removeTranslation($langcode);
ContentModerationStateEntity::updateOrCreateFromEntity($content_moderation_state);
}
}
}
/**
* Act on entities being assembled before rendering.
*
* This is a hook bridge.
*
* @see hook_entity_view()
* @see EntityFieldManagerInterface::getExtraFields()
*/
@@ -239,46 +254,18 @@ class EntityOperations implements ContainerInjectionInterface {
if ($this->moderationInfo->isLiveRevision($entity)) {
return;
}
// Don't display the moderation form when when:
// - The revision is not translation affected.
// - There are more than one translation languages.
// - The entity has pending revisions.
if (!$this->moderationInfo->isPendingRevisionAllowed($entity)) {
return;
}
$component = $display->getComponent('content_moderation_control');
if ($component) {
$build['content_moderation_control'] = $this->formBuilder->getForm(EntityModerationForm::class, $entity);
$build['content_moderation_control']['#weight'] = $component['weight'];
}
}
/**
* Check if the default revision for the given entity is published.
*
* The default revision is the same as the entity retrieved by "default" from
* the storage handler. If the entity is translated, check if any of the
* translations are published.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being saved.
* @param \Drupal\workflows\WorkflowInterface $workflow
* The workflow being applied to the entity.
*
* @return bool
* TRUE if the default revision is published. FALSE otherwise.
*/
protected function isDefaultRevisionPublished(EntityInterface $entity, WorkflowInterface $workflow) {
$default_revision = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->load($entity->id());
// Ensure we are checking all translations of the default revision.
if ($default_revision instanceof TranslatableInterface && $default_revision->isTranslatable()) {
// Loop through each language that has a translation.
foreach ($default_revision->getTranslationLanguages() as $language) {
// Load the translated revision.
$language_revision = $default_revision->getTranslation($language->getId());
// Return TRUE if a translation with a published state is found.
if ($workflow->getState($language_revision->moderation_state->value)->isPublishedState()) {
return TRUE;
}
}
}
return $workflow->getState($default_revision->moderation_state->value)->isPublishedState();
}
}
@@ -3,12 +3,10 @@
namespace Drupal\content_moderation;
use Drupal\content_moderation\Plugin\Field\ModerationStateFieldItemList;
use Drupal\Core\Config\Entity\ConfigEntityTypeInterface;
use Drupal\Core\Entity\BundleEntityFormBase;
use Drupal\Core\Entity\ContentEntityFormInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
@@ -17,13 +15,10 @@ use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Url;
use Drupal\content_moderation\Entity\Handler\BlockContentModerationHandler;
use Drupal\content_moderation\Entity\Handler\ModerationHandler;
use Drupal\content_moderation\Entity\Handler\NodeModerationHandler;
use Drupal\content_moderation\Form\BundleModerationConfigurationForm;
use Drupal\content_moderation\Routing\EntityModerationRouteProvider;
use Drupal\content_moderation\Routing\EntityTypeModerationRouteProvider;
use Drupal\content_moderation\Entity\Routing\EntityModerationRouteProvider;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -31,6 +26,8 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
*
* This class contains primarily bridged hooks for compile-time or
* cache-clear-time hooks. Runtime hooks should be placed in EntityOperations.
*
* @internal
*/
class EntityTypeInfo implements ContainerInjectionInterface {
@@ -64,6 +61,13 @@ class EntityTypeInfo implements ContainerInjectionInterface {
*/
protected $currentUser;
/**
* The state transition validation service.
*
* @var \Drupal\content_moderation\StateTransitionValidationInterface
*/
protected $validator;
/**
* A keyed array of custom moderation handlers for given entity types.
*
@@ -90,12 +94,13 @@ class EntityTypeInfo implements ContainerInjectionInterface {
* @param \Drupal\Core\Session\AccountInterface $current_user
* Current user.
*/
public function __construct(TranslationInterface $translation, ModerationInformationInterface $moderation_information, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $bundle_info, AccountInterface $current_user) {
public function __construct(TranslationInterface $translation, ModerationInformationInterface $moderation_information, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $bundle_info, AccountInterface $current_user, StateTransitionValidationInterface $validator) {
$this->stringTranslation = $translation;
$this->moderationInfo = $moderation_information;
$this->entityTypeManager = $entity_type_manager;
$this->bundleInfo = $bundle_info;
$this->currentUser = $current_user;
$this->validator = $validator;
}
/**
@@ -107,7 +112,8 @@ class EntityTypeInfo implements ContainerInjectionInterface {
$container->get('content_moderation.moderation_information'),
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('current_user')
$container->get('current_user'),
$container->get('content_moderation.state_transition_validation')
);
}
@@ -115,8 +121,6 @@ class EntityTypeInfo implements ContainerInjectionInterface {
/**
* Adds Moderation configuration to appropriate entity types.
*
* This is an alter hook bridge.
*
* @param EntityTypeInterface[] $entity_types
* The master entity type list to alter.
*
@@ -127,11 +131,6 @@ class EntityTypeInfo implements ContainerInjectionInterface {
// The ContentModerationState entity type should never be moderated.
if ($entity_type->isRevisionable() && $entity_type_id != 'content_moderation_state') {
$entity_types[$entity_type_id] = $this->addModerationToEntityType($entity_type);
// Add additional moderation support to entity types whose bundles are
// managed by a config entity type.
if ($entity_type->getBundleEntityType()) {
$entity_types[$entity_type->getBundleEntityType()] = $this->addModerationToBundleEntityType($entity_types[$entity_type->getBundleEntityType()]);
}
}
}
}
@@ -158,8 +157,6 @@ class EntityTypeInfo implements ContainerInjectionInterface {
$type->setLinkTemplate('latest-version', $type->getLinkTemplate('canonical') . '/latest');
}
// @todo Core forgot to add a direct way to manipulate route_provider, so
// we have to do it the sloppy way for now.
$providers = $type->getRouteProviderClasses() ?: [];
if (empty($providers['moderation'])) {
$providers['moderation'] = EntityModerationRouteProvider::class;
@@ -169,74 +166,9 @@ class EntityTypeInfo implements ContainerInjectionInterface {
return $type;
}
/**
* Configures moderation configuration support on a entity type definition.
*
* That "configuration support" includes a configuration form, a hypermedia
* link, and a route provider to tie it all together. There's also a
* moderation handler for per-entity-type variation.
*
* @param \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $type
* The config entity definition to modify.
*
* @return \Drupal\Core\Config\Entity\ConfigEntityTypeInterface
* The modified config entity definition.
*/
protected function addModerationToBundleEntityType(ConfigEntityTypeInterface $type) {
if ($type->hasLinkTemplate('edit-form') && !$type->hasLinkTemplate('moderation-form')) {
$type->setLinkTemplate('moderation-form', $type->getLinkTemplate('edit-form') . '/moderation');
}
if (!$type->getFormClass('moderation')) {
$type->setFormClass('moderation', BundleModerationConfigurationForm::class);
}
// @todo Core forgot to add a direct way to manipulate route_provider, so
// we have to do it the sloppy way for now.
$providers = $type->getRouteProviderClasses() ?: [];
if (empty($providers['moderation'])) {
$providers['moderation'] = EntityTypeModerationRouteProvider::class;
$type->setHandlerClass('route_provider', $providers);
}
return $type;
}
/**
* Adds an operation on bundles that should have a Moderation form.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity on which to define an operation.
*
* @return array
* An array of operation definitions.
*
* @see hook_entity_operation()
*/
public function entityOperation(EntityInterface $entity) {
$operations = [];
$type = $entity->getEntityType();
$bundle_of = $type->getBundleOf();
if ($this->currentUser->hasPermission('administer content moderation') && $bundle_of &&
$this->moderationInfo->canModerateEntitiesOfEntityType($this->entityTypeManager->getDefinition($bundle_of))
) {
$operations['manage-moderation'] = [
'title' => t('Manage moderation'),
'weight' => 27,
'url' => Url::fromRoute("entity.{$type->id()}.moderation", [$entity->getEntityTypeId() => $entity->id()]),
];
}
return $operations;
}
/**
* Gets the "extra fields" for a bundle.
*
* This is a hook bridge.
*
* @see hook_entity_extra_field_info()
*
* @return array
* A nested array of 'pseudo-field' elements. Each list is nested within the
* following keys: entity type, bundle name, context (either 'form' or
@@ -255,6 +187,8 @@ class EntityTypeInfo implements ContainerInjectionInterface {
* - delete: (optional) String containing markup (normally a link) used as
* the element's 'delete' operation in the administration interface. Only
* for 'form' context.
*
* @see hook_entity_extra_field_info()
*/
public function entityExtraFieldInfo() {
$return = [];
@@ -301,6 +235,8 @@ class EntityTypeInfo implements ContainerInjectionInterface {
*
* @return \Drupal\Core\Field\BaseFieldDefinition[]
* New fields added by moderation state.
*
* @see hook_entity_base_field_info()
*/
public function entityBaseFieldInfo(EntityTypeInterface $entity_type) {
if (!$this->moderationInfo->canModerateEntitiesOfEntityType($entity_type)) {
@@ -313,7 +249,6 @@ class EntityTypeInfo implements ContainerInjectionInterface {
->setDescription(t('The moderation state of this piece of content.'))
->setComputed(TRUE)
->setClass(ModerationStateFieldItemList::class)
->setSetting('target_type', 'moderation_state')
->setDisplayOptions('view', [
'label' => 'hidden',
'region' => 'hidden',
@@ -321,11 +256,11 @@ class EntityTypeInfo implements ContainerInjectionInterface {
])
->setDisplayOptions('form', [
'type' => 'moderation_state_default',
'weight' => 5,
'weight' => 100,
'settings' => [],
])
->addConstraint('ModerationState', [])
->setDisplayConfigurable('form', FALSE)
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', FALSE)
->setReadOnly(FALSE)
->setTranslatable(TRUE);
@@ -348,25 +283,85 @@ class EntityTypeInfo implements ContainerInjectionInterface {
public function formAlter(array &$form, FormStateInterface $form_state, $form_id) {
$form_object = $form_state->getFormObject();
if ($form_object instanceof BundleEntityFormBase) {
$type = $form_object->getEntity()->getEntityType();
if ($this->moderationInfo->canModerateEntitiesOfEntityType($type)) {
$this->entityTypeManager->getHandler($type->getBundleOf(), 'moderation')->enforceRevisionsBundleFormAlter($form, $form_state, $form_id);
$config_entity_type = $form_object->getEntity()->getEntityType();
$bundle_of = $config_entity_type->getBundleOf();
if ($bundle_of
&& ($bundle_of_entity_type = $this->entityTypeManager->getDefinition($bundle_of))
&& $this->moderationInfo->canModerateEntitiesOfEntityType($bundle_of_entity_type)) {
$this->entityTypeManager->getHandler($config_entity_type->getBundleOf(), 'moderation')->enforceRevisionsBundleFormAlter($form, $form_state, $form_id);
}
}
elseif ($form_object instanceof ContentEntityFormInterface) {
elseif ($form_object instanceof ContentEntityFormInterface && in_array($form_object->getOperation(), ['edit', 'default'])) {
$entity = $form_object->getEntity();
if ($this->moderationInfo->isModeratedEntity($entity)) {
$this->entityTypeManager
->getHandler($entity->getEntityTypeId(), 'moderation')
->enforceRevisionsEntityFormAlter($form, $form_state, $form_id);
if (!$this->moderationInfo->isPendingRevisionAllowed($entity)) {
$latest_revision = $this->moderationInfo->getLatestRevision($entity->getEntityTypeId(), $entity->id());
if ($entity->bundle()) {
$bundle_type_id = $entity->getEntityType()->getBundleEntityType();
$bundle = $this->entityTypeManager->getStorage($bundle_type_id)->load($entity->bundle());
$type_label = $bundle->label();
}
else {
$type_label = $entity->getEntityType()->getLabel();
}
$translation = $this->moderationInfo->getAffectedRevisionTranslation($latest_revision);
$args = [
'@type_label' => $type_label,
'@latest_revision_edit_url' => $translation->toUrl('edit-form', ['language' => $translation->language()])->toString(),
'@latest_revision_delete_url' => $translation->toUrl('delete-form', ['language' => $translation->language()])->toString(),
];
$label = $this->t('Unable to save this @type_label.', $args);
$message = $this->t('<a href="@latest_revision_edit_url">Publish</a> or <a href="@latest_revision_delete_url">delete</a> the latest revision to allow all workflow transitions.', $args);
$full_message = $this->t('Unable to save this @type_label. <a href="@latest_revision_edit_url">Publish</a> or <a href="@latest_revision_delete_url">delete</a> the latest revision to allow all workflow transitions.', $args);
drupal_set_message($full_message, 'error');
$form['moderation_state']['#access'] = FALSE;
$form['actions']['#access'] = FALSE;
$form['invalid_transitions'] = [
'label' => [
'#type' => 'item',
'#prefix' => '<strong class="label">',
'#markup' => $label,
'#suffix' => '</strong>',
],
'message' => [
'#type' => 'item',
'#markup' => $message,
],
'#weight' => 999,
'#no_valid_transitions' => TRUE,
];
if ($form['footer']) {
$form['invalid_transitions']['#group'] = 'footer';
}
}
// Submit handler to redirect to the latest version, if available.
$form['actions']['submit']['#submit'][] = [EntityTypeInfo::class, 'bundleFormRedirect'];
// Move the 'moderation_state' field widget to the footer region, if
// available.
if (isset($form['footer'])) {
$form['moderation_state']['#group'] = 'footer';
}
// Duplicate the label of the current moderation state to the meta
// region, if available.
if (isset($form['meta']['published'])) {
$form['meta']['published']['#markup'] = $form['moderation_state']['widget'][0]['current']['#markup'];
}
}
}
}
/**
* Redirect content entity edit forms on save, if there is a forward revision.
* Redirect content entity edit forms on save, if there is a pending revision.
*
* When saving their changes, editors should see those changes displayed on
* the next page.
@@ -381,7 +376,7 @@ class EntityTypeInfo implements ContainerInjectionInterface {
$entity = $form_state->getFormObject()->getEntity();
$moderation_info = \Drupal::getContainer()->get('content_moderation.moderation_information');
if ($moderation_info->hasForwardRevision($entity) && $entity->hasLinkTemplate('latest-version')) {
if ($moderation_info->hasPendingRevision($entity) && $entity->hasLinkTemplate('latest-version')) {
$entity_type_id = $entity->getEntityTypeId();
$form_state->setRedirect("entity.$entity_type_id.latest_version", [$entity_type_id => $entity->id()]);
}
@@ -0,0 +1,99 @@
<?php
namespace Drupal\content_moderation\EventSubscriber;
use Drupal\Core\Config\ConfigImporterEvent;
use Drupal\Core\Config\ConfigImportValidateEventSubscriberBase;
use Drupal\Core\Config\ConfigManagerInterface;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Check moderation states are not being used before updating workflow config.
*/
class ConfigImportSubscriber extends ConfigImportValidateEventSubscriberBase {
/**
* The config manager.
*
* @var \Drupal\Core\Config\ConfigManagerInterface
*/
protected $configManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs the event subscriber.
*
* @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
* The config manager
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(ConfigManagerInterface $config_manager, EntityTypeManagerInterface $entity_type_manager) {
$this->configManager = $config_manager;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public function onConfigImporterValidate(ConfigImporterEvent $event) {
foreach (['update', 'delete'] as $op) {
$unprocessed_configurations = $event->getConfigImporter()->getUnprocessedConfiguration($op);
foreach ($unprocessed_configurations as $unprocessed_configuration) {
if ($workflow = $this->getWorkflow($unprocessed_configuration)) {
if ($op === 'update') {
$original_workflow_config = $event->getConfigImporter()
->getStorageComparer()
->getSourceStorage()
->read($unprocessed_configuration);
$workflow_config = $event->getConfigImporter()
->getStorageComparer()
->getTargetStorage()
->read($unprocessed_configuration);
$diff = array_diff_key($workflow_config['type_settings']['states'], $original_workflow_config['type_settings']['states']);
foreach (array_keys($diff) as $state_id) {
$state = $workflow->getTypePlugin()->getState($state_id);
if ($workflow->getTypePlugin()->workflowStateHasData($workflow, $state)) {
$event->getConfigImporter()->logError($this->t('The moderation state @state_label is being used, but is not in the source storage.', ['@state_label' => $state->label()]));
}
}
}
if ($op === 'delete') {
if ($workflow->getTypePlugin()->workflowHasData($workflow)) {
$event->getConfigImporter()->logError($this->t('The workflow @workflow_label is being used, and cannot be deleted.', ['@workflow_label' => $workflow->label()]));
}
}
}
}
}
}
/**
* Get the workflow entity object from the configuration name.
*
* @param string $config_name
* The configuration object name.
*
* @return \Drupal\workflows\WorkflowInterface|null
* A workflow entity object. NULL if no matching entity is found.
*/
protected function getWorkflow($config_name) {
$entity_type_id = $this->configManager->getEntityTypeIdByName($config_name);
if ($entity_type_id !== 'workflow') {
return;
}
/** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $entity_type */
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
$entity_id = ConfigEntityStorage::getIDFromConfigName($config_name, $entity_type->getConfigPrefix());
return $this->entityTypeManager->getStorage($entity_type_id)->load($entity_id);
}
}
@@ -0,0 +1,207 @@
<?php
namespace Drupal\content_moderation\Form;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseDialogCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\workflows\WorkflowInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* The form for editing entity types associated with a workflow.
*/
class ContentModerationConfigureEntityTypesForm extends FormBase {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity type bundle information service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInformation;
/**
* The workflow entity object.
*
* @var \Drupal\workflows\WorkflowInterface
*/
protected $workflow;
/**
* The entity type definition object.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('content_moderation.moderation_information')
);
}
/**
* {@inheritdoc}
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $bundle_info, ModerationInformationInterface $moderation_information) {
$this->entityTypeManager = $entity_type_manager;
$this->bundleInfo = $bundle_info;
$this->moderationInformation = $moderation_information;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'workflow_type_edit_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, WorkflowInterface $workflow = NULL, $entity_type_id = NULL) {
$this->workflow = $workflow;
try {
$this->entityType = $this->entityTypeManager->getDefinition($entity_type_id);
}
catch (PluginNotFoundException $e) {
throw new NotFoundHttpException();
}
$options = $defaults = [];
foreach ($this->bundleInfo->getBundleInfo($this->entityType->id()) as $bundle_id => $bundle) {
// Check if moderation is enabled for this bundle on any workflow.
$moderation_enabled = $this->moderationInformation->shouldModerateEntitiesOfBundle($this->entityType, $bundle_id);
// Check if moderation is enabled for this bundle on this workflow.
$workflow_moderation_enabled = $this->workflow->getTypePlugin()->appliesToEntityTypeAndBundle($this->entityType->id(), $bundle_id);
// Only show bundles that are not enabled anywhere, or enabled on this
// workflow.
if (!$moderation_enabled || $workflow_moderation_enabled) {
// Add the bundle to the options if it's not enabled on a workflow,
// unless the workflow it's enabled on is this one.
$options[$bundle_id] = [
'type' => $bundle['label'],
];
// Add the bundle to the list of default values if it's enabled on this
// workflow.
$defaults[$bundle_id] = $workflow_moderation_enabled;
}
}
if (!empty($options)) {
$bundles_header = $this->t('All @entity_type types', ['@entity_type' => $this->entityType->getLabel()]);
if ($bundle_entity_type_id = $this->entityType->getBundleEntityType()) {
$bundles_header = $this->t('All @entity_type_plural_label', ['@entity_type_plural_label' => $this->entityTypeManager->getDefinition($bundle_entity_type_id)->getPluralLabel()]);
}
$form['bundles'] = [
'#type' => 'tableselect',
'#header' => [
'type' => $bundles_header,
],
'#options' => $options,
'#default_value' => $defaults,
'#attributes' => ['class' => ['no-highlight']],
];
}
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => $this->t('Save'),
'#ajax' => [
'callback' => [$this, 'ajaxcallback'],
],
];
$form['actions']['cancel'] = [
'#type' => 'button',
'#value' => $this->t('Cancel'),
'#ajax' => [
'callback' => [$this, 'ajaxcallback'],
],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
foreach ($form_state->getValue('bundles') as $bundle_id => $checked) {
if ($checked) {
$this->workflow->getTypePlugin()->addEntityTypeAndBundle($this->entityType->id(), $bundle_id);
}
else {
$this->workflow->getTypePlugin()->removeEntityTypeAndBundle($this->entityType->id(), $bundle_id);
}
}
$this->workflow->save();
}
/**
* Ajax callback to close the modal and update the selected text.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* An ajax response object.
*/
public function ajaxCallback() {
$selected_bundles = [];
foreach ($this->bundleInfo->getBundleInfo($this->entityType->id()) as $bundle_id => $bundle) {
if ($this->workflow->getTypePlugin()->appliesToEntityTypeAndBundle($this->entityType->id(), $bundle_id)) {
$selected_bundles[$bundle_id] = $bundle['label'];
}
}
$selected_bundles_list = [
'#theme' => 'item_list',
'#items' => $selected_bundles,
'#context' => ['list_style' => 'comma-list'],
'#empty' => $this->t('none'),
];
$response = new AjaxResponse();
$response->addCommand(new CloseDialogCommand());
$response->addCommand(new HtmlCommand('#selected-' . $this->entityType->id(), $selected_bundles_list));
return $response;
}
/**
* Route title callback.
*/
public function getTitle(WorkflowInterface $workflow = NULL, $entity_type_id) {
$this->entityType = $this->entityTypeManager->getDefinition($entity_type_id);
$title = $this->t('Select the @entity_type types for the @workflow workflow', ['@entity_type' => $this->entityType->getLabel(), '@workflow' => $workflow->label()]);
if ($bundle_entity_type_id = $this->entityType->getBundleEntityType()) {
$title = $this->t('Select the @entity_type_plural_label for the @workflow workflow', ['@entity_type_plural_label' => $this->entityTypeManager->getDefinition($bundle_entity_type_id)->getPluralLabel(), '@workflow' => $workflow->label()]);
}
return $title;
}
}
@@ -0,0 +1,142 @@
<?php
namespace Drupal\content_moderation\Form;
use Drupal\Component\Serialization\Json;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\workflows\Plugin\WorkflowTypeConfigureFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* The content moderation WorkflowType configuration form.
*
* @see \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration
*/
class ContentModerationConfigureForm extends WorkflowTypeConfigureFormBase implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The moderation info service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* The entity type type bundle info service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* Create an instance of ContentModerationConfigureForm.
*/
public function __construct(EntityTypeManagerInterface $entityTypeManager, ModerationInformationInterface $moderationInformation, EntityTypeBundleInfoInterface $entityTypeBundleInfo) {
$this->entityTypeManager = $entityTypeManager;
$this->moderationInfo = $moderationInformation;
$this->entityTypeBundleInfo = $entityTypeBundleInfo;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('content_moderation.moderation_information'),
$container->get('entity_type.bundle.info')
);
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$workflow = $form_state->getFormObject()->getEntity();
$header = [
'type' => $this->t('Items'),
'operations' => $this->t('Operations')
];
$form['entity_types_container'] = [
'#type' => 'details',
'#title' => $this->t('This workflow applies to:'),
'#open' => TRUE,
];
$form['entity_types_container']['entity_types'] = [
'#type' => 'table',
'#header' => $header,
'#empty' => $this->t('There are no entity types.'),
];
$entity_types = $this->entityTypeManager->getDefinitions();
foreach ($entity_types as $entity_type) {
if (!$this->moderationInfo->canModerateEntitiesOfEntityType($entity_type)) {
continue;
}
$selected_bundles = [];
foreach ($this->entityTypeBundleInfo->getBundleInfo($entity_type->id()) as $bundle_id => $bundle) {
if ($this->workflowType->appliesToEntityTypeAndBundle($entity_type->id(), $bundle_id)) {
$selected_bundles[$bundle_id] = $bundle['label'];
}
}
$selected_bundles_list = [
'#theme' => 'item_list',
'#items' => $selected_bundles,
'#context' => ['list_style' => 'comma-list'],
'#empty' => $this->t('none'),
];
$form['entity_types_container']['entity_types'][$entity_type->id()] = [
'type' => [
'#type' => 'inline_template',
'#template' => '<strong>{{ label }}</strong></br><span id="selected-{{ entity_type_id }}">{{ selected_bundles }}</span>',
'#context' => [
'label' => $this->t('@bundle types', ['@bundle' => $entity_type->getLabel()]),
'entity_type_id' => $entity_type->id(),
'selected_bundles' => $selected_bundles_list,
]
],
'operations' => [
'#type' => 'operations',
'#links' => [
'select' => [
'title' => $this->t('Select'),
'url' => Url::fromRoute('content_moderation.workflow_type_edit_form', ['workflow' => $workflow->id(), 'entity_type_id' => $entity_type->id()]),
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 700,
]),
],
],
],
],
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
// Configuration is updated from modal windows launched from this form, no
// need to change any configuration here.
}
}
@@ -0,0 +1,46 @@
<?php
namespace Drupal\content_moderation\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\workflows\Plugin\WorkflowTypeStateFormBase;
use Drupal\workflows\StateInterface;
/**
* The content moderation state form.
*
* @see \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration
*/
class ContentModerationStateForm extends WorkflowTypeStateFormBase {
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state, StateInterface $state = NULL) {
/** @var \Drupal\content_moderation\ContentModerationState $state */
$state = $form_state->get('state');
$is_required_state = isset($state) ? in_array($state->id(), $this->workflowType->getRequiredStates(), TRUE) : FALSE;
$form = [];
$form['published'] = [
'#type' => 'checkbox',
'#title' => $this->t('Published'),
'#description' => $this->t('When content reaches this state it should be published.'),
'#default_value' => isset($state) ? $state->isPublishedState() : FALSE,
'#disabled' => $is_required_state,
];
$form['default_revision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Default revision'),
'#description' => $this->t('When content reaches this state it should be made the default revision; this is implied for published states.'),
'#default_value' => isset($state) ? $state->isDefaultRevisionState() : FALSE,
'#disabled' => $is_required_state,
// @todo Add form #state to force "make default" on when "published" is
// on for a state.
// @see https://www.drupal.org/node/2645614
];
return $form;
}
}
@@ -71,7 +71,7 @@ class EntityModerationForm extends FormBase {
$transitions = $this->validation->getValidTransitions($entity, $this->currentUser());
// Exclude self-transitions.
$transitions = array_filter($transitions, function(Transition $transition) use ($current_state) {
$transitions = array_filter($transitions, function (Transition $transition) use ($current_state) {
return $transition->to()->id() != $current_state;
});
@@ -88,8 +88,8 @@ class EntityModerationForm extends FormBase {
if ($current_state) {
$form['current'] = [
'#type' => 'item',
'#title' => $this->t('Status'),
'#markup' => $workflow->getState($current_state)->label(),
'#title' => $this->t('Moderation state'),
'#markup' => $workflow->getTypePlugin()->getState($current_state)->label(),
];
}
@@ -98,7 +98,7 @@ class EntityModerationForm extends FormBase {
$form['new_state'] = [
'#type' => 'select',
'#title' => $this->t('Moderate'),
'#title' => $this->t('Change to'),
'#options' => $target_states,
];
@@ -137,10 +137,10 @@ class EntityModerationForm extends FormBase {
drupal_set_message($this->t('The moderation state has been updated.'));
$new_state = $this->moderationInfo->getWorkflowForEntity($entity)->getState($new_state);
$new_state = $this->moderationInfo->getWorkflowForEntity($entity)->getTypePlugin()->getState($new_state);
// The page we're on likely won't be visible if we just set the entity to
// the default state, as we hide that latest-revision tab if there is no
// forward revision. Redirect to the canonical URL instead, since that will
// pending revision. Redirect to the canonical URL instead, since that will
// still exist.
if ($new_state->isDefaultRevisionState()) {
$form_state->setRedirectUrl($entity->toUrl('canonical'));
@@ -7,6 +7,7 @@ use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\TypedData\TranslatableInterface;
/**
* General service for moderation-related questions about Entity API.
@@ -111,6 +112,25 @@ class ModerationInformation implements ModerationInformationInterface {
}
}
/**
* {@inheritdoc}
*/
public function getAffectedRevisionTranslation(ContentEntityInterface $entity) {
foreach ($entity->getTranslationLanguages() as $language) {
$translation = $entity->getTranslation($language->getId());
if (!$translation->isDefaultRevision() && $translation->isRevisionTranslationAffected()) {
return $translation;
}
}
}
/**
* {@inheritdoc}
*/
public function isPendingRevisionAllowed(ContentEntityInterface $entity) {
return !(!$entity->isRevisionTranslationAffected() && count($entity->getTranslationLanguages()) > 1 && $this->hasPendingRevision($entity));
}
/**
* {@inheritdoc}
*/
@@ -121,7 +141,7 @@ class ModerationInformation implements ModerationInformationInterface {
/**
* {@inheritdoc}
*/
public function hasForwardRevision(ContentEntityInterface $entity) {
public function hasPendingRevision(ContentEntityInterface $entity) {
return $this->isModeratedEntity($entity)
&& !($this->getLatestRevisionId($entity->getEntityTypeId(), $entity->id()) == $this->getDefaultRevisionId($entity->getEntityTypeId(), $entity->id()));
}
@@ -134,7 +154,30 @@ class ModerationInformation implements ModerationInformationInterface {
return $this->isLatestRevision($entity)
&& $entity->isDefaultRevision()
&& $entity->moderation_state->value
&& $workflow->getState($entity->moderation_state->value)->isPublishedState();
&& $workflow->getTypePlugin()->getState($entity->moderation_state->value)->isPublishedState();
}
/**
* {@inheritdoc}
*/
public function isDefaultRevisionPublished(ContentEntityInterface $entity) {
$workflow = $this->getWorkflowForEntity($entity);
$default_revision = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId())->load($entity->id());
// Ensure we are checking all translations of the default revision.
if ($default_revision instanceof TranslatableInterface && $default_revision->isTranslatable()) {
// Loop through each language that has a translation.
foreach ($default_revision->getTranslationLanguages() as $language) {
// Load the translated revision.
$language_revision = $default_revision->getTranslation($language->getId());
// Return TRUE if a translation with a published state is found.
if ($workflow->getTypePlugin()->getState($language_revision->moderation_state->value)->isPublishedState()) {
return TRUE;
}
}
}
return $workflow->getTypePlugin()->getState($default_revision->moderation_state->value)->isPublishedState();
}
/**
@@ -89,6 +89,30 @@ interface ModerationInformationInterface {
*/
public function getDefaultRevisionId($entity_type_id, $entity_id);
/**
* Returns the revision translation affected translation of a revision.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The content entity.
*
* @return \Drupal\Core\Entity\ContentEntityInterface
* The revision translation affected translation.
*/
public function getAffectedRevisionTranslation(ContentEntityInterface $entity);
/**
* Determines if pending revisions are allowed.
*
* @internal
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The content entity.
*
* @return bool
* If pending revisions are allowed.
*/
public function isPendingRevisionAllowed(ContentEntityInterface $entity);
/**
* Determines if an entity is a latest revision.
*
@@ -102,15 +126,15 @@ interface ModerationInformationInterface {
public function isLatestRevision(ContentEntityInterface $entity);
/**
* Determines if a forward revision exists for the specified entity.
* Determines if a pending revision exists for the specified entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity which may or may not have a forward revision.
* The entity which may or may not have a pending revision.
*
* @return bool
* TRUE if this entity has forward revisions available, FALSE otherwise.
* TRUE if this entity has pending revisions available, FALSE otherwise.
*/
public function hasForwardRevision(ContentEntityInterface $entity);
public function hasPendingRevision(ContentEntityInterface $entity);
/**
* Determines if an entity is "live".
@@ -126,6 +150,21 @@ interface ModerationInformationInterface {
*/
public function isLiveRevision(ContentEntityInterface $entity);
/**
* Determines if the default revision for the given entity is published.
*
* The default revision is the same as the entity retrieved by "default" from
* the storage handler. If the entity is translated, check if any of the
* translations are published.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being saved.
*
* @return bool
* TRUE if the default revision is published. FALSE otherwise.
*/
public function isDefaultRevisionPublished(ContentEntityInterface $entity);
/**
* Gets the workflow for the given content entity.
*
@@ -28,9 +28,6 @@ class EntityRevisionConverter extends EntityConverter {
* The entity manager, needed by the parent class.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* The moderation info utility service.
*
* @todo: If the parent class is ever cleaned up to use EntityTypeManager
* instead of Entity manager, this method will also need to be adjusted.
*/
public function __construct(EntityManagerInterface $entity_manager, ModerationInformationInterface $moderation_info) {
parent::__construct($entity_manager);
@@ -41,23 +38,23 @@ class EntityRevisionConverter extends EntityConverter {
* {@inheritdoc}
*/
public function applies($definition, $name, Route $route) {
return $this->hasForwardRevisionFlag($definition) || $this->isEditFormPage($route);
return $this->hasPendingRevisionFlag($definition) || $this->isEditFormPage($route);
}
/**
* Determines if the route definition includes a forward-revision flag.
* Determines if the route definition includes a pending revision flag.
*
* This is a custom flag defined by the Content Moderation module to load
* forward revisions rather than the default revision on a given route.
* pending revisions rather than the default revision on a given route.
*
* @param array $definition
* The parameter definition provided in the route options.
*
* @return bool
* TRUE if the forward revision flag is set, FALSE otherwise.
* TRUE if the pending revision flag is set, FALSE otherwise.
*/
protected function hasForwardRevisionFlag(array $definition) {
return (isset($definition['load_forward_revision']) && $definition['load_forward_revision']);
protected function hasPendingRevisionFlag(array $definition) {
return (isset($definition['load_pending_revision']) && $definition['load_pending_revision']);
}
/**
@@ -92,13 +89,12 @@ class EntityRevisionConverter extends EntityConverter {
$entity_type_id = $this->getEntityTypeFromDefaults($definition, $name, $defaults);
$latest_revision = $this->moderationInformation->getLatestRevision($entity_type_id, $value);
// If the entity type is translatable, ensure we return the proper
// translation object for the current context.
if ($latest_revision instanceof EntityInterface && $entity instanceof TranslatableInterface) {
$latest_revision = $this->entityManager->getTranslationFromContext($latest_revision, NULL, ['operation' => 'entity_upcast']);
}
if ($latest_revision instanceof EntityInterface && $latest_revision->isRevisionTranslationAffected()) {
if ($latest_revision instanceof EntityInterface) {
// If the entity type is translatable, ensure we return the proper
// translation object for the current context.
if ($entity instanceof TranslatableInterface) {
$latest_revision = $this->entityManager->getTranslationFromContext($latest_revision, NULL, ['operation' => 'entity_upcast']);
}
$entity = $latest_revision;
}
}
@@ -7,6 +7,8 @@ use Drupal\workflows\Entity\Workflow;
/**
* Defines a class for dynamic permissions based on transitions.
*
* @internal
*/
class Permissions {
@@ -22,11 +24,11 @@ class Permissions {
$permissions = [];
/** @var \Drupal\workflows\WorkflowInterface $workflow */
foreach (Workflow::loadMultipleByType('content_moderation') as $id => $workflow) {
foreach ($workflow->getTransitions() as $transition) {
foreach ($workflow->getTypePlugin()->getTransitions() as $transition) {
$permissions['use ' . $workflow->id() . ' transition ' . $transition->id()] = [
'title' => $this->t('Use %transition transition from %workflow workflow.', [
'%transition' => $transition->label(),
'title' => $this->t('%workflow workflow: Use %transition transition.', [
'%workflow' => $workflow->label(),
'%transition' => $transition->label(),
]),
];
}
@@ -76,19 +76,6 @@ class DynamicLocalTasks extends DeriverBase implements ContainerDeriverInterface
public function getDerivativeDefinitions($base_plugin_definition) {
$this->derivatives = [];
foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
if ($this->moderationInfo->canModerateEntitiesOfEntityType($entity_type)) {
$bundle_id = $entity_type->getBundleEntityType();
$this->derivatives["$bundle_id.moderation_tab"] = [
'route_name' => "entity.$bundle_id.moderation",
'title' => $this->t('Manage moderation'),
// @todo - are we sure they all have an edit_form?
'base_route' => "entity.$bundle_id.edit_form",
'weight' => 30,
] + $base_plugin_definition;
}
}
$latest_version_entities = array_filter($this->entityTypeManager->getDefinitions(), function (EntityTypeInterface $type) {
return $this->moderationInfo->canModerateEntitiesOfEntityType($type) && $type->hasLinkTemplate('latest-version');
});
@@ -61,7 +61,7 @@ class ContentModerationStateFormatter extends FormatterBase implements Container
$workflow = $this->moderationInformation->getWorkflowForEntity($items->getEntity());
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#markup' => $workflow->getState($item->value)->label(),
'#markup' => $workflow->getTypePlugin()->getState($item->value)->label(),
];
}
return $elements;
@@ -2,7 +2,7 @@
namespace Drupal\content_moderation\Plugin\Field\FieldWidget;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\content_moderation\Plugin\Field\ModerationStateFieldItemList;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
@@ -75,7 +75,7 @@ class ModerationStateWidget extends OptionsSelectWidget implements ContainerFact
* @param \Drupal\content_moderation\ModerationInformation $moderation_information
* Moderation information service.
* @param \Drupal\content_moderation\StateTransitionValidation $validator
* Moderation state transition validation service
* Moderation state transition validation service.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, ModerationInformation $moderation_information, StateTransitionValidation $validator) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
@@ -102,113 +102,77 @@ class ModerationStateWidget extends OptionsSelectWidget implements ContainerFact
);
}
/**
* {@inheritdoc}
*/
public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
$entity = $items->getEntity();
if (!$this->moderationInformation->isModeratedEntity($entity)) {
return [];
}
return parent::form($items, $form, $form_state, $get_delta);
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
/** @var ContentEntityInterface $entity */
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $items->getEntity();
if (!$this->moderationInformation->isModeratedEntity($entity)) {
// @todo https://www.drupal.org/node/2779933 write a test for this.
return $element + ['#access' => FALSE];
}
$workflow = $this->moderationInformation->getWorkflowForEntity($entity);
$default = $items->get($delta)->value ? $workflow->getState($items->get($delta)->value) : $workflow->getTypePlugin()->getInitialState($workflow, $entity);
$default = $items->get($delta)->value ? $workflow->getTypePlugin()->getState($items->get($delta)->value) : $workflow->getTypePlugin()->getInitialState($entity);
/** @var \Drupal\workflows\Transition[] $transitions */
$transitions = $this->validator->getValidTransitions($entity, $this->currentUser);
$target_states = [];
$transition_labels = [];
$default_value = NULL;
foreach ($transitions as $transition) {
$target_states[$transition->to()->id()] = $transition->label();
$transition_to_state = $transition->to();
$transition_labels[$transition_to_state->id()] = $transition_to_state->label();
}
// @todo https://www.drupal.org/node/2779933 write a test for this.
$element += [
'#access' => FALSE,
'#type' => 'select',
'#options' => $target_states,
'#default_value' => $default->id(),
'#published' => $default->isPublishedState(),
'#key_column' => $this->column,
'#type' => 'container',
'current' => [
'#type' => 'item',
'#title' => $this->t('Current state'),
'#markup' => $default->label(),
'#access' => !$entity->isNew(),
'#wrapper_attributes' => [
'class' => ['container-inline'],
],
],
'state' => [
'#type' => 'select',
'#title' => $entity->isNew() ? $this->t('Save as') : $this->t('Change to'),
'#key_column' => $this->column,
'#options' => $transition_labels,
'#default_value' => $default_value,
'#access' => !empty($transition_labels),
'#wrapper_attributes' => [
'class' => ['container-inline'],
],
],
];
$element['#element_validate'][] = [get_class($this), 'validateElement'];
// Use the dropbutton.
$element['#process'][] = [get_called_class(), 'processActions'];
return $element;
}
/**
* Entity builder updating the node moderation state with the submitted value.
*
* @param string $entity_type_id
* The entity type identifier.
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity updated with the submitted values.
* @param array $form
* The complete form array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public static function updateStatus($entity_type_id, ContentEntityInterface $entity, array $form, FormStateInterface $form_state) {
$element = $form_state->getTriggeringElement();
if (isset($element['#moderation_state'])) {
$entity->moderation_state->value = $element['#moderation_state'];
}
}
/**
* Process callback to alter action buttons.
*/
public static function processActions($element, FormStateInterface $form_state, array &$form) {
// We'll steal most of the button configuration from the default submit
// button. However, NodeForm also hides that button for admins (as it adds
// its own, too), so we have to restore it.
$default_button = $form['actions']['submit'];
$default_button['#access'] = TRUE;
// Add a custom button for each transition we're allowing. The #dropbutton
// property tells FAPI to cluster them all together into a single widget.
$options = $element['#options'];
$entity = $form_state->getFormObject()->getEntity();
$translatable = !$entity->isNew() && $entity->isTranslatable();
foreach ($options as $id => $label) {
$button = [
'#dropbutton' => 'save',
'#moderation_state' => $id,
'#weight' => -10,
];
$button['#value'] = $translatable
? t('Save and @transition (this translation)', ['@transition' => $label])
: t('Save and @transition', ['@transition' => $label]);
$form['actions']['moderation_state_' . $id] = $button + $default_button;
}
// Hide the default buttons, including the specialty ones added by
// NodeForm.
foreach (['publish', 'unpublish', 'submit'] as $key) {
$form['actions'][$key]['#access'] = FALSE;
unset($form['actions'][$key]['#dropbutton']);
}
// Setup a callback to translate the button selection back into field
// widget, so that it will get saved properly.
$form['#entity_builders']['update_moderation_state'] = [get_called_class(), 'updateStatus'];
return $element;
}
/**
* {@inheritdoc}
*/
public static function validateElement(array $element, FormStateInterface $form_state) {
$form_state->setValueForElement($element, [$element['state']['#key_column'] => $element['state']['#value']]);
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return $field_definition->getName() === 'moderation_state';
return is_a($field_definition->getClass(), ModerationStateFieldItemList::class, TRUE);
}
}
@@ -3,6 +3,7 @@
namespace Drupal\content_moderation\Plugin\Field;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Field\FieldItemList;
/**
@@ -38,7 +39,7 @@ class ModerationStateFieldItemList extends FieldItemList {
// the node type form creates a fake Node entity to get default values.
// @see \Drupal\node\NodeTypeForm::form()
$workflow = $moderation_info->getWorkFlowForEntity($entity);
return $workflow ? $workflow->getTypePlugin()->getInitialState($workflow, $entity)->id() : NULL;
return $workflow ? $workflow->getTypePlugin()->getInitialState($entity)->id() : NULL;
}
/**
@@ -47,7 +48,7 @@ class ModerationStateFieldItemList extends FieldItemList {
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity the content moderation state entity will be loaded from.
*
* @return \Drupal\content_moderation\ContentModerationStateInterface|null
* @return \Drupal\content_moderation\Entity\ContentModerationStateInterface|null
* The content_moderation_state revision or FALSE if none exists.
*/
protected function loadContentModerationStateRevision(ContentEntityInterface $entity) {
@@ -68,7 +69,7 @@ class ModerationStateFieldItemList extends FieldItemList {
return NULL;
}
/** @var \Drupal\content_moderation\ContentModerationStateInterface $content_moderation_state */
/** @var \Drupal\content_moderation\Entity\ContentModerationStateInterface $content_moderation_state */
$content_moderation_state = $content_moderation_storage->loadRevision(key($revisions));
if ($entity->getEntityType()->hasKey('langcode')) {
$langcode = $entity->language()->getId();
@@ -117,4 +118,60 @@ class ModerationStateFieldItemList extends FieldItemList {
}
}
/**
* {@inheritdoc}
*/
public function onChange($delta) {
$this->updateModeratedEntity($this->list[$delta]->value);
parent::onChange($delta);
}
/**
* {@inheritdoc}
*/
public function setValue($values, $notify = TRUE) {
parent::setValue($values, $notify);
if (isset($this->list[0])) {
$this->updateModeratedEntity($this->list[0]->value);
}
}
/**
* Updates the default revision flag and the publishing status of the entity.
*
* @param string $moderation_state_id
* The ID of the new moderation state.
*/
protected function updateModeratedEntity($moderation_state_id) {
$entity = $this->getEntity();
/** @var \Drupal\content_moderation\ModerationInformationInterface $content_moderation_info */
$content_moderation_info = \Drupal::service('content_moderation.moderation_information');
$workflow = $content_moderation_info->getWorkflowForEntity($entity);
// Change the entity's default revision flag and the publishing status only
// if the new workflow state is a valid one.
if ($workflow->getTypePlugin()->hasState($moderation_state_id)) {
/** @var \Drupal\content_moderation\ContentModerationState $current_state */
$current_state = $workflow->getTypePlugin()->getState($moderation_state_id);
// This entity is default if it is new, a new translation, the default
// revision state, or the default revision is not published.
$update_default_revision = $entity->isNew()
|| $entity->isNewTranslation()
|| $current_state->isDefaultRevisionState()
|| !$content_moderation_info->isDefaultRevisionPublished($entity);
$entity->isDefaultRevision($update_default_revision);
// Update publishing status if it can be updated and if it needs updating.
$published_state = $current_state->isPublishedState();
if (($entity instanceof EntityPublishedInterface) && $entity->isPublished() !== $published_state) {
$published_state ? $entity->setPublished() : $entity->setUnpublished();
}
}
}
}
@@ -15,5 +15,6 @@ use Symfony\Component\Validator\Constraint;
class ModerationStateConstraint extends Constraint {
public $message = 'Invalid state transition from %from to %to';
public $invalidStateMessage = 'State %state does not exist on %workflow workflow';
}
@@ -6,7 +6,6 @@ use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\content_moderation\StateTransitionValidation;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
@@ -16,13 +15,6 @@ use Symfony\Component\Validator\ConstraintValidator;
*/
class ModerationStateConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The state transition validation.
*
* @var \Drupal\content_moderation\StateTransitionValidation
*/
protected $validation;
/**
* The entity type manager.
*
@@ -42,13 +34,10 @@ class ModerationStateConstraintValidator extends ConstraintValidator implements
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\content_moderation\StateTransitionValidation $validation
* The state transition validation.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_information
* The moderation information.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, StateTransitionValidation $validation, ModerationInformationInterface $moderation_information) {
$this->validation = $validation;
public function __construct(EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_information) {
$this->entityTypeManager = $entity_type_manager;
$this->moderationInformation = $moderation_information;
}
@@ -59,7 +48,6 @@ class ModerationStateConstraintValidator extends ConstraintValidator implements
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('content_moderation.state_transition_validation'),
$container->get('content_moderation.moderation_information')
);
}
@@ -68,7 +56,7 @@ class ModerationStateConstraintValidator extends ConstraintValidator implements
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
/** @var \Drupal\Core\Entity\EntityInterface $entity */
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $value->getEntity();
// Ignore entities that are not subject to moderation anyway.
@@ -76,29 +64,43 @@ class ModerationStateConstraintValidator extends ConstraintValidator implements
return;
}
// Ignore entities that are being created for the first time.
if ($entity->isNew()) {
return;
}
// Ignore entities that are being moderated for the first time, such as
// when they existed before moderation was enabled for this entity type.
if ($this->isFirstTimeModeration($entity)) {
return;
}
$original_entity = $this->moderationInformation->getLatestRevision($entity->getEntityTypeId(), $entity->id());
if (!$entity->isDefaultTranslation() && $original_entity->hasTranslation($entity->language()->getId())) {
$original_entity = $original_entity->getTranslation($entity->language()->getId());
}
$workflow = $this->moderationInformation->getWorkflowForEntity($entity);
$new_state = $workflow->getState($entity->moderation_state->value) ?: $workflow->getInitialState();
$original_state = $workflow->getState($original_entity->moderation_state->value);
// @todo - what if $new_state references something that does not exist or
// is null.
if (!$original_state->canTransitionTo($new_state->id())) {
$this->context->addViolation($constraint->message, ['%from' => $original_state->label(), '%to' => $new_state->label()]);
if (!$workflow->getTypePlugin()->hasState($entity->moderation_state->value)) {
// If the state we are transitioning to doesn't exist, we can't validate
// the transitions for this entity further.
$this->context->addViolation($constraint->invalidStateMessage, [
'%state' => $entity->moderation_state->value,
'%workflow' => $workflow->label(),
]);
return;
}
// If a new state is being set and there is an existing state, validate
// there is a valid transition between them.
if (!$entity->isNew() && !$this->isFirstTimeModeration($entity)) {
$original_entity = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadRevision($entity->getLoadedRevisionId());
if (!$entity->isDefaultTranslation() && $original_entity->hasTranslation($entity->language()->getId())) {
$original_entity = $original_entity->getTranslation($entity->language()->getId());
}
// If the state of the original entity doesn't exist on the workflow,
// we cannot do any further validation of transitions, because none will
// be setup for a state that doesn't exist. Instead allow any state to
// take its place.
if (!$workflow->getTypePlugin()->hasState($original_entity->moderation_state->value)) {
return;
}
$new_state = $workflow->getTypePlugin()->getState($entity->moderation_state->value);
$original_state = $workflow->getTypePlugin()->getState($original_entity->moderation_state->value);
if (!$original_state->canTransitionTo($new_state->id())) {
$this->context->addViolation($constraint->message, [
'%from' => $original_state->label(),
'%to' => $new_state->label()
]);
}
}
}
@@ -2,12 +2,12 @@
namespace Drupal\content_moderation\Plugin\WorkflowType;
use Drupal\Core\Access\AccessResult;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\content_moderation\ContentModerationState;
use Drupal\workflows\Plugin\WorkflowTypeBase;
@@ -25,9 +25,13 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
* "draft",
* "published",
* },
* forms = {
* "configure" = "\Drupal\content_moderation\Form\ContentModerationConfigureForm",
* "state" = "\Drupal\content_moderation\Form\ContentModerationStateForm"
* },
* )
*/
class ContentModeration extends WorkflowTypeBase implements ContainerFactoryPluginInterface {
class ContentModeration extends WorkflowTypeBase implements ContentModerationInterface, ContainerFactoryPluginInterface {
use StringTranslationTrait;
@@ -39,11 +43,38 @@ class ContentModeration extends WorkflowTypeBase implements ContainerFactoryPlug
protected $entityTypeManager;
/**
* Creates an instance of the ContentModeration WorkflowType plugin.
* The entity type bundle info service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
protected $entityTypeBundleInfo;
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* Constructs a ContentModeration object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* Moderation information service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, ModerationInformationInterface $moderation_info) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
$this->moderationInfo = $moderation_info;
}
/**
@@ -54,39 +85,18 @@ class ContentModeration extends WorkflowTypeBase implements ContainerFactoryPlug
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('content_moderation.moderation_information')
);
}
/**
* {@inheritdoc}
*/
public function initializeWorkflow(WorkflowInterface $workflow) {
$workflow
->addState('draft', $this->t('Draft'))
->setStateWeight('draft', -5)
->addState('published', $this->t('Published'))
->setStateWeight('published', 0)
->addTransition('create_new_draft', $this->t('Create New Draft'), ['draft', 'published'], 'draft')
->addTransition('publish', $this->t('Publish'), ['draft', 'published'], 'published');
return $workflow;
}
/**
* {@inheritdoc}
*/
public function checkWorkflowAccess(WorkflowInterface $entity, $operation, AccountInterface $account) {
if ($operation === 'view') {
return AccessResult::allowedIfHasPermission($account, 'view content moderation');
}
return parent::checkWorkflowAccess($entity, $operation, $account);
}
/**
* {@inheritdoc}
*/
public function decorateState(StateInterface $state) {
if (isset($this->configuration['states'][$state->id()])) {
public function getState($state_id) {
$state = parent::getState($state_id);
if (isset($this->configuration['states'][$state->id()]['published']) && isset($this->configuration['states'][$state->id()]['default_revision'])) {
$state = new ContentModerationState($state, $this->configuration['states'][$state->id()]['published'], $this->configuration['states'][$state->id()]['default_revision']);
}
else {
@@ -98,81 +108,60 @@ class ContentModeration extends WorkflowTypeBase implements ContainerFactoryPlug
/**
* {@inheritdoc}
*/
public function buildStateConfigurationForm(FormStateInterface $form_state, WorkflowInterface $workflow, StateInterface $state = NULL) {
/** @var \Drupal\content_moderation\ContentModerationState $state */
$is_required_state = isset($state) ? in_array($state->id(), $this->getRequiredStates(), TRUE) : FALSE;
$form = [];
$form['published'] = [
'#type' => 'checkbox',
'#title' => $this->t('Published'),
'#description' => $this->t('When content reaches this state it should be published.'),
'#default_value' => isset($state) ? $state->isPublishedState() : FALSE,
'#disabled' => $is_required_state,
];
$form['default_revision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Default revision'),
'#description' => $this->t('When content reaches this state it should be made the default revision; this is implied for published states.'),
'#default_value' => isset($state) ? $state->isDefaultRevisionState() : FALSE,
'#disabled' => $is_required_state,
// @todo Add form #state to force "make default" on when "published" is
// on for a state.
// @see https://www.drupal.org/node/2645614
];
return $form;
public function workflowHasData(WorkflowInterface $workflow) {
return (bool) $this->entityTypeManager
->getStorage('content_moderation_state')
->getQuery()
->condition('workflow', $workflow->id())
->count()
->accessCheck(FALSE)
->range(0, 1)
->execute();
}
/**
* Gets the entity types the workflow is applied to.
*
* @return string[]
* The entity types the workflow is applied to.
* {@inheritdoc}
*/
public function workflowStateHasData(WorkflowInterface $workflow, StateInterface $state) {
return (bool) $this->entityTypeManager
->getStorage('content_moderation_state')
->getQuery()
->condition('workflow', $workflow->id())
->condition('moderation_state', $state->id())
->count()
->accessCheck(FALSE)
->range(0, 1)
->execute();
}
/**
* {@inheritdoc}
*/
public function getEntityTypes() {
return array_keys($this->configuration['entity_types']);
}
/**
* Gets any bundles the workflow is applied to for the given entity type.
*
* @param string $entity_type_id
* The entity type ID to get the bundles for.
*
* @return string[]
* The bundles of the entity type the workflow is applied to or an empty
* array if the entity type is not applied to the workflow.
* {@inheritdoc}
*/
public function getBundlesForEntityType($entity_type_id) {
return isset($this->configuration['entity_types'][$entity_type_id]) ? $this->configuration['entity_types'][$entity_type_id] : [];
}
/**
* Checks if the workflow applies to the supplied entity type and bundle.
*
* @param string $entity_type_id
* The entity type ID to check.
* @param string $bundle_id
* The bundle ID to check.
*
* @return bool
* TRUE if the workflow applies to the supplied entity type ID and bundle
* ID. FALSE if not.
* {@inheritdoc}
*/
public function appliesToEntityTypeAndBundle($entity_type_id, $bundle_id) {
return in_array($bundle_id, $this->getBundlesForEntityType($entity_type_id), TRUE);
}
/**
* Removes an entity type ID / bundle ID from the workflow.
*
* @param string $entity_type_id
* The entity type ID to remove.
* @param string $bundle_id
* The bundle ID to remove.
* {@inheritdoc}
*/
public function removeEntityTypeAndBundle($entity_type_id, $bundle_id) {
if (!isset($this->configuration['entity_types'][$entity_type_id])) {
return;
}
$key = array_search($bundle_id, $this->configuration['entity_types'][$entity_type_id], TRUE);
if ($key !== FALSE) {
unset($this->configuration['entity_types'][$entity_type_id][$key]);
@@ -186,14 +175,7 @@ class ContentModeration extends WorkflowTypeBase implements ContainerFactoryPlug
}
/**
* Add an entity type ID / bundle ID to the workflow.
*
* @param string $entity_type_id
* The entity type ID to add. It is responsibility of the caller to provide
* a valid entity type ID.
* @param string $bundle_id
* The bundle ID to add. It is responsibility of the caller to provide a
* valid bundle ID.
* {@inheritdoc}
*/
public function addEntityTypeAndBundle($entity_type_id, $bundle_id) {
if (!$this->appliesToEntityTypeAndBundle($entity_type_id, $bundle_id)) {
@@ -204,19 +186,42 @@ class ContentModeration extends WorkflowTypeBase implements ContainerFactoryPlug
}
/**
* {@inheritDoc}
* {@inheritdoc}
*/
public function defaultConfiguration() {
// This plugin does not store anything per transition.
return [
'states' => [
'draft' => [
'label' => 'Draft',
'published' => FALSE,
'default_revision' => FALSE,
'weight' => 0,
],
'published' => [
'label' => 'Published',
'published' => TRUE,
'default_revision' => TRUE,
'weight' => 1,
],
],
'transitions' => [
'create_new_draft' => [
'label' => 'Create New Draft',
'to' => 'draft',
'weight' => 0,
'from' => [
'draft',
'published',
],
],
'publish' => [
'label' => 'Publish',
'to' => 'published',
'weight' => 1,
'from' => [
'draft',
'published',
],
],
],
'entity_types' => [],
@@ -293,11 +298,19 @@ class ContentModeration extends WorkflowTypeBase implements ContainerFactoryPlug
/**
* {@inheritdoc}
*/
public function getInitialState(WorkflowInterface $workflow, $entity = NULL) {
if ($entity instanceof EntityPublishedInterface) {
return $workflow->getState($entity->isPublished() && !$entity->isNew() ? 'published' : 'draft');
public function getInitialState($entity = NULL) {
// Workflows are not tied to entities, but Content Moderation adds the
// relationship between Workflows and entities. Content Moderation needs the
// entity object to be able to determine the initial state based on
// publishing status.
if (!($entity instanceof ContentEntityInterface)) {
throw new \InvalidArgumentException('A content entity object must be supplied.');
}
return parent::getInitialState($workflow);
if ($entity instanceof EntityPublishedInterface) {
return $this->getState($entity->isPublished() && !$entity->isNew() ? 'published' : 'draft');
}
// Workflows determines the initial state for non-publishable entities.
return parent::getInitialState();
}
}
@@ -0,0 +1,77 @@
<?php
namespace Drupal\content_moderation\Plugin\WorkflowType;
use Drupal\workflows\WorkflowTypeInterface;
/**
* Interface for ContentModeration WorkflowType plugin.
*/
interface ContentModerationInterface extends WorkflowTypeInterface {
/**
* Gets the entity types the workflow is applied to.
*
* @return string[]
* The entity types the workflow is applied to.
*/
public function getEntityTypes();
/**
* Gets any bundles the workflow is applied to for the given entity type.
*
* @param string $entity_type_id
* The entity type ID to get the bundles for.
*
* @return string[]
* The bundles of the entity type the workflow is applied to or an empty
* array if the entity type is not applied to the workflow.
*/
public function getBundlesForEntityType($entity_type_id);
/**
* Checks if the workflow applies to the supplied entity type and bundle.
*
* @param string $entity_type_id
* The entity type ID to check.
* @param string $bundle_id
* The bundle ID to check.
*
* @return bool
* TRUE if the workflow applies to the supplied entity type ID and bundle
* ID. FALSE if not.
*/
public function appliesToEntityTypeAndBundle($entity_type_id, $bundle_id);
/**
* Removes an entity type ID / bundle ID from the workflow.
*
* @param string $entity_type_id
* The entity type ID to remove.
* @param string $bundle_id
* The bundle ID to remove.
*/
public function removeEntityTypeAndBundle($entity_type_id, $bundle_id);
/**
* Add an entity type ID / bundle ID to the workflow.
*
* @param string $entity_type_id
* The entity type ID to add. It is responsibility of the caller to provide
* a valid entity type ID.
* @param string $bundle_id
* The bundle ID to add. It is responsibility of the caller to provide a
* valid bundle ID.
*/
public function addEntityTypeAndBundle($entity_type_id, $bundle_id);
/**
* {@inheritdoc}
*
* @param $entity
* Content Moderation uses this parameter to determine the initial state
* based on publishing status.
*/
public function getInitialState($entity = NULL);
}
@@ -40,9 +40,9 @@ class StateTransitionValidation implements StateTransitionValidationInterface {
*/
public function getValidTransitions(ContentEntityInterface $entity, AccountInterface $user) {
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
$current_state = $entity->moderation_state->value ? $workflow->getState($entity->moderation_state->value) : $workflow->getTypePlugin()->getInitialState($workflow, $entity);
$current_state = $entity->moderation_state->value ? $workflow->getTypePlugin()->getState($entity->moderation_state->value) : $workflow->getTypePlugin()->getInitialState($entity);
return array_filter($current_state->getTransitions(), function(Transition $transition) use ($workflow, $user) {
return array_filter($current_state->getTransitions(), function (Transition $transition) use ($workflow, $user) {
return $user->hasPermission('use ' . $workflow->id() . ' transition ' . $transition->id());
});
}
@@ -8,6 +8,8 @@ use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Provides the content_moderation views integration.
*
* @internal
*/
class ViewsData {
@@ -49,137 +51,13 @@ class ViewsData {
public function getViewsData() {
$data = [];
$data['content_revision_tracker']['table']['group'] = $this->t('Content moderation (tracker)');
$data['content_revision_tracker']['entity_type'] = [
'title' => $this->t('Entity type'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'string',
],
'argument' => [
'id' => 'string',
],
'sort' => [
'id' => 'standard',
],
];
$data['content_revision_tracker']['entity_id'] = [
'title' => $this->t('Entity ID'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'numeric',
],
'argument' => [
'id' => 'numeric',
],
'sort' => [
'id' => 'standard',
],
];
$data['content_revision_tracker']['langcode'] = [
'title' => $this->t('Entity language'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'language',
],
'argument' => [
'id' => 'language',
],
'sort' => [
'id' => 'standard',
],
];
$data['content_revision_tracker']['revision_id'] = [
'title' => $this->t('Latest revision ID'),
'field' => [
'id' => 'standard',
],
'filter' => [
'id' => 'numeric',
],
'argument' => [
'id' => 'numeric',
],
'sort' => [
'id' => 'standard',
],
];
$entity_types_with_moderation = array_filter($this->entityTypeManager->getDefinitions(), function (EntityTypeInterface $type) {
return $this->moderationInformation->canModerateEntitiesOfEntityType($type);
});
// Add a join for each entity type to the content_revision_tracker table.
foreach ($entity_types_with_moderation as $entity_type_id => $entity_type) {
/** @var \Drupal\views\EntityViewsDataInterface $views_data */
// We need the views_data handler in order to get the table name later.
if ($this->entityTypeManager->hasHandler($entity_type_id, 'views_data') && $views_data = $this->entityTypeManager->getHandler($entity_type_id, 'views_data')) {
// Add a join from the entity base table to the revision tracker table.
$base_table = $views_data->getViewsTableForEntityType($entity_type);
$data['content_revision_tracker']['table']['join'][$base_table] = [
'left_field' => $entity_type->getKey('id'),
'field' => 'entity_id',
'extra' => [
[
'field' => 'entity_type',
'value' => $entity_type_id,
],
],
];
// Some entity types might not be translatable.
if ($entity_type->hasKey('langcode')) {
$data['content_revision_tracker']['table']['join'][$base_table]['extra'][] = [
'field' => 'langcode',
'left_field' => $entity_type->getKey('langcode'),
'operation' => '=',
];
}
// Add a relationship between the revision tracker table to the latest
// revision on the entity revision table.
$data['content_revision_tracker']['latest_revision__' . $entity_type_id] = [
'title' => $this->t('@label latest revision', ['@label' => $entity_type->getLabel()]),
'group' => $this->t('@label revision', ['@label' => $entity_type->getLabel()]),
'relationship' => [
'id' => 'standard',
'label' => $this->t('@label latest revision', ['@label' => $entity_type->getLabel()]),
'base' => $this->getRevisionViewsTableForEntityType($entity_type),
'base field' => $entity_type->getKey('revision'),
'relationship field' => 'revision_id',
'extra' => [
[
'left_field' => 'entity_type',
'value' => $entity_type_id,
],
],
],
];
// Some entity types might not be translatable.
if ($entity_type->hasKey('langcode')) {
$data['content_revision_tracker']['latest_revision__' . $entity_type_id]['relationship']['extra'][] = [
'left_field' => 'langcode',
'field' => $entity_type->getKey('langcode'),
'operation' => '=',
];
}
}
}
// Provides a relationship from moderated entity to its moderation state
// entity.
$content_moderation_state_entity_type = \Drupal::entityTypeManager()->getDefinition('content_moderation_state');
$content_moderation_state_entity_type = $this->entityTypeManager->getDefinition('content_moderation_state');
$content_moderation_state_entity_base_table = $content_moderation_state_entity_type->getDataTable() ?: $content_moderation_state_entity_type->getBaseTable();
$content_moderation_state_entity_revision_base_table = $content_moderation_state_entity_type->getRevisionDataTable() ?: $content_moderation_state_entity_type->getRevisionTable();
foreach ($entity_types_with_moderation as $entity_type_id => $entity_type) {
@@ -226,39 +104,4 @@ class ViewsData {
return $data;
}
/**
* Alters the table and field information from hook_views_data().
*
* @param array $data
* An array of all information about Views tables and fields, collected from
* hook_views_data(), passed by reference.
*
* @see hook_views_data()
*/
public function alterViewsData(array &$data) {
$entity_types_with_moderation = array_filter($this->entityTypeManager->getDefinitions(), function (EntityTypeInterface $type) {
return $this->moderationInformation->canModerateEntitiesOfEntityType($type);
});
foreach ($entity_types_with_moderation as $type) {
$data[$type->getRevisionTable()]['latest_revision'] = [
'title' => t('Is Latest Revision'),
'help' => t('Restrict the view to only revisions that are the latest revision of their entity.'),
'filter' => ['id' => 'latest_revision'],
];
}
}
/**
* Gets the table of an entity type to be used as revision table in views.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return string
* The revision base table.
*/
protected function getRevisionViewsTableForEntityType(EntityTypeInterface $entity_type) {
return $entity_type->getRevisionDataTable() ?: $entity_type->getRevisionTable();
}
}
@@ -8,8 +8,8 @@ dependencies:
- content_moderation
- node
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
# Information added by Drupal.org packaging script on 2017-11-03
version: '8.4.2'
core: '8.x'
project: 'drupal'
datestamp: 1502903957
datestamp: 1509719929
@@ -9,8 +9,8 @@ dependencies:
- node
- views
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
# Information added by Drupal.org packaging script on 2017-11-03
version: '8.4.2'
core: '8.x'
project: 'drupal'
datestamp: 1502903957
datestamp: 1509719929
@@ -36,19 +36,27 @@ class ContentModerationWorkflowTypeTest extends BrowserTestBase {
* Test creating a new workflow using the content moderation plugin.
*/
public function testNewWorkflow() {
$types[] = $this->createContentType();
$types[] = $this->createContentType();
$types[] = $this->createContentType();
$entity_bundle_info = \Drupal::service('entity_type.bundle.info');
$this->drupalPostForm('admin/config/workflow/workflows/add', [
'label' => 'Test Workflow',
'id' => 'test_workflow',
'label' => 'Test',
'id' => 'test',
'workflow_type' => 'content_moderation',
], 'Save');
$session = $this->assertSession();
// Make sure the test workflow includes the default states and transitions.
$this->assertSession()->pageTextContains('Draft');
$this->assertSession()->pageTextContains('Published');
$this->assertSession()->pageTextContains('Create New Draft');
$this->assertSession()->pageTextContains('Publish');
$session->pageTextContains('Draft');
$session->pageTextContains('Published');
$session->pageTextContains('Create New Draft');
$session->pageTextContains('Publish');
$session->linkByHrefNotExists('/admin/config/workflow/workflows/manage/test/state/draft/delete');
$session->linkByHrefNotExists('/admin/config/workflow/workflows/manage/test/state/published/delete');
// Ensure after a workflow is created, the bundle information can be
// refreshed.
@@ -59,20 +67,35 @@ class ContentModerationWorkflowTypeTest extends BrowserTestBase {
$this->submitForm([
'label' => 'Test State',
'id' => 'test_state',
'type_settings[content_moderation][published]' => TRUE,
'type_settings[content_moderation][default_revision]' => FALSE,
'type_settings[published]' => TRUE,
'type_settings[default_revision]' => FALSE,
], 'Save');
$this->assertSession()->pageTextContains('Created Test State state.');
$session->pageTextContains('Created Test State state.');
$session->linkByHrefExists('/admin/config/workflow/workflows/manage/test/state/test_state/delete');
// Check there is a link to delete a default transition.
$session->linkByHrefExists('/admin/config/workflow/workflows/manage/test/transition/publish/delete');
// Delete the transition.
$this->drupalGet('/admin/config/workflow/workflows/manage/test/transition/publish/delete');
$this->submitForm([], 'Delete');
// The link to delete the transition should now be gone.
$session->linkByHrefNotExists('/admin/config/workflow/workflows/manage/test/transition/publish/delete');
// Ensure that the published settings cannot be changed.
$this->drupalGet('admin/config/workflow/workflows/manage/test_workflow/state/published');
$this->assertSession()->fieldDisabled('type_settings[content_moderation][published]');
$this->assertSession()->fieldDisabled('type_settings[content_moderation][default_revision]');
$this->drupalGet('admin/config/workflow/workflows/manage/test/state/published');
$session->fieldDisabled('type_settings[published]');
$session->fieldDisabled('type_settings[default_revision]');
// Ensure that the draft settings cannot be changed.
$this->drupalGet('admin/config/workflow/workflows/manage/test_workflow/state/draft');
$this->assertSession()->fieldDisabled('type_settings[content_moderation][published]');
$this->assertSession()->fieldDisabled('type_settings[content_moderation][default_revision]');
$this->drupalGet('admin/config/workflow/workflows/manage/test/state/draft');
$session->fieldDisabled('type_settings[published]');
$session->fieldDisabled('type_settings[default_revision]');
$this->drupalGet('admin/config/workflow/workflows/manage/test/type/node');
$session->pageTextContains('Select the content type entities for the Test workflow');
foreach ($types as $type) {
$session->pageTextContains($type->label());
}
}
}
@@ -11,6 +11,18 @@ use Drupal\workflows\Entity\Workflow;
*/
class ModerationFormTest extends ModerationStateTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'node',
'content_moderation',
'locale',
'content_translation',
];
/**
* {@inheritdoc}
*/
@@ -24,9 +36,7 @@ class ModerationFormTest extends ModerationStateTestBase {
/**
* Tests the moderation form that shows on the latest version page.
*
* The latest version page only shows if there is a forward revision. There
* is only a forward revision if a draft revision is created on a node where
* the default revision is not a published moderation state.
* The latest version page only shows if there is a pending revision.
*
* @see \Drupal\content_moderation\EntityOperations
* @see \Drupal\Tests\content_moderation\Functional\ModerationStateBlockTest::testCustomBlockModeration
@@ -36,7 +46,8 @@ class ModerationFormTest extends ModerationStateTestBase {
$this->drupalPostForm('node/add/moderated_content', [
'title[0][value]' => 'Some moderated content',
'body[0][value]' => 'First version of the content.',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
$node = $this->drupalGetNodeByTitle('Some moderated content');
$canonical_path = sprintf('node/%d', $node->id());
@@ -51,7 +62,7 @@ class ModerationFormTest extends ModerationStateTestBase {
$this->assertResponse(200);
$this->assertField('edit-new-state', 'The node view page has a moderation form.');
// The latest version page should not show, because there is no forward
// The latest version page should not show, because there is no pending
// revision.
$this->drupalGet($latest_version_path);
$this->assertResponse(403);
@@ -59,7 +70,8 @@ class ModerationFormTest extends ModerationStateTestBase {
// Update the draft.
$this->drupalPostForm($edit_path, [
'body[0][value]' => 'Second version of the content.',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
// The canonical view should have a moderation form, because it is not the
// live revision.
@@ -68,14 +80,15 @@ class ModerationFormTest extends ModerationStateTestBase {
$this->assertField('edit-new-state', 'The node view page has a moderation form.');
// The latest version page should not show, because there is still no
// forward revision.
// pending revision.
$this->drupalGet($latest_version_path);
$this->assertResponse(403);
// Publish the draft.
$this->drupalPostForm($edit_path, [
'body[0][value]' => 'Third version of the content.',
], t('Save and Publish'));
'moderation_state[0][state]' => 'published',
], t('Save'));
// The published view should not have a moderation form, because it is the
// live revision.
@@ -84,14 +97,15 @@ class ModerationFormTest extends ModerationStateTestBase {
$this->assertNoField('edit-new-state', 'The node view page has no moderation form.');
// The latest version page should not show, because there is still no
// forward revision.
// pending revision.
$this->drupalGet($latest_version_path);
$this->assertResponse(403);
// Make a forward revision.
// Make a pending revision.
$this->drupalPostForm($edit_path, [
'body[0][value]' => 'Fourth version of the content.',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
// The published view should not have a moderation form, because it is the
// live revision.
@@ -100,7 +114,7 @@ class ModerationFormTest extends ModerationStateTestBase {
$this->assertNoField('edit-new-state', 'The node view page has no moderation form.');
// The latest version page should show the moderation form and have "Draft"
// status, because the forward revision is in "Draft".
// status, because the pending revision is in "Draft".
$this->drupalGet($latest_version_path);
$this->assertResponse(200);
$this->assertField('edit-new-state', 'The latest-version page has a moderation form.');
@@ -112,7 +126,7 @@ class ModerationFormTest extends ModerationStateTestBase {
], t('Apply'));
// The latest version page should not show, because there is no
// forward revision.
// pending revision.
$this->drupalGet($latest_version_path);
$this->assertResponse(403);
}
@@ -127,23 +141,23 @@ class ModerationFormTest extends ModerationStateTestBase {
$workflow->save();
// Create new moderated content in draft.
$this->drupalPostForm('entity_test_mulrevpub/add', [], t('Save and Create New Draft'));
$this->drupalPostForm('entity_test_mulrevpub/add', ['moderation_state[0][state]' => 'draft'], t('Save'));
// The latest version page should not show, because there is no forward
// The latest version page should not show, because there is no pending
// revision.
$this->drupalGet('/entity_test_mulrevpub/manage/1/latest');
$this->assertResponse(403);
// Update the draft.
$this->drupalPostForm('entity_test_mulrevpub/manage/1/edit', [], t('Save and Create New Draft'));
$this->drupalPostForm('entity_test_mulrevpub/manage/1/edit', ['moderation_state[0][state]' => 'draft'], t('Save'));
// The latest version page should not show, because there is still no
// forward revision.
// pending revision.
$this->drupalGet('/entity_test_mulrevpub/manage/1/latest');
$this->assertResponse(403);
// Publish the draft.
$this->drupalPostForm('entity_test_mulrevpub/manage/1/edit', [], t('Save and Publish'));
$this->drupalPostForm('entity_test_mulrevpub/manage/1/edit', ['moderation_state[0][state]' => 'published'], t('Save'));
// The published view should not have a moderation form, because it is the
// default revision.
@@ -152,12 +166,12 @@ class ModerationFormTest extends ModerationStateTestBase {
$this->assertNoText('Status', 'The node view page has no moderation form.');
// The latest version page should not show, because there is still no
// forward revision.
// pending revision.
$this->drupalGet('entity_test_mulrevpub/manage/1/latest');
$this->assertResponse(403);
// Make a forward revision.
$this->drupalPostForm('entity_test_mulrevpub/manage/1/edit', [], t('Save and Create New Draft'));
// Make a pending revision.
$this->drupalPostForm('entity_test_mulrevpub/manage/1/edit', ['moderation_state[0][state]' => 'draft'], t('Save'));
// The published view should not have a moderation form, because it is the
// default revision.
@@ -166,10 +180,10 @@ class ModerationFormTest extends ModerationStateTestBase {
$this->assertNoText('Status', 'The node view page has no moderation form.');
// The latest version page should show the moderation form and have "Draft"
// status, because the forward revision is in "Draft".
// status, because the pending revision is in "Draft".
$this->drupalGet('entity_test_mulrevpub/manage/1/latest');
$this->assertResponse(200);
$this->assertText('Status', 'Form text found on the latest-version page.');
$this->assertText('Moderation state', 'Form text found on the latest-version page.');
$this->assertText('Draft', 'Correct status found on the latest-version page.');
// Submit the moderation form to change status to published.
@@ -178,7 +192,7 @@ class ModerationFormTest extends ModerationStateTestBase {
], t('Apply'));
// The latest version page should not show, because there is no
// forward revision.
// pending revision.
$this->drupalGet('entity_test_mulrevpub/manage/1/latest');
$this->assertResponse(403);
}
@@ -189,7 +203,7 @@ class ModerationFormTest extends ModerationStateTestBase {
public function testModerationFormSetsRevisionAuthor() {
// Create new moderated content in published.
$node = $this->createNode(['type' => 'moderated_content', 'moderation_state' => 'published']);
// Make a forward revision.
// Make a pending revision.
$node->title = $this->randomMachineName();
$node->moderation_state->value = 'draft';
$node->save();
@@ -205,4 +219,310 @@ class ModerationFormTest extends ModerationStateTestBase {
$this->assertText('by ' . $another_user->getAccountName());
}
/**
* Tests translated and moderated nodes.
*/
public function testContentTranslationNodeForm() {
$this->drupalLogin($this->rootUser);
// Add French language.
$edit = [
'predefined_langcode' => 'fr',
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Enable content translation on articles.
$this->drupalGet('admin/config/regional/content-language');
$edit = [
'entity_types[node]' => TRUE,
'settings[node][moderated_content][translatable]' => TRUE,
'settings[node][moderated_content][settings][language][language_alterable]' => TRUE,
];
$this->drupalPostForm(NULL, $edit, t('Save configuration'));
// Adding languages requires a container rebuild in the test running
// environment so that multilingual services are used.
$this->rebuildContainer();
// Create new moderated content in draft (revision 1).
$this->drupalPostForm('node/add/moderated_content', [
'title[0][value]' => 'Some moderated content',
'body[0][value]' => 'First version of the content.',
'moderation_state[0][state]' => 'draft',
], t('Save'));
$this->assertTrue($this->xpath('//ul[@class="entity-moderation-form"]'));
$node = $this->drupalGetNodeByTitle('Some moderated content');
$this->assertTrue($node->language(), 'en');
$edit_path = sprintf('node/%d/edit', $node->id());
$translate_path = sprintf('node/%d/translations/add/en/fr', $node->id());
$latest_version_path = sprintf('node/%d/latest', $node->id());
$french = \Drupal::languageManager()->getLanguage('fr');
$this->drupalGet($latest_version_path);
$this->assertSession()->statusCodeEquals('403');
$this->assertFalse($this->xpath('//ul[@class="entity-moderation-form"]'));
// Add french translation (revision 2).
$this->drupalGet($translate_path);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionNotExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'body[0][value]' => 'Second version of the content.',
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
$this->drupalGet($latest_version_path, ['language' => $french]);
$this->assertSession()->statusCodeEquals('403');
$this->assertFalse($this->xpath('//ul[@class="entity-moderation-form"]'));
// Add french pending revision (revision 3).
$this->drupalGet($edit_path, ['language' => $french]);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'body[0][value]' => 'Third version of the content.',
'moderation_state[0][state]' => 'draft',
], t('Save (this translation)'));
$this->drupalGet($latest_version_path, ['language' => $french]);
$this->assertTrue($this->xpath('//ul[@class="entity-moderation-form"]'));
// It should not be possible to add a new english revision.
$this->drupalGet($edit_path);
$this->assertSession()->fieldNotExists('moderation_state[0][state]');
$this->assertSession()->pageTextContains('Unable to save this Moderated content.');
$this->clickLink('Publish');
$this->assertSession()->fieldValueEquals('body[0][value]', 'Third version of the content.');
$this->drupalGet($edit_path);
$this->clickLink('Delete');
$this->assertSession()->buttonExists('Delete');
$this->drupalGet($latest_version_path);
$this->assertFalse($this->xpath('//ul[@class="entity-moderation-form"]'));
// Publish the french pending revision (revision 4).
$this->drupalGet($edit_path, ['language' => $french]);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionNotExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'body[0][value]' => 'Fifth version of the content.',
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
$this->drupalGet($latest_version_path, ['language' => $french]);
$this->assertFalse($this->xpath('//ul[@class="entity-moderation-form"]'));
// Now we can publish the english (revision 5).
$this->drupalGet($edit_path);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionNotExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'body[0][value]' => 'Sixth version of the content.',
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
$this->drupalGet($latest_version_path);
$this->assertFalse($this->xpath('//ul[@class="entity-moderation-form"]'));
// Make sure we're allowed to create a pending french revision.
$this->drupalGet($edit_path, ['language' => $french]);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionExists('moderation_state[0][state]', 'archived');
// Add a english pending revision (revision 6).
$this->drupalGet($edit_path);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'body[0][value]' => 'Seventh version of the content.',
'moderation_state[0][state]' => 'draft',
], t('Save (this translation)'));
$this->drupalGet($latest_version_path);
$this->assertTrue($this->xpath('//ul[@class="entity-moderation-form"]'));
// Make sure we're not allowed to create a pending french revision.
$this->drupalGet($edit_path, ['language' => $french]);
$this->assertSession()->fieldNotExists('moderation_state[0][state]');
$this->assertSession()->pageTextContains('Unable to save this Moderated content.');
$this->drupalGet($latest_version_path, ['language' => $french]);
$this->assertFalse($this->xpath('//ul[@class="entity-moderation-form"]'));
// We should be able to publish the english pending revision (revision 7)
$this->drupalGet($edit_path);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionNotExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'body[0][value]' => 'Eighth version of the content.',
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
$this->drupalGet($latest_version_path);
$this->assertFalse($this->xpath('//ul[@class="entity-moderation-form"]'));
// Make sure we're allowed to create a pending french revision.
$this->drupalGet($edit_path, ['language' => $french]);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionExists('moderation_state[0][state]', 'archived');
// Make sure we're allowed to create a pending english revision.
$this->drupalGet($edit_path);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionExists('moderation_state[0][state]', 'archived');
// Create new moderated content. (revision 1).
$this->drupalPostForm('node/add/moderated_content', [
'title[0][value]' => 'Second moderated content',
'body[0][value]' => 'First version of the content.',
'moderation_state[0][state]' => 'published',
], t('Save'));
$node = $this->drupalGetNodeByTitle('Second moderated content');
$this->assertTrue($node->language(), 'en');
$edit_path = sprintf('node/%d/edit', $node->id());
$translate_path = sprintf('node/%d/translations/add/en/fr', $node->id());
// Add a pending revision (revision 2).
$this->drupalGet($edit_path);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'body[0][value]' => 'Second version of the content.',
'moderation_state[0][state]' => 'draft',
], t('Save'));
// It shouldn't be possible to translate as we have a pending revision.
$this->drupalGet($translate_path);
$this->assertSession()->fieldNotExists('moderation_state[0][state]');
$this->assertSession()->pageTextContains('Unable to save this Moderated content.');
// Create new moderated content (revision 1).
$this->drupalPostForm('node/add/moderated_content', [
'title[0][value]' => 'Third moderated content',
'moderation_state[0][state]' => 'published',
], t('Save'));
$node = $this->drupalGetNodeByTitle('Third moderated content');
$this->assertTrue($node->language(), 'en');
$edit_path = sprintf('node/%d/edit', $node->id());
$translate_path = sprintf('node/%d/translations/add/en/fr', $node->id());
// Translate it, without updating data (revision 2).
$this->drupalGet($translate_path);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'moderation_state[0][state]' => 'draft',
], t('Save (this translation)'));
// Add another draft for the translation (revision 3).
$this->drupalGet($edit_path, ['language' => $french]);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionNotExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'moderation_state[0][state]' => 'draft',
], t('Save (this translation)'));
// Editing the original translation should not be possible.
$this->drupalGet($edit_path);
$this->assertSession()->fieldNotExists('moderation_state[0][state]');
$this->assertSession()->pageTextContains('Unable to save this Moderated content.');
// Updating and publishing the french translation is still possible.
$this->drupalGet($edit_path, ['language' => $french]);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionNotExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
// Now the french translation is published, an english draft can be added.
$this->drupalGet($edit_path);
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
$this->assertSession()->optionExists('moderation_state[0][state]', 'archived');
$this->drupalPostForm(NULL, [
'moderation_state[0][state]' => 'draft',
], t('Save (this translation)'));
}
/**
* Tests that workflows and states can not be deleted if they are in use.
*
* @covers \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration::workflowHasData
* @covers \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration::workflowStateHasData
*/
public function testWorkflowInUse() {
$user = $this->createUser([
'administer workflows',
'create moderated_content content',
'edit own moderated_content content',
'use editorial transition create_new_draft',
'use editorial transition publish',
'use editorial transition archive'
]);
$this->drupalLogin($user);
$paths = [
'archived_state' => 'admin/config/workflow/workflows/manage/editorial/state/archived/delete',
'editorial_workflow' => 'admin/config/workflow/workflows/manage/editorial/delete',
];
$messages = [
'archived_state' => 'This workflow state is in use. You cannot remove this workflow state until you have removed all content using it.',
'editorial_workflow' => 'This workflow is in use. You cannot remove this workflow until you have removed all content using it.',
];
foreach ($paths as $path) {
$this->drupalGet($path);
$this->assertSession()->buttonExists('Delete');
}
// Create new moderated content in draft.
$this->drupalPostForm('node/add/moderated_content', [
'title[0][value]' => 'Some moderated content',
'body[0][value]' => 'First version of the content.',
'moderation_state[0][state]' => 'draft',
], 'Save');
// The archived state is not used yet, so can still be deleted.
$this->drupalGet($paths['archived_state']);
$this->assertSession()->buttonExists('Delete');
// The workflow is being used, so can't be deleted.
$this->drupalGet($paths['editorial_workflow']);
$this->assertSession()->buttonNotExists('Delete');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains($messages['editorial_workflow']);
$node = $this->drupalGetNodeByTitle('Some moderated content');
$this->drupalPostForm('node/' . $node->id() . '/edit', [
'moderation_state[0][state]' => 'published',
], 'Save');
$this->drupalPostForm('node/' . $node->id() . '/edit', [
'moderation_state[0][state]' => 'archived',
], 'Save');
// Now the archived state is being used so it can not be deleted either.
foreach ($paths as $type => $path) {
$this->drupalGet($path);
$this->assertSession()->buttonNotExists('Delete');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains($messages[$type]);
}
}
}
@@ -53,8 +53,9 @@ class ModerationLocaleTest extends ModerationStateTestBase {
$edit = [
'title[0][value]' => 'Published English node',
'langcode[0][value]' => 'en',
'moderation_state[0][state]' => 'published',
];
$this->drupalPostForm('node/add/article', $edit, t('Save and Publish'));
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertText(t('Article Published English node has been created.'));
$english_node = $this->drupalGetNodeByTitle('Published English node');
@@ -63,8 +64,9 @@ class ModerationLocaleTest extends ModerationStateTestBase {
$this->clickLink(t('Add'));
$edit = [
'title[0][value]' => 'French node Draft',
'moderation_state[0][state]' => 'draft',
];
$this->drupalPostForm(NULL, $edit, t('Save and Create New Draft (this translation)'));
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
// Here the error has occurred "The website encountered an unexpected error.
// Please try again later."
// If the translation has got lost.
@@ -74,8 +76,9 @@ class ModerationLocaleTest extends ModerationStateTestBase {
$edit = [
'title[0][value]' => 'English node',
'langcode[0][value]' => 'en',
'moderation_state[0][state]' => 'draft',
];
$this->drupalPostForm('node/add/article', $edit, t('Save and Create New Draft'));
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertText(t('Article English node has been created.'));
$english_node = $this->drupalGetNodeByTitle('English node');
@@ -84,14 +87,17 @@ class ModerationLocaleTest extends ModerationStateTestBase {
$this->clickLink(t('Add'));
$edit = [
'title[0][value]' => 'French node',
'moderation_state[0][state]' => 'draft',
];
$this->drupalPostForm(NULL, $edit, t('Save and Create New Draft (this translation)'));
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
$this->assertText(t('Article French node has been updated.'));
$english_node = $this->drupalGetNodeByTitle('English node', TRUE);
// Publish the English article and check that the translation stays
// unpublished.
$this->drupalPostForm('node/' . $english_node->id() . '/edit', [], t('Save and Publish (this translation)'));
$this->drupalPostForm('node/' . $english_node->id() . '/edit', [
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
$this->assertText(t('Article English node has been updated.'));
$english_node = $this->drupalGetNodeByTitle('English node', TRUE);
$french_node = $english_node->getTranslation('fr');
@@ -106,8 +112,9 @@ class ModerationLocaleTest extends ModerationStateTestBase {
// the translation first.
$edit = [
'title[0][value]' => 'Another node',
'moderation_state[0][state]' => 'draft',
];
$this->drupalPostForm('node/add/article', $edit, t('Save and Create New Draft'));
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertText(t('Article Another node has been created.'));
$english_node = $this->drupalGetNodeByTitle('Another node');
@@ -116,14 +123,17 @@ class ModerationLocaleTest extends ModerationStateTestBase {
$this->clickLink(t('Add'));
$edit = [
'title[0][value]' => 'Translated node',
'moderation_state[0][state]' => 'draft',
];
$this->drupalPostForm(NULL, $edit, t('Save and Create New Draft (this translation)'));
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
$this->assertText(t('Article Translated node has been updated.'));
$english_node = $this->drupalGetNodeByTitle('Another node', TRUE);
// Publish the translation and check that the source language version stays
// unpublished.
$this->drupalPostForm('fr/node/' . $english_node->id() . '/edit', [], t('Save and Publish (this translation)'));
$this->drupalPostForm('fr/node/' . $english_node->id() . '/edit', [
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
$this->assertText(t('Article Translated node has been updated.'));
$english_node = $this->drupalGetNodeByTitle('Another node', TRUE);
$french_node = $english_node->getTranslation('fr');
@@ -135,8 +145,9 @@ class ModerationLocaleTest extends ModerationStateTestBase {
// Now check that we can create a new draft of the translation.
$edit = [
'title[0][value]' => 'New draft of translated node',
'moderation_state[0][state]' => 'draft',
];
$this->drupalPostForm('fr/node/' . $english_node->id() . '/edit', $edit, t('Save and Create New Draft (this translation)'));
$this->drupalPostForm('fr/node/' . $english_node->id() . '/edit', $edit, t('Save (this translation)'));
$this->assertText(t('Article New draft of translated node has been updated.'));
$english_node = $this->drupalGetNodeByTitle('Another node', TRUE);
$french_node = $english_node->getTranslation('fr');
@@ -144,12 +155,11 @@ class ModerationLocaleTest extends ModerationStateTestBase {
$this->assertTrue($french_node->isPublished());
$this->assertEqual($french_node->getTitle(), 'Translated node', 'The default revision of the published translation remains the same.');
// Publish the draft.
$edit = [
'new_state' => 'published',
];
$this->drupalPostForm('fr/node/' . $english_node->id() . '/latest', $edit, t('Apply'));
$this->assertText(t('The moderation state has been updated.'));
// Publish the French article before testing the archive transition.
$this->drupalPostForm('fr/node/' . $english_node->id() . '/edit', [
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
$this->assertText(t('Article New draft of translated node has been updated.'));
$english_node = $this->drupalGetNodeByTitle('Another node', TRUE);
$french_node = $english_node->getTranslation('fr');
$this->assertEqual($french_node->moderation_state->value, 'published');
@@ -157,15 +167,21 @@ class ModerationLocaleTest extends ModerationStateTestBase {
$this->assertEqual($french_node->getTitle(), 'New draft of translated node', 'The draft has replaced the published revision.');
// Publish the English article before testing the archive transition.
$this->drupalPostForm('node/' . $english_node->id() . '/edit', [], t('Save and Publish (this translation)'));
$this->drupalPostForm('node/' . $english_node->id() . '/edit', [
'moderation_state[0][state]' => 'published',
], t('Save (this translation)'));
$this->assertText(t('Article Another node has been updated.'));
$english_node = $this->drupalGetNodeByTitle('Another node', TRUE);
$this->assertEqual($english_node->moderation_state->value, 'published');
// Archive the node and its translation.
$this->drupalPostForm('node/' . $english_node->id() . '/edit', [], t('Save and Archive (this translation)'));
$this->drupalPostForm('node/' . $english_node->id() . '/edit', [
'moderation_state[0][state]' => 'archived',
], t('Save (this translation)'));
$this->assertText(t('Article Another node has been updated.'));
$this->drupalPostForm('fr/node/' . $english_node->id() . '/edit', [], t('Save and Archive (this translation)'));
$this->drupalPostForm('fr/node/' . $english_node->id() . '/edit', [
'moderation_state[0][state]' => 'archived',
], t('Save (this translation)'));
$this->assertText(t('Article New draft of translated node has been updated.'));
$english_node = $this->drupalGetNodeByTitle('Another node', TRUE);
$french_node = $english_node->getTranslation('fr');
@@ -173,43 +189,6 @@ class ModerationLocaleTest extends ModerationStateTestBase {
$this->assertFalse($english_node->isPublished());
$this->assertEqual($french_node->moderation_state->value, 'archived');
$this->assertFalse($french_node->isPublished());
// Create another article with its translation. This time publishing english
// after creating a forward french revision.
$edit = [
'title[0][value]' => 'An english node',
];
$this->drupalPostForm('node/add/article', $edit, t('Save and Create New Draft'));
$this->assertText(t('Article An english node has been created.'));
$english_node = $this->drupalGetNodeByTitle('An english node');
$this->assertFalse($english_node->isPublished());
// Add a French translation.
$this->drupalGet('node/' . $english_node->id() . '/translations');
$this->clickLink(t('Add'));
$edit = [
'title[0][value]' => 'A french node',
];
$this->drupalPostForm(NULL, $edit, t('Save and Publish (this translation)'));
$english_node = $this->drupalGetNodeByTitle('An english node', TRUE);
$french_node = $english_node->getTranslation('fr');
$this->assertTrue($french_node->isPublished());
$this->assertFalse($english_node->isPublished());
// Create a forward revision
$this->drupalPostForm('fr/node/' . $english_node->id() . '/edit', [], t('Save and Create New Draft (this translation)'));
$english_node = $this->drupalGetNodeByTitle('An english node', TRUE);
$french_node = $english_node->getTranslation('fr');
$this->assertTrue($french_node->isPublished());
$this->assertFalse($english_node->isPublished());
// Publish the english node and the default french node not the latest
// french node should be used.
$this->drupalPostForm('/node/' . $english_node->id() . '/edit', [], t('Save and Publish (this translation)'));
$english_node = $this->drupalGetNodeByTitle('An english node', TRUE);
$french_node = $english_node->getTranslation('fr');
$this->assertTrue($french_node->isPublished());
$this->assertTrue($english_node->isPublished());
}
}
@@ -43,7 +43,6 @@ class ModerationRevisionRevertTest extends BrowserTestBase {
'administer nodes',
'bypass node access',
'view all revisions',
'view content moderation',
'use editorial transition create_new_draft',
'use editorial transition publish',
]);
@@ -55,10 +54,16 @@ class ModerationRevisionRevertTest extends BrowserTestBase {
*/
public function testEditingAfterRevertRevision() {
// Create a draft.
$this->drupalPostForm('node/add/moderated_bundle', ['title[0][value]' => 'First draft node'], t('Save and Create New Draft'));
$this->drupalPostForm('node/add/moderated_bundle', [
'title[0][value]' => 'First draft node',
'moderation_state[0][state]' => 'draft',
], t('Save'));
// Now make it published.
$this->drupalPostForm('node/1/edit', ['title[0][value]' => 'Published node'], t('Save and Publish'));
$this->drupalPostForm('node/1/edit', [
'title[0][value]' => 'Published node',
'moderation_state[0][state]' => 'published',
], t('Save'));
// Check the editing form that show the published title.
$this->drupalGet('node/1/edit');
@@ -76,7 +81,9 @@ class ModerationRevisionRevertTest extends BrowserTestBase {
$this->assertSession()
->pageTextContains('First draft node');
// Try to save the node.
$this->click('.moderation-state-draft > input');
$this->drupalPostForm('node/1/edit', [
'moderation_state[0][state]' => 'draft',
], t('Save'));
// Check if the submission passed the EntityChangedConstraintValidator.
$this->assertSession()
@@ -32,7 +32,6 @@ class ModerationStateAccessTest extends BrowserTestBase {
$permissions = [
'access content',
'view all revisions',
'view content moderation',
];
$editor1 = $this->drupalCreateUser($permissions);
$this->drupalLogin($editor1);
@@ -69,7 +68,6 @@ class ModerationStateAccessTest extends BrowserTestBase {
$permissions = [
'access content',
'view all revisions',
'administer content moderation',
];
$admin1 = $this->drupalCreateUser($permissions);
$this->drupalLogin($admin1);
@@ -51,25 +51,18 @@ class ModerationStateBlockTest extends ModerationStateTestBase {
public function testCustomBlockModeration() {
$this->drupalLogin($this->rootUser);
$this->drupalGet('admin/structure/block/block-content/types');
$this->assertLinkByHref('admin/structure/block/block-content/manage/basic/moderation');
$this->drupalGet('admin/structure/block/block-content/manage/basic');
$this->assertLinkByHref('admin/structure/block/block-content/manage/basic/moderation');
$this->drupalGet('admin/structure/block/block-content/manage/basic/moderation');
// Enable moderation for custom blocks at
// admin/structure/block/block-content/manage/basic/moderation.
$edit = ['workflow' => 'editorial'];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertText(t('Your settings have been saved.'));
// Enable moderation for custom blocks.
$edit['bundles[basic]'] = TRUE;
$this->drupalPostForm('admin/config/workflow/workflows/manage/editorial/type/block_content', $edit, t('Save'));
// Create a custom block at block/add and save it as draft.
$body = 'Body of moderated block';
$edit = [
'info[0][value]' => 'Moderated block',
'moderation_state[0][state]' => 'draft',
'body[0][value]' => $body,
];
$this->drupalPostForm('block/add', $edit, t('Save and Create New Draft'));
$this->drupalPostForm('block/add', $edit, t('Save'));
$this->assertText(t('basic Moderated block has been created.'));
// Place the block in the Sidebar First region.
@@ -91,8 +84,9 @@ class ModerationStateBlockTest extends ModerationStateTestBase {
$updated_body = 'This is the new body value';
$edit = [
'body[0][value]' => $updated_body,
'moderation_state[0][state]' => 'draft',
];
$this->drupalPostForm('block/' . $block->id(), $edit, t('Save and Create New Draft'));
$this->drupalPostForm('block/' . $block->id(), $edit, t('Save'));
$this->assertText(t('basic Moderated block has been updated.'));
// Navigate to the home page and check that the block shows the updated
@@ -101,18 +95,21 @@ class ModerationStateBlockTest extends ModerationStateTestBase {
$this->drupalGet('');
$this->assertText($updated_body);
// Publish the block so we can create a forward revision.
$this->drupalPostForm('block/' . $block->id(), [], t('Save and Publish'));
// Publish the block so we can create a pending revision.
$this->drupalPostForm('block/' . $block->id(), [
'moderation_state[0][state]' => 'published',
], t('Save'));
// Create a forward revision.
$forward_revision_body = 'This is the forward revision body value';
// Create a pending revision.
$pending_revision_body = 'This is the pending revision body value';
$edit = [
'body[0][value]' => $forward_revision_body,
'body[0][value]' => $pending_revision_body,
'moderation_state[0][state]' => 'draft',
];
$this->drupalPostForm('block/' . $block->id(), $edit, t('Save and Create New Draft'));
$this->drupalPostForm('block/' . $block->id(), $edit, t('Save'));
$this->assertText(t('basic Moderated block has been updated.'));
// Navigate to home page and check that the forward revision doesn't show,
// Navigate to home page and check that the pending revision doesn't show,
// since it should not be set as the default revision.
$this->drupalGet('');
$this->assertText($updated_body);
@@ -124,10 +121,17 @@ class ModerationStateBlockTest extends ModerationStateTestBase {
$this->drupalPostForm('block/' . $block->id() . '/latest', $edit, t('Apply'));
$this->assertText(t('The moderation state has been updated.'));
// Navigate to home page and check that the forward revision is now the
// Navigate to home page and check that the pending revision is now the
// default revision and therefore visible.
$this->drupalGet('');
$this->assertText($forward_revision_body);
$this->assertText($pending_revision_body);
// Check that revision is checked by default when content moderation is
// enabled.
$this->drupalGet('/block/' . $block->id());
$this->assertSession()->checkboxChecked('revision');
$this->assertText('Revisions must be required when moderation is enabled.');
$this->assertSession()->fieldDisabled('revision');
}
}
@@ -28,7 +28,8 @@ class ModerationStateNodeTest extends ModerationStateTestBase {
public function testCreatingContent() {
$this->drupalPostForm('node/add/moderated_content', [
'title[0][value]' => 'moderated content',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
$node = $this->getNodeByTitle('moderated content');
if (!$node) {
$this->fail('Test node was not saved correctly.');
@@ -37,7 +38,9 @@ class ModerationStateNodeTest extends ModerationStateTestBase {
$path = 'node/' . $node->id() . '/edit';
// Set up published revision.
$this->drupalPostForm($path, [], t('Save and Publish'));
$this->drupalPostForm($path, [
'moderation_state[0][state]' => 'published',
], t('Save'));
\Drupal::entityTypeManager()->getStorage('node')->resetCache([$node->id()]);
/* @var \Drupal\node\NodeInterface $node */
$node = \Drupal::entityTypeManager()->getStorage('node')->load($node->id());
@@ -52,9 +55,8 @@ class ModerationStateNodeTest extends ModerationStateTestBase {
$this->assertText(t('The Moderated content moderated content has been deleted.'));
// Disable content moderation.
$this->drupalPostForm('admin/structure/types/manage/moderated_content/moderation', ['workflow' => ''], t('Save'));
$this->drupalGet('admin/structure/types/manage/moderated_content/moderation');
$this->assertOptionSelected('edit-workflow', '');
$edit['bundles[moderated_content]'] = FALSE;
$this->drupalPostForm('admin/config/workflow/workflows/manage/editorial/type/node', $edit, t('Save'));;
// Ensure the parent environment is up-to-date.
// @see content_moderation_workflow_insert()
\Drupal::service('entity_type.bundle.info')->clearCachedBundles();
@@ -63,7 +65,7 @@ class ModerationStateNodeTest extends ModerationStateTestBase {
// Create a new node.
$this->drupalPostForm('node/add/moderated_content', [
'title[0][value]' => 'non-moderated content',
], t('Save and publish'));
], t('Save'));
$node = $this->getNodeByTitle('non-moderated content');
if (!$node) {
@@ -80,7 +82,8 @@ class ModerationStateNodeTest extends ModerationStateTestBase {
$this->drupalPostForm('node/add/moderated_content', [
'title[0][value]' => 'Some moderated content',
'body[0][value]' => 'First version of the content.',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
$node = $this->drupalGetNodeByTitle('Some moderated content');
$edit_path = sprintf('node/%d/edit', $node->id());
@@ -94,7 +97,8 @@ class ModerationStateNodeTest extends ModerationStateTestBase {
// URL, but viewing the second revision.
$this->drupalPostForm($edit_path, [
'body[0][value]' => 'Second version of the content.',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
$this->assertUrl(Url::fromRoute('entity.node.canonical', ['node' => $node->id()]));
$this->assertText('Second version of the content.');
@@ -102,15 +106,17 @@ class ModerationStateNodeTest extends ModerationStateTestBase {
// canonical URL.
$this->drupalPostForm($edit_path, [
'body[0][value]' => 'Third version of the content.',
], t('Save and Publish'));
'moderation_state[0][state]' => 'published',
], t('Save'));
$this->assertUrl(Url::fromRoute('entity.node.canonical', ['node' => $node->id()]));
$this->assertText('Third version of the content.');
// Make a new forward revision; after saving, we should be on the "Latest
// Make a new pending revision; after saving, we should be on the "Latest
// version" tab.
$this->drupalPostForm($edit_path, [
'body[0][value]' => 'Fourth version of the content.',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
$this->assertUrl(Url::fromRoute('entity.node.latest_version', ['node' => $node->id()]));
$this->assertText('Fourth version of the content.');
}
@@ -138,4 +144,46 @@ class ModerationStateNodeTest extends ModerationStateTestBase {
$this->assertEqual(0, $query['page']);
}
/**
* Tests the workflow when a user has no Content Moderation permissions.
*/
public function testNoContentModerationPermissions() {
$session_assert = $this->assertSession();
// Create a user with quite advanced node permissions but no content
// moderation permissions.
$limited_user = $this->createUser([
'administer nodes',
'bypass node access',
]);
$this->drupalLogin($limited_user);
// Check the user can add content, but can't see the moderation state
// select.
$this->drupalGet('node/add/moderated_content');
$session_assert->statusCodeEquals(200);
$session_assert->fieldNotExists('moderation_state[0][state]');
$this->drupalPostForm(NULL, [
'title[0][value]' => 'moderated content',
], 'Save');
// Manually move the content to archived because the user doesn't have
// permission to do this.
$node = $this->getNodeByTitle('moderated content');
$node->moderation_state->value = 'archived';
$node->save();
// Check the user can see the current state but not the select.
$this->drupalGet('node/' . $node->id() . '/edit');
$session_assert->statusCodeEquals(200);
$session_assert->pageTextContains('Archived');
$session_assert->fieldNotExists('moderation_state[0][state]');
$this->drupalPostForm(NULL, [], 'Save');
// When saving they should still be on the edit form, and see the validation
// error message.
$session_assert->pageTextContains('Edit Moderated content moderated content');
$session_assert->pageTextContains('Invalid state transition from Archived to Archived');
}
}
@@ -11,6 +11,9 @@ class ModerationStateNodeTypeTest extends ModerationStateTestBase {
/**
* A node type without moderation state disabled.
*
* @covers \Drupal\content_moderation\EntityTypeInfo::formAlter
* @covers \Drupal\content_moderation\Entity\Handler\NodeModerationHandler::enforceRevisionsBundleFormAlter
*/
public function testNotModerated() {
$this->drupalLogin($this->adminUser);
@@ -18,19 +21,22 @@ class ModerationStateNodeTypeTest extends ModerationStateTestBase {
$this->assertText('The content type Not moderated has been added.');
$this->grantUserPermissionToCreateContentOfType($this->adminUser, 'not_moderated');
$this->drupalGet('node/add/not_moderated');
$this->assertRaw('Save as unpublished');
$this->assertRaw('Save');
$this->drupalPostForm(NULL, [
'title[0][value]' => 'Test',
], t('Save and publish'));
], t('Save'));
$this->assertText('Not moderated Test has been created.');
}
/**
* Tests enabling moderation on an existing node-type, with content.
*
* @covers \Drupal\content_moderation\EntityTypeInfo::formAlter
* @covers \Drupal\content_moderation\Entity\Handler\NodeModerationHandler::enforceRevisionsBundleFormAlter
*/
public function testEnablingOnExistingContent() {
$editor_permissions = [
'administer content moderation',
'administer workflows',
'access administration pages',
'administer content types',
'administer nodes',
@@ -53,20 +59,11 @@ class ModerationStateNodeTypeTest extends ModerationStateTestBase {
$this->drupalGet('node/add/not_moderated');
$this->drupalPostForm(NULL, [
'title[0][value]' => 'Test',
], t('Save and publish'));
], t('Save'));
$this->assertText('Not moderated Test has been created.');
// Now enable moderation state, ensuring all the expected links and tabs are
// present.
$this->drupalGet('admin/structure/types');
$this->assertLinkByHref('admin/structure/types/manage/not_moderated/moderation');
$this->drupalGet('admin/structure/types/manage/not_moderated');
$this->assertLinkByHref('admin/structure/types/manage/not_moderated/moderation');
$this->drupalGet('admin/structure/types/manage/not_moderated/moderation');
$this->assertOptionSelected('edit-workflow', '');
$this->assertNoLink('Delete');
$edit['workflow'] = 'editorial';
$this->drupalPostForm(NULL, $edit, t('Save'));
// Now enable moderation state.
$this->enableModerationThroughUi('not_moderated');
// And make sure it works.
$nodes = \Drupal::entityTypeManager()->getStorage('node')
@@ -81,14 +78,14 @@ class ModerationStateNodeTypeTest extends ModerationStateTestBase {
$this->assertLinkByHref('node/' . $node->id() . '/edit');
$this->drupalGet('node/' . $node->id() . '/edit');
$this->assertResponse(200);
$this->assertRaw('Save and Create New Draft');
$this->assertNoRaw('Save and Publish');
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionNotExists('moderation_state[0][state]', 'published');
$this->drupalLogin($editor_with_publish);
$this->drupalGet('node/' . $node->id() . '/edit');
$this->assertResponse(200);
$this->assertRaw('Save and Create New Draft');
$this->assertRaw('Save and Publish');
$this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
$this->assertSession()->optionExists('moderation_state[0][state]', 'published');
}
}
@@ -29,7 +29,7 @@ abstract class ModerationStateTestBase extends BrowserTestBase {
* @var array
*/
protected $permissions = [
'administer content moderation',
'administer workflows',
'access administration pages',
'administer content types',
'administer nodes',
@@ -38,6 +38,9 @@ abstract class ModerationStateTestBase extends BrowserTestBase {
'access content overview',
'use editorial transition create_new_draft',
'use editorial transition publish',
'use editorial transition archive',
'use editorial transition archived_draft',
'use editorial transition archived_published',
];
/**
@@ -94,6 +97,11 @@ abstract class ModerationStateTestBase extends BrowserTestBase {
protected function createContentTypeFromUi($content_type_name, $content_type_id, $moderated = FALSE, $workflow_id = 'editorial') {
$this->drupalGet('admin/structure/types');
$this->clickLink('Add content type');
// Check that the 'Create new revision' checkbox is checked and disabled.
$this->assertSession()->checkboxChecked('options[revision]');
$this->assertSession()->fieldDisabled('options[revision]');
$edit = [
'name' => $content_type_name,
'type' => $content_type_id,
@@ -113,9 +121,11 @@ abstract class ModerationStateTestBase extends BrowserTestBase {
* @param string $workflow_id
* The workflow to attach to the bundle.
*/
protected function enableModerationThroughUi($content_type_id, $workflow_id = 'editorial') {
$edit['workflow'] = $workflow_id;
$this->drupalPostForm('admin/structure/types/manage/' . $content_type_id . '/moderation', $edit, t('Save'));
public function enableModerationThroughUi($content_type_id, $workflow_id = 'editorial') {
$this->drupalGet('/admin/config/workflow/workflows');
$this->assertLinkByHref('admin/config/workflow/workflows/manage/' . $workflow_id);
$edit['bundles[' . $content_type_id . ']'] = TRUE;
$this->drupalPostForm('admin/config/workflow/workflows/manage/' . $workflow_id . '/type/node', $edit, t('Save'));
// Ensure the parent environment is up-to-date.
// @see content_moderation_workflow_insert()
\Drupal::service('entity_type.bundle.info')->clearCachedBundles();
@@ -28,7 +28,7 @@ class NodeAccessTest extends ModerationStateTestBase {
* @var array
*/
protected $permissions = [
'administer content moderation',
'administer workflows',
'access administration pages',
'administer content types',
'administer nodes',
@@ -46,7 +46,7 @@ class NodeAccessTest extends ModerationStateTestBase {
protected function setUp() {
parent::setUp();
$this->drupalLogin($this->adminUser);
$this->createContentTypeFromUi('Moderated content', 'moderated_content', TRUE);
$this->createContentTypeFromUi('Moderated content', 'moderated_content', FALSE);
$this->grantUserPermissionToCreateContentOfType($this->adminUser, 'moderated_content');
// Rebuild permissions because hook_node_grants() is implemented by the
@@ -60,10 +60,23 @@ class NodeAccessTest extends ModerationStateTestBase {
public function testPageAccess() {
$this->drupalLogin($this->adminUser);
// Access the node form before moderation is enabled, the publication state
// should now be visible.
$this->drupalGet('node/add/moderated_content');
$this->assertSession()->fieldExists('Published');
// Now enable the workflow.
$this->enableModerationThroughUi('moderated_content', 'editorial');
// Access that the status field is no longer visible.
$this->drupalGet('node/add/moderated_content');
$this->assertSession()->fieldNotExists('Published');
// Create a node to test with.
$this->drupalPostForm('node/add/moderated_content', [
$this->drupalPostForm(NULL, [
'title[0][value]' => 'moderated content',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
$node = $this->getNodeByTitle('moderated content');
if (!$node) {
$this->fail('Test node was not saved correctly.');
@@ -91,7 +104,9 @@ class NodeAccessTest extends ModerationStateTestBase {
// Publish the node.
$this->drupalLogin($this->adminUser);
$this->drupalPostForm($edit_path, [], t('Save and Publish'));
$this->drupalPostForm($edit_path, [
'moderation_state[0][state]' => 'published',
], t('Save'));
// Ensure access works correctly for anonymous users.
$this->drupalLogout();
@@ -104,11 +119,12 @@ class NodeAccessTest extends ModerationStateTestBase {
$this->drupalGet($view_path);
$this->assertResponse(200);
// Create a forward revision for the 'Latest revision' tab.
// Create a pending revision for the 'Latest revision' tab.
$this->drupalLogin($this->adminUser);
$this->drupalPostForm($edit_path, [
'title[0][value]' => 'moderated content revised',
], t('Save and Create New Draft'));
'moderation_state[0][state]' => 'draft',
], t('Save'));
$this->drupalLogin($user);
@@ -120,7 +136,7 @@ class NodeAccessTest extends ModerationStateTestBase {
$this->drupalGet($view_path);
$this->assertResponse(200);
// Now make another user, who should not be able to see forward revisions.
// Now make another user, who should not be able to see pending revisions.
$user = $this->createUser([
'use editorial transition create_new_draft',
]);
@@ -55,37 +55,13 @@ class ContentModerationPermissionsTest extends KernelTestBase {
'id' => 'simple_workflow',
'label' => 'Simple Workflow',
'type' => 'content_moderation',
'transitions' => [
'publish' => [
'label' => 'Publish',
'from' => ['draft'],
'to' => 'published',
'weight' => 0,
],
'unpublish' => [
'label' => 'Unpublish',
'from' => ['published'],
'to' => 'draft',
'weight' => 0,
],
],
'states' => [
'draft' => [
'label' => 'Draft',
'weight' => -5,
],
'published' => [
'label' => 'Published',
'weight' => 0,
],
],
],
[
'use simple_workflow transition publish' => [
'title' => 'Use <em class="placeholder">Publish</em> transition from <em class="placeholder">Simple Workflow</em> workflow.',
'title' => '<em class="placeholder">Simple Workflow</em> workflow: Use <em class="placeholder">Publish</em> transition.',
],
'use simple_workflow transition unpublish' => [
'title' => 'Use <em class="placeholder">Unpublish</em> transition from <em class="placeholder">Simple Workflow</em> workflow.',
'use simple_workflow transition create_new_draft' => [
'title' => '<em class="placeholder">Simple Workflow</em> workflow: Use <em class="placeholder">Create New Draft</em> transition.',
],
],
],
@@ -0,0 +1,38 @@
<?php
namespace Drupal\Tests\content_moderation\Kernel;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\KernelTests\KernelTestBase;
use Drupal\rest\Entity\RestResourceConfig;
use Drupal\rest\RestResourceConfigInterface;
/**
* @group content_moderation
*/
class ContentModerationStateResourceTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['serialization', 'rest', 'content_moderation'];
/**
* @see content_moderation_rest_resource_alter()
*/
public function testCreateContentModerationStateResource() {
$this->setExpectedException(PluginNotFoundException::class, 'The "entity:content_moderation_state" plugin does not exist.');
RestResourceConfig::create([
'id' => 'entity.content_moderation_state',
'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
'configuration' => [
'methods' => ['GET'],
'formats' => ['json'],
'authentication' => ['cookie'],
],
])
->enable()
->save();
}
}
@@ -3,11 +3,11 @@
namespace Drupal\Tests\content_moderation\Kernel;
use Drupal\content_moderation\Entity\ContentModerationState;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\entity_test\Entity\EntityTestBundle;
use Drupal\entity_test\Entity\EntityTestWithBundle;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\entity_test\Entity\EntityTestRev;
use Drupal\KernelTests\KernelTestBase;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\node\Entity\Node;
@@ -27,7 +27,13 @@ class ContentModerationStateTest extends KernelTestBase {
public static $modules = [
'entity_test',
'node',
'block',
'block_content',
'media',
'media_test_source',
'image',
'file',
'field',
'content_moderation',
'user',
'system',
@@ -51,29 +57,30 @@ class ContentModerationStateTest extends KernelTestBase {
$this->installSchema('node', 'node_access');
$this->installEntitySchema('node');
$this->installEntitySchema('user');
$this->installEntitySchema('entity_test_with_bundle');
$this->installEntitySchema('entity_test_rev');
$this->installEntitySchema('entity_test_no_bundle');
$this->installEntitySchema('entity_test_mulrevpub');
$this->installEntitySchema('block_content');
$this->installEntitySchema('media');
$this->installEntitySchema('file');
$this->installEntitySchema('content_moderation_state');
$this->installConfig('content_moderation');
$this->installSchema('file', 'file_usage');
$this->installConfig(['field', 'system', 'image', 'file', 'media']);
$this->entityTypeManager = $this->container->get('entity_type.manager');
}
/**
* Tests basic monolingual content moderation through the API.
* Sets up a bundle entity type for the specified entity type, if needed.
*
* @dataProvider basicModerationTestCases
* @param string $entity_type_id
* The entity type identifier.
*
* @return string
* The bundle identifier.
*/
public function testBasicModeration($entity_type_id) {
// Make the 'entity_test_with_bundle' entity type revisionable.
if ($entity_type_id == 'entity_test_with_bundle') {
$this->setEntityTestWithBundleKeys(['revision' => 'revision_id']);
}
$entity_storage = $this->entityTypeManager->getStorage($entity_type_id);
protected function setupBundleEntityType($entity_type_id) {
$bundle_id = $entity_type_id;
$bundle_entity_type_id = $this->entityTypeManager->getDefinition($entity_type_id)->getBundleEntityType();
if ($bundle_entity_type_id) {
@@ -83,6 +90,16 @@ class ContentModerationStateTest extends KernelTestBase {
$entity_type = $entity_type_storage->create([
$bundle_entity_type_definition->getKey('id') => 'example',
]);
if ($entity_type_id == 'media') {
$entity_type->set('source', 'test');
$entity_type->save();
$source_field = $entity_type->getSource()->createSourceField($entity_type);
$source_field->getFieldStorageDefinition()->save();
$source_field->save();
$entity_type->set('source_configuration', [
'source_field' => $source_field->getName(),
]);
}
$entity_type->save();
$bundle_id = $entity_type->id();
}
@@ -91,6 +108,19 @@ class ContentModerationStateTest extends KernelTestBase {
$workflow->getTypePlugin()->addEntityTypeAndBundle($entity_type_id, $bundle_id);
$workflow->save();
return $bundle_id;
}
/**
* Tests basic monolingual content moderation through the API.
*
* @dataProvider basicModerationTestCases
*/
public function testBasicModeration($entity_type_id) {
$bundle_id = $this->setupBundleEntityType($entity_type_id);
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity_storage = $this->entityTypeManager->getStorage($entity_type_id);
$entity = $entity_storage->create([
'title' => 'Test title',
$this->entityTypeManager->getDefinition($entity_type_id)->getKey('bundle') => $bundle_id,
@@ -174,8 +204,8 @@ class ContentModerationStateTest extends KernelTestBase {
'Block content' => [
'block_content',
],
'Test Entity with Bundle' => [
'entity_test_with_bundle',
'Media' => [
'media',
],
'Test entity - revisions, data table, and published interface' => [
'entity_test_mulrevpub',
@@ -189,6 +219,69 @@ class ContentModerationStateTest extends KernelTestBase {
];
}
/**
* Tests removal of content moderation state entity field data.
*
* @dataProvider basicModerationTestCases
*/
public function testContentModerationStateDataRemoval($entity_type_id) {
$bundle_id = $this->setupBundleEntityType($entity_type_id);
// Test content moderation state deletion.
$entity_storage = $this->entityTypeManager->getStorage($entity_type_id);
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $entity_storage->create([
'title' => 'Test title',
$this->entityTypeManager->getDefinition($entity_type_id)->getKey('bundle') => $bundle_id,
]);
$entity->save();
$entity = $this->reloadEntity($entity);
$entity->delete();
$content_moderation_state = ContentModerationState::loadFromModeratedEntity($entity);
$this->assertFalse($content_moderation_state);
// Test content moderation state revision deletion.
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity2 */
$entity2 = $entity_storage->create([
'title' => 'Test title',
$this->entityTypeManager->getDefinition($entity_type_id)->getKey('bundle') => $bundle_id,
]);
$entity2->save();
$revision = clone $entity2;
$revision->isDefaultRevision(FALSE);
$content_moderation_state = ContentModerationState::loadFromModeratedEntity($revision);
$this->assertTrue($content_moderation_state);
$entity2 = $this->reloadEntity($entity2);
$entity2->setNewRevision(TRUE);
$entity2->save();
$entity_storage->deleteRevision($revision->getRevisionId());
$content_moderation_state = ContentModerationState::loadFromModeratedEntity($revision);
$this->assertFalse($content_moderation_state);
$content_moderation_state = ContentModerationState::loadFromModeratedEntity($entity2);
$this->assertTrue($content_moderation_state);
// Test content moderation state translation deletion.
if ($this->entityTypeManager->getDefinition($entity_type_id)->isTranslatable()) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity3 */
$entity3 = $entity_storage->create([
'title' => 'Test title',
$this->entityTypeManager->getDefinition($entity_type_id)->getKey('bundle') => $bundle_id,
]);
$langcode = 'it';
ConfigurableLanguage::createFromLangcode($langcode)
->save();
$entity3->save();
$translation = $entity3->addTranslation($langcode, ['title' => 'Titolo test']);
$translation->save();
$content_moderation_state = ContentModerationState::loadFromModeratedEntity($entity3);
$this->assertTrue($content_moderation_state->hasTranslation($langcode));
$entity3->removeTranslation($langcode);
$entity3->save();
$content_moderation_state = ContentModerationState::loadFromModeratedEntity($entity3);
$this->assertFalse($content_moderation_state->hasTranslation($langcode));
}
}
/**
* Tests basic multilingual content moderation through the API.
*/
@@ -305,38 +398,79 @@ class ContentModerationStateTest extends KernelTestBase {
$this->assertEquals(6, $english_node->getRevisionId());
}
/**
* Tests moderation when the moderation_state field has a config override.
*/
public function testModerationWithFieldConfigOverride() {
NodeType::create([
'type' => 'test_type',
])->save();
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addEntityTypeAndBundle('node', 'test_type');
$workflow->save();
$fields = $this->container->get('entity_field.manager')->getFieldDefinitions('node', 'test_type');
$field_config = $fields['moderation_state']->getConfig('test_type');
$field_config->setLabel('Field Override!');
$field_config->save();
$node = Node::create([
'title' => 'Test node',
'type' => 'test_type',
]);
$node->save();
$this->assertFalse($node->isPublished());
$this->assertEquals('draft', $node->moderation_state->value);
$node->moderation_state = 'published';
$node->save();
$this->assertTrue($node->isPublished());
$this->assertEquals('published', $node->moderation_state->value);
}
/**
* Tests that entities with special languages can be moderated.
*/
public function testModerationWithSpecialLanguages() {
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addEntityTypeAndBundle('entity_test_rev', 'entity_test_rev');
$workflow->save();
// Create a test entity.
$entity = EntityTestRev::create([
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
]);
$entity->save();
$this->assertEquals('draft', $entity->moderation_state->value);
$entity->moderation_state->value = 'published';
$entity->save();
$this->assertEquals('published', EntityTestRev::load($entity->id())->moderation_state->value);
}
/**
* Tests that a non-translatable entity type with a langcode can be moderated.
*/
public function testNonTranslatableEntityTypeModeration() {
// Make the 'entity_test_with_bundle' entity type revisionable.
$this->setEntityTestWithBundleKeys(['revision' => 'revision_id']);
// Create a test bundle.
$entity_test_bundle = EntityTestBundle::create([
'id' => 'example',
]);
$entity_test_bundle->save();
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addEntityTypeAndBundle('entity_test_with_bundle', 'example');
$workflow->getTypePlugin()->addEntityTypeAndBundle('entity_test_rev', 'entity_test_rev');
$workflow->save();
// Check that the tested entity type is not translatable.
$entity_type = \Drupal::entityTypeManager()->getDefinition('entity_test_with_bundle');
$entity_type = \Drupal::entityTypeManager()->getDefinition('entity_test_rev');
$this->assertFalse($entity_type->isTranslatable(), 'The test entity type is not translatable.');
// Create a test entity.
$entity_test_with_bundle = EntityTestWithBundle::create([
'type' => 'example'
]);
$entity_test_with_bundle->save();
$this->assertEquals('draft', $entity_test_with_bundle->moderation_state->value);
$entity = EntityTestRev::create();
$entity->save();
$this->assertEquals('draft', $entity->moderation_state->value);
$entity_test_with_bundle->moderation_state->value = 'published';
$entity_test_with_bundle->save();
$entity->moderation_state->value = 'published';
$entity->save();
$this->assertEquals('published', EntityTestWithBundle::load($entity_test_with_bundle->id())->moderation_state->value);
$this->assertEquals('published', EntityTestRev::load($entity->id())->moderation_state->value);
}
/**
@@ -344,54 +478,35 @@ class ContentModerationStateTest extends KernelTestBase {
* moderated.
*/
public function testNonLangcodeEntityTypeModeration() {
// Make the 'entity_test_with_bundle' entity type revisionable and unset
// the langcode entity key.
$this->setEntityTestWithBundleKeys(['revision' => 'revision_id'], ['langcode']);
// Unset the langcode entity key for 'entity_test_rev'.
$entity_type = clone \Drupal::entityTypeManager()->getDefinition('entity_test_rev');
$keys = $entity_type->getKeys();
unset($keys['langcode']);
$entity_type->set('entity_keys', $keys);
\Drupal::state()->set('entity_test_rev.entity_type', $entity_type);
// Create a test bundle.
$entity_test_bundle = EntityTestBundle::create([
'id' => 'example',
]);
$entity_test_bundle->save();
// Update the entity type in order to remove the 'langcode' field.
\Drupal::entityDefinitionUpdateManager()->applyUpdates();
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addEntityTypeAndBundle('entity_test_with_bundle', 'example');
$workflow->getTypePlugin()->addEntityTypeAndBundle('entity_test_rev', 'entity_test_rev');
$workflow->save();
// Check that the tested entity type is not translatable.
$entity_type = \Drupal::entityTypeManager()->getDefinition('entity_test_with_bundle');
// Check that the tested entity type is not translatable and does not have a
// 'langcode' entity key.
$entity_type = \Drupal::entityTypeManager()->getDefinition('entity_test_rev');
$this->assertFalse($entity_type->isTranslatable(), 'The test entity type is not translatable.');
$this->assertFalse($entity_type->getKey('langcode'), "The test entity type does not have a 'langcode' entity key.");
// Create a test entity.
$entity_test_with_bundle = EntityTestWithBundle::create([
'type' => 'example'
]);
$entity_test_with_bundle->save();
$this->assertEquals('draft', $entity_test_with_bundle->moderation_state->value);
$entity = EntityTestRev::create();
$entity->save();
$this->assertEquals('draft', $entity->moderation_state->value);
$entity_test_with_bundle->moderation_state->value = 'published';
$entity_test_with_bundle->save();
$entity->moderation_state->value = 'published';
$entity->save();
$this->assertEquals('published', EntityTestWithBundle::load($entity_test_with_bundle->id())->moderation_state->value);
}
/**
* Set the keys on the test entity type.
*
* @param array $keys
* The entity keys to override
* @param array $remove_keys
* Keys to remove.
*/
protected function setEntityTestWithBundleKeys($keys, $remove_keys = []) {
$entity_type = clone \Drupal::entityTypeManager()->getDefinition('entity_test_with_bundle');
$original_keys = $entity_type->getKeys();
foreach ($remove_keys as $remove_key) {
unset($original_keys[$remove_key]);
}
$entity_type->set('entity_keys', $keys + $original_keys);
\Drupal::state()->set('entity_test_with_bundle.entity_type', $entity_type);
\Drupal::entityDefinitionUpdateManager()->applyUpdates();
$this->assertEquals('published', EntityTestRev::load($entity->id())->moderation_state->value);
}
/**
@@ -439,6 +554,41 @@ class ContentModerationStateTest extends KernelTestBase {
$this->assertEquals([], $entity_types);
}
/**
* Test the content moderation workflow dependencies for non-config bundles.
*/
public function testWorkflowNonConfigBundleDependencies() {
// Create a bundle not based on any particular configuration.
entity_test_create_bundle('test_bundle');
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addEntityTypeAndBundle('entity_test', 'test_bundle');
$workflow->save();
// Ensure the bundle is correctly added to the workflow.
$this->assertEquals([
'module' => [
'content_moderation',
'entity_test',
],
], $workflow->getDependencies());
$this->assertEquals([
'test_bundle',
], $workflow->getTypePlugin()->getBundlesForEntityType('entity_test'));
// Delete the test bundle to ensure the workflow entity responds
// appropriately.
entity_test_delete_bundle('test_bundle');
$workflow = Workflow::load('editorial');
$this->assertEquals([], $workflow->getTypePlugin()->getBundlesForEntityType('entity_test'));
$this->assertEquals([
'module' => [
'content_moderation',
],
], $workflow->getDependencies());
}
/**
* Reloads the entity after clearing the static cache.
*
@@ -0,0 +1,145 @@
<?php
namespace Drupal\Tests\content_moderation\Kernel;
use Drupal\Core\Config\ConfigImporterException;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\workflows\Entity\Workflow;
/**
* Tests how Content Moderation handles workflow config changes.
*
* @group content_moderation
*/
class ContentModerationWorkflowConfigTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = [
'node',
'content_moderation',
'user',
'system',
'text',
'workflows',
];
/**
* @var \Drupal\Core\Entity\EntityTypeManager
*/
protected $entityTypeManager;
/**
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* @var \Drupal\workflows\Entity\Workflow
*/
protected $workflow;
/**
* @var \Drupal\Core\Config\Entity\ConfigEntityStorage
*/
protected $workflowStorage;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('node', 'node_access');
$this->installEntitySchema('node');
$this->installEntitySchema('user');
$this->installEntitySchema('content_moderation_state');
$this->installConfig('content_moderation');
NodeType::create([
'type' => 'example',
])->save();
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()
->addState('test1', 'Test one')
->addState('test2', 'Test two')
->addState('test3', 'Test three')
->addEntityTypeAndBundle('node', 'example');
$workflow->save();
$this->workflow = $workflow;
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
}
/**
* Test deleting a state via config import.
*/
public function testDeletingStateViaConfiguration() {
$config_sync = \Drupal::service('config.storage.sync');
// Alter the workflow data.
$config_data = $this->config('workflows.workflow.editorial')->get();
unset($config_data['type_settings']['states']['test1']);
$config_sync->write('workflows.workflow.editorial', $config_data);
// Alter the data of another entity type.
$config_data = $this->config('node.type.example')->get();
$config_data['description'] = 'A new description';
$config_sync->write('node.type.example', $config_data);
// Alter the values of simple config.
$config_data = $this->config('core.extension')->get();
$config_data['module']['node'] = 1;
$config_sync->write('core.extension', $config_data);
// There are no Nodes with the moderation state test1, so this should run
// with no errors.
$this->configImporter()->reset()->import();
$node = Node::create([
'type' => 'example',
'title' => 'Test title',
'moderation_state' => 'test2',
]);
$node->save();
$config_data = $this->config('workflows.workflow.editorial')->get();
unset($config_data['type_settings']['states']['test2']);
unset($config_data['type_settings']['states']['test3']);
\Drupal::service('config.storage.sync')->write('workflows.workflow.editorial', $config_data);
// Now there is a Node with the moderation state test2, this will fail.
try {
$this->configImporter()->reset()->import();
$this->fail('ConfigImporterException not thrown, invalid import was not stopped due to deleted state.');
}
catch (ConfigImporterException $e) {
$this->assertEqual($e->getMessage(), 'There were errors validating the config synchronization.');
$error_log = $this->configImporter->getErrors();
$expected = ['The moderation state Test two is being used, but is not in the source storage.'];
$this->assertEqual($expected, $error_log);
}
\Drupal::service('config.storage.sync')->delete('workflows.workflow.editorial');
// An error should be thrown when trying to delete an in use workflow.
try {
$this->configImporter()->reset()->import();
$this->fail('ConfigImporterException not thrown, invalid import was not stopped due to deleted workflow.');
}
catch (ConfigImporterException $e) {
$this->assertEqual($e->getMessage(), 'There were errors validating the config synchronization.');
$error_log = $this->configImporter->getErrors();
$expected = [
'The moderation state Test two is being used, but is not in the source storage.',
'The workflow Editorial is being used, and cannot be deleted.',
];
$this->assertEqual($expected, $error_log);
}
}
}
@@ -37,9 +37,6 @@ class ContentModerationWorkflowTypeApiTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
$this->workflow = Workflow::create(['id' => 'test', 'type' => 'content_moderation']);
$this->workflow
->addState('draft', 'Draft')
->addState('published', 'Published');
}
/**
@@ -101,4 +98,26 @@ class ContentModerationWorkflowTypeApiTest extends KernelTestBase {
);
}
/**
* @covers ::addEntityTypeAndBundle
* @covers ::removeEntityTypeAndBundle
*/
public function testRemoveEntityTypeAndBundle() {
/** @var \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration $workflow_plugin */
$workflow_plugin = $this->workflow->getTypePlugin();
// There should be no bundles for fake_node to start with.
$this->assertEquals([], $workflow_plugin->getBundlesForEntityType('fake_node'));
// Removing a bundle which is not set on the workflow should not throw an
// error and should still result in none being returned.
$workflow_plugin->removeEntityTypeAndBundle('fake_node', 'fake_page');
$this->assertEquals([], $workflow_plugin->getBundlesForEntityType('fake_node'));
// Adding a bundle for fake_node should result it in being returned, but
// then removing it will return no bundles for fake_node.
$workflow_plugin->addEntityTypeAndBundle('fake_node', 'fake_page');
$this->assertEquals(['fake_page'], $workflow_plugin->getBundlesForEntityType('fake_node'));
$workflow_plugin->removeEntityTypeAndBundle('fake_node', 'fake_page');
$this->assertEquals([], $workflow_plugin->getBundlesForEntityType('fake_node'));
}
}
@@ -83,6 +83,7 @@ class DefaultRevisionStateTest extends KernelTestBase {
$this->assertEquals('draft', $english_node->moderation_state->value);
$this->assertFalse($english_node->isPublished());
$this->assertTrue($english_node->isDefaultRevision());
$this->assertModerationState($english_node->getRevisionId(), $english_node->language()->getId(), 'draft');
// Revision 2 (fr)
$french_node = $english_node->addTranslation('fr', ['title' => 'French title']);
@@ -90,6 +91,7 @@ class DefaultRevisionStateTest extends KernelTestBase {
$french_node->save();
$this->assertTrue($french_node->isPublished());
$this->assertTrue($french_node->isDefaultRevision());
$this->assertModerationState($french_node->getRevisionId(), $french_node->language()->getId(), 'published');
// Revision 3 (fr)
$node = Node::load($english_node->id())->getTranslation('fr');
@@ -97,6 +99,7 @@ class DefaultRevisionStateTest extends KernelTestBase {
$node->save();
$this->assertFalse($node->isPublished());
$this->assertFalse($node->isDefaultRevision());
$this->assertModerationState($node->getRevisionId(), $node->language()->getId(), 'draft');
// Revision 4 (en)
$latest_revision = $this->entityTypeManager->getStorage('node')->loadRevision(3);
@@ -104,6 +107,36 @@ class DefaultRevisionStateTest extends KernelTestBase {
$latest_revision->save();
$this->assertFalse($latest_revision->isPublished());
$this->assertFalse($latest_revision->isDefaultRevision());
$this->assertModerationState($latest_revision->getRevisionId(), $latest_revision->language()->getId(), 'draft');
}
/**
* Verifies the expected moderation state revision exists.
*
* @param int $revision_id
* The revision ID of the host entity.
* @param string $langcode
* The language code of the host entity to check.
* @param string $expected_state
* The state the content moderation state revision should be in.
* @param string $expected_workflow
* The workflow the content moderation state revision should be using.
*/
protected function assertModerationState($revision_id, $langcode, $expected_state, $expected_workflow = 'editorial') {
$moderation_state_storage = $this->entityTypeManager->getStorage('content_moderation_state');
$query = $moderation_state_storage->getQuery();
$results = $query->allRevisions()
->condition('content_entity_revision_id', $revision_id)
->condition('langcode', $langcode)
->execute();
$this->assertCount(1, $results);
$moderation_state = $moderation_state_storage
->loadRevision(key($results))
->getTranslation($langcode);
$this->assertEquals($expected_state, $moderation_state->get('moderation_state')->value);
$this->assertEquals($expected_workflow, $moderation_state->get('workflow')->target_id);
}
}
@@ -2,7 +2,6 @@
namespace Drupal\Tests\content_moderation\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
@@ -55,9 +54,9 @@ class EntityOperationsTest extends KernelTestBase {
}
/**
* Verifies that the process of saving forward-revisions works as expected.
* Verifies that the process of saving pending revisions works as expected.
*/
public function testForwardRevisions() {
public function testPendingRevisions() {
// Create a new node in draft.
$page = Node::create([
'type' => 'page',
@@ -68,7 +67,7 @@ class EntityOperationsTest extends KernelTestBase {
$id = $page->id();
// Verify the entity saved correctly, and that the presence of forward
// Verify the entity saved correctly, and that the presence of pending
// revisions doesn't affect the default node load.
/** @var Node $page */
$page = Node::load($id);
@@ -87,7 +86,7 @@ class EntityOperationsTest extends KernelTestBase {
$this->assertTrue($page->isDefaultRevision());
$this->assertTrue($page->isPublished());
// Make a new forward-revision in Draft.
// Make a new pending revision in Draft.
$page->setTitle('C');
$page->moderation_state->value = 'draft';
$page->save();
@@ -96,7 +95,7 @@ class EntityOperationsTest extends KernelTestBase {
$page = Node::load($id);
$this->assertEquals('B', $page->getTitle());
// Verify we can load the forward revision, even if the mechanism is kind
// Verify we can load the pending revision, even if the mechanism is kind
// of gross. Note: revisionIds() is only available on NodeStorageInterface,
// so this won't work for non-nodes. We'd need to use entity queries. This
// is a core bug that should get fixed.
@@ -96,6 +96,124 @@ class EntityStateChangeValidationTest extends KernelTestBase {
$this->assertEquals('Invalid state transition from <em class="placeholder">Draft</em> to <em class="placeholder">Archived</em>', $violations->get(0)->getMessage());
}
/**
* Test validation with an invalid state.
*/
public function testInvalidState() {
$node_type = NodeType::create([
'type' => 'example',
]);
$node_type->save();
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addEntityTypeAndBundle('node', 'example');
$workflow->save();
$node = Node::create([
'type' => 'example',
'title' => 'Test title',
]);
$node->moderation_state->value = 'invalid_state';
$violations = $node->validate();
$this->assertCount(1, $violations);
$this->assertEquals('State <em class="placeholder">invalid_state</em> does not exist on <em class="placeholder">Editorial</em> workflow', $violations->get(0)->getMessage());
}
/**
* Test validation with content that has no initial state or an invalid state.
*/
public function testInvalidStateWithoutExisting() {
// Create content without moderation enabled for the content type.
$node_type = NodeType::create([
'type' => 'example',
]);
$node_type->save();
$node = Node::create([
'type' => 'example',
'title' => 'Test title',
]);
$node->save();
// Enable moderation to test validation on existing content, with no
// explicit state.
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addState('deleted_state', 'Deleted state');
$workflow->getTypePlugin()->addEntityTypeAndBundle('node', 'example');
$workflow->save();
// Validate the invalid state.
$node->moderation_state->value = 'invalid_state';
$violations = $node->validate();
$this->assertCount(1, $violations);
// Assign the node to a state we're going to delete.
$node->moderation_state->value = 'deleted_state';
$node->save();
// Delete the state so $node->original contains an invalid state when
// validating.
$workflow->getTypePlugin()->deleteState('deleted_state');
$workflow->save();
$node->moderation_state->value = 'draft';
$violations = $node->validate();
$this->assertCount(0, $violations);
}
/**
* Test state transition validation with multiple languages.
*/
public function testInvalidStateMultilingual() {
ConfigurableLanguage::createFromLangcode('fr')->save();
$node_type = NodeType::create([
'type' => 'example',
]);
$node_type->save();
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addEntityTypeAndBundle('node', 'example');
$workflow->save();
$node = Node::create([
'type' => 'example',
'title' => 'English Published Node',
'langcode' => 'en',
'moderation_state' => 'published',
]);
$node->save();
$node_fr = $node->addTranslation('fr');
$node_fr->setTitle('French Published Node');
$node_fr->save();
$this->assertEquals('published', $node_fr->moderation_state->value);
// Create a pending revision of the original node.
$node->moderation_state = 'draft';
$node->setNewRevision(TRUE);
$node->isDefaultRevision(FALSE);
$node->save();
// For the pending english revision, there should be a violation from draft
// to archived.
$node->moderation_state = 'archived';
$violations = $node->validate();
$this->assertCount(1, $violations);
$this->assertEquals('Invalid state transition from <em class="placeholder">Draft</em> to <em class="placeholder">Archived</em>', $violations->get(0)->getMessage());
// From the default french published revision, there should be none.
$node_fr = Node::load($node->id())->getTranslation('fr');
$this->assertEquals('published', $node_fr->moderation_state->value);
$node_fr->moderation_state = 'archived';
$violations = $node_fr->validate();
$this->assertCount(0, $violations);
// From the latest french revision, there should also be no violation.
$node_fr = $node->getTranslation('fr');
$this->assertEquals('published', $node_fr->moderation_state->value);
$node_fr->moderation_state = 'archived';
$violations = $node_fr->validate();
$this->assertCount(0, $violations);
}
/**
* Tests that content without prior moderation information can be moderated.
*/
@@ -20,6 +20,7 @@ class EntityTypeInfoTest extends KernelTestBase {
*/
public static $modules = [
'content_moderation',
'workflows',
'entity_test',
];
@@ -79,4 +79,24 @@ class ModerationStateFieldItemListTest extends KernelTestBase {
$this->assertEquals(['draft'], $states);
}
/**
* Tests that moderation state changes also change the related entity state.
*/
public function testModerationStateChanges() {
// Change the moderation state and check that the entity's
// 'isDefaultRevision' flag and the publishing status have also been
// updated.
$this->testNode->moderation_state->value = 'published';
$this->assertTrue($this->testNode->isPublished());
$this->assertTrue($this->testNode->isDefaultRevision());
$this->testNode->save();
// Repeat the checks using an 'unpublished' state.
$this->testNode->moderation_state->value = 'draft';
$this->assertFalse($this->testNode->isPublished());
$this->assertFalse($this->testNode->isDefaultRevision());
}
}
@@ -0,0 +1,92 @@
<?php
namespace Drupal\Tests\content_moderation\Kernel;
use Drupal\content_moderation\Plugin\Field\FieldWidget\ModerationStateWidget;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Form\FormState;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\workflows\Entity\Workflow;
/**
* @coversDefaultClass \Drupal\content_moderation\Plugin\Field\FieldWidget\ModerationStateWidget
* @group content_moderation
*/
class ModerationStateWidgetTest extends KernelTestBase {
/**
* Modules to install.
*
* @var array
*/
public static $modules = [
'system',
'user',
'workflows',
'content_moderation',
'node',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('content_moderation_state');
$this->installEntitySchema('user');
$this->installConfig(['content_moderation', 'system']);
NodeType::create([
'type' => 'moderated',
])->save();
NodeType::create([
'type' => 'unmoderated',
])->save();
$workflow = Workflow::load('editorial');
$workflow->getTypePlugin()->addEntityTypeAndBundle('node', 'moderated');
$workflow->save();
}
/**
* Test the widget does not impact a non-moderated entity.
*/
public function testWidgetNonModeratedEntity() {
// Create an unmoderated entity and build a form display which will include
// the ModerationStateWidget plugin, in a hidden state.
$entity = Node::create([
'type' => 'unmoderated',
]);
$entity_form_display = EntityFormDisplay::create([
'targetEntityType' => 'node',
'bundle' => 'unmoderated',
'mode' => 'default',
'status' => TRUE,
]);
$form = [];
$form_state = new FormState();
$entity_form_display->buildForm($entity, $form, $form_state);
// The moderation_state field should have no values for an entity that isn't
// being moderated.
$entity_form_display->extractFormValues($entity, $form, $form_state);
$this->assertEquals(0, $entity->moderation_state->count());
}
/**
* @covers ::isApplicable
*/
public function testIsApplicable() {
// The moderation_state field definition should be applicable to our widget.
$fields = $this->container->get('entity_field.manager')->getFieldDefinitions('node', 'test_type');
$this->assertTrue(ModerationStateWidget::isApplicable($fields['moderation_state']));
$this->assertFalse(ModerationStateWidget::isApplicable($fields['status']));
// A config override should still be applicable.
$field_config = $fields['moderation_state']->getConfig('moderated');
$this->assertTrue(ModerationStateWidget::isApplicable($field_config));
}
}
@@ -52,7 +52,7 @@ class StateFormatterTest extends KernelTestBase {
]);
$entity->save();
$field_output = $this->container->get('renderer')->executeInRenderContext(new RenderContext(), function() use ($entity, $formatter_settings) {
$field_output = $this->container->get('renderer')->executeInRenderContext(new RenderContext(), function () use ($entity, $formatter_settings) {
return $entity->moderation_state->view($formatter_settings);
});
@@ -2,7 +2,6 @@
namespace Drupal\Tests\content_moderation\Kernel;
use Drupal\entity_test\Entity\EntityTestMulRevPub;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
@@ -51,54 +50,6 @@ class ViewsDataIntegrationTest extends ViewsKernelTestBase {
$workflow->save();
}
/**
* Tests content_moderation_views_data().
*
* @see content_moderation_views_data()
*/
public function testViewsData() {
$node = Node::create([
'type' => 'page',
'title' => 'Test title first revision',
]);
$node->moderation_state->value = 'published';
$node->save();
// Create a totally unrelated entity to ensure the extra join information
// joins by the correct entity type.
$unrelated_entity = EntityTestMulRevPub::create([
'id' => $node->id(),
]);
$unrelated_entity->save();
$this->assertEquals($unrelated_entity->id(), $node->id());
$revision = clone $node;
$revision->setNewRevision(TRUE);
$revision->isDefaultRevision(FALSE);
$revision->title->value = 'Test title second revision';
$revision->moderation_state->value = 'draft';
$revision->save();
$view = Views::getView('test_content_moderation_latest_revision');
$view->execute();
// Ensure that the content_revision_tracker contains the right latest
// revision ID.
// Also ensure that the relationship back to the revision table contains the
// right latest revision.
$expected_result = [
[
'nid' => $node->id(),
'revision_id' => $revision->getRevisionId(),
'title' => $revision->label(),
'moderation_state_1' => 'draft',
'moderation_state' => 'published',
],
];
$this->assertIdenticalResultset($view, $expected_result, ['nid' => 'nid', 'content_revision_tracker_revision_id' => 'revision_id', 'moderation_state' => 'moderation_state', 'moderation_state_1' => 'moderation_state_1']);
}
/**
* Tests the join from the revision data table to the moderation state table.
*/
@@ -5,13 +5,14 @@ namespace Drupal\Tests\content_moderation\Unit;
use Drupal\content_moderation\ContentPreprocess;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\node\Entity\Node;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\content_moderation\ContentPreprocess
*
* @group content_moderation
*/
class ContentPreprocessTest extends \PHPUnit_Framework_TestCase {
class ContentPreprocessTest extends UnitTestCase {
/**
* @covers ::isLatestVersionPage
@@ -12,6 +12,7 @@ use Drupal\Core\Session\AccountInterface;
use Drupal\node\Entity\Node;
use Drupal\content_moderation\Access\LatestRevisionCheck;
use Drupal\content_moderation\ModerationInformation;
use Drupal\Tests\UnitTestCase;
use Drupal\user\EntityOwnerInterface;
use Prophecy\Argument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
@@ -21,7 +22,7 @@ use Symfony\Component\Routing\Route;
* @coversDefaultClass \Drupal\content_moderation\Access\LatestRevisionCheck
* @group content_moderation
*/
class LatestRevisionCheckTest extends \PHPUnit_Framework_TestCase {
class LatestRevisionCheckTest extends UnitTestCase {
/**
* {@inheritdoc}
@@ -44,8 +45,8 @@ class LatestRevisionCheckTest extends \PHPUnit_Framework_TestCase {
* The class of the entity to mock.
* @param string $entity_type
* The machine name of the entity to mock.
* @param bool $has_forward
* Whether this entity should have a forward revision in the system.
* @param bool $has_pending_revision
* Whether this entity should have a pending revision in the system.
* @param array $account_permissions
* An array of permissions the account has.
* @param bool $is_owner
@@ -56,7 +57,7 @@ class LatestRevisionCheckTest extends \PHPUnit_Framework_TestCase {
*
* @dataProvider accessSituationProvider
*/
public function testLatestAccessPermissions($entity_class, $entity_type, $has_forward, array $account_permissions, $is_owner, $result_class) {
public function testLatestAccessPermissions($entity_class, $entity_type, $has_pending_revision, array $account_permissions, $is_owner, $result_class) {
/** @var \Drupal\Core\Session\AccountInterface $account */
$account = $this->prophesize(AccountInterface::class);
@@ -81,7 +82,7 @@ class LatestRevisionCheckTest extends \PHPUnit_Framework_TestCase {
/** @var \Drupal\content_moderation\ModerationInformation $mod_info */
$mod_info = $this->prophesize(ModerationInformation::class);
$mod_info->hasForwardRevision($entity->reveal())->willReturn($has_forward);
$mod_info->hasPendingRevision($entity->reveal())->willReturn($has_pending_revision);
$route = $this->prophesize(Route::class);
@@ -118,13 +119,13 @@ class LatestRevisionCheckTest extends \PHPUnit_Framework_TestCase {
// Node with own content permissions and no latest version, but no perms
// to view latest version.
[Node::class, 'node', TRUE, ['view own unpublished content'], FALSE, AccessResultNeutral::class],
// Block with forward revision, and permissions to view any.
// Block with pending revision, and permissions to view any.
[BlockContent::class, 'block_content', TRUE, ['view latest version', 'view any unpublished content'], FALSE, AccessResultAllowed::class],
// Block with no forward revision.
// Block with no pending revision.
[BlockContent::class, 'block_content', FALSE, ['view latest version', 'view any unpublished content'], FALSE, AccessResultForbidden::class],
// Block with forward revision, but no permission to view any.
// Block with pending revision, but no permission to view any.
[BlockContent::class, 'block_content', TRUE, ['view latest version', 'view own unpublished content'], FALSE, AccessResultNeutral::class],
// Block with no forward revision.
// Block with no pending revision.
[BlockContent::class, 'block_content', FALSE, ['view latest version', 'view own unpublished content'], FALSE, AccessResultForbidden::class],
];
}
@@ -10,13 +10,14 @@ use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\content_moderation\ModerationInformation;
use Drupal\Tests\UnitTestCase;
use Drupal\workflows\WorkflowInterface;
/**
* @coversDefaultClass \Drupal\content_moderation\ModerationInformation
* @group content_moderation
*/
class ModerationInformationTest extends \PHPUnit_Framework_TestCase {
class ModerationInformationTest extends UnitTestCase {
/**
* Builds a mock user.
@@ -7,8 +7,9 @@ use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\content_moderation\StateTransitionValidation;
use Drupal\Tests\UnitTestCase;
use Drupal\workflow_type_test\Plugin\WorkflowType\TestType;
use Drupal\workflows\Entity\Workflow;
use Drupal\workflows\WorkflowTypeInterface;
use Drupal\workflows\WorkflowTypeManager;
use Prophecy\Argument;
@@ -16,7 +17,7 @@ use Prophecy\Argument;
* @coversDefaultClass \Drupal\content_moderation\StateTransitionValidation
* @group content_moderation
*/
class StateTransitionValidationTest extends \PHPUnit_Framework_TestCase {
class StateTransitionValidationTest extends UnitTestCase {
/**
* Verifies user-aware transition validation.
@@ -61,16 +62,14 @@ class StateTransitionValidationTest extends \PHPUnit_Framework_TestCase {
// Create a container so that the plugin manager and workflow type can be
// mocked.
$container = new ContainerBuilder();
$workflow_type = $this->prophesize(WorkflowTypeInterface::class);
$workflow_type->decorateState(Argument::any())->willReturnArgument(0);
$workflow_type->decorateTransition(Argument::any())->willReturnArgument(0);
$workflow_manager = $this->prophesize(WorkflowTypeManager::class);
$workflow_manager->createInstance('content_moderation', Argument::any())->willReturn($workflow_type->reveal());
$workflow_manager->createInstance('content_moderation', Argument::any())->willReturn(new TestType([], '', []));
$container->set('plugin.manager.workflows.type', $workflow_manager->reveal());
\Drupal::setContainer($container);
$workflow = new Workflow(['id' => 'process', 'type' => 'content_moderation'], 'workflow');
$workflow
->getTypePlugin()
->addState('draft', 'draft')
->addState('needs_review', 'needs_review')
->addState('published', 'published')