clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
################
# DrupalCI GitLabCI template
#
# Gitlab-ci.yml to replicate DrupalCI testing for Contrib
#
# With thanks to:
# * The GitLab Acceleration Initiative participants
# * DrupalSpoons
################
################
# Guidelines
#
# This template is designed to give any Contrib maintainer everything they need to test, without requiring modification. It is also designed to keep up to date with Core Development automatically through the use of include files that can be centrally maintained.
#
# However, you can modify this template if you have additional needs for your project.
################
################
# Includes
#
# Additional configuration can be provided through includes.
# One advantage of include files is that if they are updated upstream, the changes affect all pipelines using that include.
#
# Includes can be overridden by re-declaring anything provided in an include, here in gitlab-ci.yml
# https://docs.gitlab.com/ee/ci/yaml/includes.html#override-included-configuration-values
################
include:
################
# DrupalCI includes:
# As long as you include this, any future includes added by the Drupal Association will be accessible to your pipelines automatically.
# View these include files at https://git.drupalcode.org/project/gitlab_templates/
################
- project: $_GITLAB_TEMPLATES_REPO
ref: $_GITLAB_TEMPLATES_REF
file:
- '/includes/include.drupalci.main.yml'
# EXPERIMENTAL: For Drupal 7, remove the above line and uncomment the below.
# - '/includes/include.drupalci.main-d7.yml'
- '/includes/include.drupalci.variables.yml'
- '/includes/include.drupalci.workflows.yml'
################
# Pipeline configuration variables
#
# These are the variables provided to the Run Pipeline form that a user may want to override.
#
# Docs at https://git.drupalcode.org/project/gitlab_templates/-/blob/1.0.x/includes/include.drupalci.variables.yml
################
variables:
SKIP_STYLELINT: '1'
OPT_IN_TEST_MAX_PHP: 1
OPT_IN_TEST_NEXT_MINOR: 1
OPT_IN_TEST_NEXT_MAJOR: 1
OPT_IN_TEST_PREVIOUS_MINOR: 1
_PHPUNIT_CONCURRENT: "1"
_PHPUNIT_EXTRA: --suppress-deprecations
_CSPELL_IGNORE_PATHS: 'README.md'
_CSPELL_WORDS: 'Fulfilment'
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+123
View File
@@ -0,0 +1,123 @@
Provides code-driven workflow functionality.
A workflow is a set of states and transitions that an entity goes through during its lifecycle.
A transition represents a one-way link between two states and has its own label.
The current state of a workflow is stored in a state field, which provides an API for getting and
applying transitions. An entity can have multiple workflows, each in its own state field.
An order might have checkout and payment workflows. A node might have legal and marketing workflows.
Workflow groups are used to group workflows used for the same purpose (e.g. payment workflows).
## Architecture
[Workflow](https://git.drupalcode.org/project/state_machine/-/blob/8.x-1.x/src/Plugin/Workflow/WorkflowInterface.php) and [WorkflowGroup](https://git.drupalcode.org/project/state_machine/-/blob/8.x-1.x/src/Plugin/WorkflowGroup/WorkflowGroupInterface.php) are plugins defined in YAML, similar to menu links.
This leaves room for a future entity-based UI.
Example yourmodule.workflow_groups.yml:
```yaml
commerce_order:
label: Order
entity_type: commerce_order
```
Groups can also override the default workflow class, for more advanced use cases.
Example yourmodule.workflows.yml:
```yaml
default:
id: default
label: Default
group: commerce_order
states:
new:
label: New
fulfillment:
label: Fulfilment
completed:
label: Completed
canceled:
label: Canceled
transitions:
create:
label: Create
from: [new]
to: fulfillment
fulfill:
label: Fulfill
from: [fulfillment]
to: completed
cancel:
label: Cancel
from: [new, fulfillment]
to: canceled
```
Transitions can be further restricted by [guards](https://git.drupalcode.org/project/state_machine/-/blob/8.x-1.x/src/Guard/GuardInterface.php), which are implemented as tagged services:
```yaml
mymodule.fulfillment_guard:
class: Drupal\mymodule\Guard\FulfillmentGuard
tags:
- { name: state_machine.guard, group: commerce_order }
```
The group argument allows the guard factory to only instantiate the guards relevant
to a specific workflow group.
The current state is stored in a [StateItem](https://git.drupalcode.org/project/state_machine/-/blob/8.x-1.x/src/Plugin/Field/FieldType/StateItem.php) field.
A field setting specifies the used workflow, or a value callback that allows
the workflow to be resolved at runtime (checkout workflow based on the used plugin, etc.
A validator is provided that ensures that the specified state is valid (exists in the
workflow and is in the allowed transitions).
The current state should always be changed by applying a transition:
```php
// Apply the "complete" transition to field_state.
$state_item = $entity->get('field_state')->first();
$state_item->applyTransitionById('complete');
$entity->save();
// Or, if the entity has a getter...
$entity->getState()->applyTransitionById('complete');
$entity->save();
```
This allows the next state ID to vary between different workflows (as long as they all have the same transition).
A formatter is provided that outputs a form with the allowed transitions,
allowing workflow changes to happen outside of the edit form.
## Events
If a transition has been applied, the StateItem field will dispatch several events on entity save.
The pre_transition events are dispatched before the save (and allow the entity to be modified), while
the post_transition events are dispatched after the save.
### Transition-specific
Pattern: "{$workflow_group}.{$transition}.{$phase}"
Examples:
- commerce_order.create.pre_transition
- commerce_order.create.post_transition
### Group-specific
Pattern: "{$workflow_group}.{$phase}"
Examples:
- commerce_order.pre_transition
- commerce_order.post_transition
Useful for performing an action based on the "to" state, regardless of which
transition made the change.
### Generic
Pattern: "state_machine.{$phase}"
Examples:
- state_machine.pre_transition
- state_machine.post_transition
Useful for logging, notifications, and other use cases that require reacting
to every transition regardless of the workflow group.
Credits
-------
Initial code by Pedro Cambra.
Inspired by https://github.com/winzou/state-machine
+14
View File
@@ -0,0 +1,14 @@
{
"name": "drupal/state_machine",
"type": "drupal-module",
"description": "Provides code-driven workflow functionality.",
"homepage": "http://drupal.org/project/state_machine",
"license": "GPL-2.0-or-later",
"require": {
"php": ">=7.4",
"drupal/core": "^9.2 || ^10.1 || ^11"
},
"require-dev": {
"drupal/diff": "^1 || ^2"
}
}
@@ -0,0 +1,32 @@
field.field_settings.state:
type: mapping
mapping:
workflow:
type: string
label: Workflow
workflow_callback:
type: string
label: Workflow callback
field.formatter.settings.state_transition_form:
type: mapping
label: 'Formatter settings'
mapping:
require_confirmation:
type: boolean
label: 'Require confirmation before applying the state transition.'
use_modal:
type: boolean
label: 'Display confirmation in a modal dialog.'
field.value.state:
type: mapping
label: 'Default value'
mapping:
value:
type: string
label: 'Value'
views.filter.state_machine_state:
type: views.filter.in_operator
label: 'State'
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

+50
View File
@@ -0,0 +1,50 @@
<?xml version="1.0"?>
<ruleset name="Commerce coding standards">
<description>Drupal 8 coding standards</description>
<exclude-pattern>*/.git/*</exclude-pattern>
<exclude-pattern>*/config/*</exclude-pattern>
<exclude-pattern>*/css/*</exclude-pattern>
<exclude-pattern>*/js/*</exclude-pattern>
<exclude-pattern>*/icons/*</exclude-pattern>
<exclude-pattern>*/vendor/*</exclude-pattern>
<rule ref="Drupal"/>
<!-- The following rules are intentionally disabled. -->
<rule ref="Drupal.Commenting.ClassComment.Missing">
<severity>0</severity>
</rule>
<rule ref="Drupal.Files.LineLength.TooLong">
<severity>0</severity>
</rule>
<rule ref="Drupal.Arrays.Array.LongLineDeclaration">
<severity>0</severity>
</rule>
<rule ref="Drupal.Commenting.VariableComment.VarOrder">
<severity>0</severity>
</rule>
<rule ref="Drupal.Semantics.FunctionT.NotLiteralString">
<severity>0</severity>
</rule>
<!-- Complains about example code. -->
<rule ref="Generic.CodeAnalysis.UselessOverridingMethod.Found">
<severity>0</severity>
</rule>
<!-- Complains about '#element_validate callback:' -->
<rule ref="Drupal.Commenting.DocComment.ShortNotCapital">
<severity>0</severity>
</rule>
<!-- Complains a lot about tests which don't need short descriptions. -->
<rule ref="Drupal.Commenting.DocComment.MissingShort">
<severity>0</severity>
</rule>
<rule ref="Drupal.Commenting.DocComment.ShortSingleLine">
<severity>0</severity>
</rule>
<!-- Complains about annotation classes. -->
<rule ref="Drupal.NamingConventions.ValidVariableName.LowerCamelName">
<severity>0</severity>
</rule>
</ruleset>
@@ -0,0 +1,29 @@
parameters:
ignoreErrors:
-
message: """
#^Call to deprecated method renderPlain\\(\\) of interface Drupal\\\\Core\\\\Render\\\\RendererInterface\\:
in drupal\\:10\\.3\\.0 and is removed from drupal\\:12\\.0\\.0\\. Use
\\\\Drupal\\\\Core\\\\Render\\\\RendererInterface\\:\\:renderInIsolation\\(\\) instead\\.$#
"""
count: 1
path: src/Form/StateTransitionConfirmForm.php
-
message: "#^Method Drupal\\\\state_machine\\\\Plugin\\\\Field\\\\FieldType\\\\StateItem\\:\\:postSave\\(\\) should return bool but return statement is missing\\.$#"
count: 1
path: src/Plugin/Field/FieldType/StateItem.php
-
message: "#^\\\\Drupal calls should be avoided in classes, use dependency injection instead$#"
count: 1
path: src/WorkflowManager.php
-
message: """
#^Call to deprecated method renderPlain\\(\\) of interface Drupal\\\\Core\\\\Render\\\\RendererInterface\\:
in drupal\\:10\\.3\\.0 and is removed from drupal\\:12\\.0\\.0\\. Use
\\\\Drupal\\\\Core\\\\Render\\\\RendererInterface\\:\\:renderInIsolation\\(\\) instead\\.$#
"""
count: 1
path: src/Plugin/diff/Field/StateFieldBuilder.php
@@ -0,0 +1,63 @@
<?php
namespace Drupal\state_machine\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Defines an access checker for the state transition confirmation form.
*/
class StateTransitionAccessCheck implements AccessInterface {
/**
* Checks access to the state transition confirmation form.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param \Drupal\Core\Session\AccountInterface $account
* The currently logged in account.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(RouteMatchInterface $route_match, AccountInterface $account) {
// Get the entity type from the route name.
// The entity route name is 'entity.{entity_type}.state_transition_form'.
$parts = explode('.', $route_match->getRouteName());
$entity_type = $parts[1];
$parameters = $route_match->getParameters();
// Check if one of the required parameter is missing.
foreach ([$entity_type, 'field_name', 'transition_id'] as $required_parameter) {
if (!$parameters->has($required_parameter)) {
return AccessResult::neutral();
}
}
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $route_match->getParameter($entity_type);
$field_name = $route_match->getParameter('field_name');
// Ensures the passed entity has a state field matching the field name
// passed in the url.
if (!$entity || !$entity->hasField($field_name)) {
return AccessResult::forbidden();
}
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $entity->get($field_name)->first();
$allowed_transitions = array_keys($state_item->getTransitions());
// Now check if the requested transition is allowed.
$requested_transition = $route_match->getParameter('transition_id');
if (!in_array($requested_transition, $allowed_transitions, TRUE)) {
return AccessResult::forbidden()->addCacheableDependency($entity);
}
// Now finally check that the current user can update the given entity.
return $entity->access('update', $account, TRUE);
}
}
@@ -0,0 +1,41 @@
<?php
namespace Drupal\state_machine\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Adds the context provider service IDs to the context manager.
*/
class GuardsPass implements CompilerPassInterface {
/**
* {@inheritdoc}
*
* Passes the grouped service IDs of guards to the guard factory.
*/
public function process(ContainerBuilder $container) {
$guards = [];
$priorities = [];
foreach ($container->findTaggedServiceIds('state_machine.guard') as $id => $attributes) {
if (empty($attributes[0]['group'])) {
// Guards without a specified group should be invoked for all of them.
$attributes[0]['group'] = '_generic';
}
$group_id = $attributes[0]['group'];
$guards[$group_id][$id] = $id;
$priorities[$group_id][$id] = $attributes[0]['priority'] ?? 0;
}
// Sort the guards by priority.
foreach ($priorities as $group_id => $services) {
array_multisort($priorities[$group_id], SORT_DESC, $guards[$group_id]);
}
$definition = $container->getDefinition('state_machine.guard_factory');
$definition->addArgument($guards);
}
}
@@ -0,0 +1,143 @@
<?php
namespace Drupal\state_machine\Event;
use Drupal\Component\EventDispatcher\Event;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowTransition;
/**
* Defines the workflow transition event.
*/
class WorkflowTransitionEvent extends Event {
/**
* The transition.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowTransition
*/
protected $transition;
/**
* The workflow.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowInterface
*/
protected $workflow;
/**
* The entity.
*
* @var \Drupal\Core\Entity\ContentEntityInterface
*/
protected $entity;
/**
* The state field name.
*
* @var string
*/
protected $fieldName;
/**
* Constructs a new WorkflowTransitionEvent object.
*
* @param \Drupal\state_machine\Plugin\Workflow\WorkflowTransition $transition
* The transition.
* @param \Drupal\state_machine\Plugin\Workflow\WorkflowInterface $workflow
* The workflow.
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity.
* @param string $field_name
* The state field name.
*/
public function __construct(WorkflowTransition $transition, WorkflowInterface $workflow, ContentEntityInterface $entity, $field_name) {
$this->transition = $transition;
$this->workflow = $workflow;
$this->entity = $entity;
$this->fieldName = $field_name;
}
/**
* Gets the transition.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowTransition
* The transition.
*/
public function getTransition() {
return $this->transition;
}
/**
* Gets the workflow.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowInterface
* The workflow.
*/
public function getWorkflow() {
return $this->workflow;
}
/**
* Gets the entity.
*
* @return \Drupal\Core\Entity\ContentEntityInterface
* The entity.
*/
public function getEntity() {
return $this->entity;
}
/**
* Gets the state field name.
*
* @return string
* The state field name.
*/
public function getFieldName() {
return $this->fieldName;
}
/**
* Gets the state field.
*
* @return \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface
* The state field.
*/
public function getField() {
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $field */
$field = $this->entity->get($this->fieldName)->first();
return $field;
}
/**
* Gets the "from" state.
*
* @deprecated in state_machine:8.x-1.0-rc1 and is removed from state_machine:8.x-2.0.
* Use $this->getField()->getOriginalId() instead.
* @see https://www.drupal.org/node/2982709
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowState
* The "from" state.
*/
public function getFromState() {
$original_id = $this->getField()->getOriginalId();
return $this->workflow->getState($original_id);
}
/**
* Gets the "to" state.
*
* @deprecated in state_machine:8.x-1.0-rc1 and is removed from state_machine:8.x-2.0.
* Use $this->getTransition->getToState() instead.
* @see https://www.drupal.org/node/2982709
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowState
* The "to" state.
*/
public function getToState() {
return $this->transition->getToState();
}
}
@@ -0,0 +1,128 @@
<?php
namespace Drupal\state_machine\Form;
use Drupal\Core\Entity\ContentEntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a confirmation form for performing an entity state transition.
*/
class StateTransitionConfirmForm extends ContentEntityConfirmFormBase {
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The field name.
*
* @var string
*/
protected $fieldName;
/**
* The transition.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowTransition
*/
protected $transition;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->renderer = $container->get('renderer');
return $instance;
}
/**
* {@inheritdoc}
*/
public function getBaseFormId() {
return 'state_machine_transition_confirm_form';
}
/**
* Returns the transition object.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowTransition
* The transition object.
*/
public function getTransition() {
return $this->transition;
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $field_name = '', $transition_id = '') {
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $this->entity->get($field_name)->first();
$transition = $state_item->getWorkflow()->getTransition($transition_id);
$this->fieldName = $field_name;
$this->transition = $transition;
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function getDescription() {
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $this->entity->get($this->fieldName)->first();
$items = [
$this->t('<b>Transition</b>: @transition_label', ['@transition_label' => $this->transition->getLabel()]),
$this->t('<b>@entity_type</b>: @entity_label', ['@entity_type' => $this->entity->getEntityType()->getLabel(), '@entity_label' => $this->entity->label()]),
$this->t('<b>From</b>: @from_state', ['@from_state' => $state_item->getOriginalLabel()]),
$this->t('<b>To</b>: @to_state', ['@to_state' => $this->transition->getToState()]),
];
$description = [
'items' => [
'#type' => 'html_tag',
'#value' => implode('<br/>', $items),
'#tag' => 'p',
],
'warning' => [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => parent::getDescription(),
],
];
return $this->renderer->renderPlain($description);
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to apply this transition?');
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return $this->entity->toUrl('canonical');
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $this->entity->get($this->fieldName)->first();
if ($state_item->isTransitionAllowed($this->transition->getId())) {
$state_item->applyTransition($this->transition);
$this->entity->save();
}
$form_state->setRedirectUrl($this->getCancelUrl());
}
}
@@ -0,0 +1,182 @@
<?php
namespace Drupal\state_machine\Form;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
class StateTransitionForm extends FormBase implements StateTransitionFormInterface {
/**
* The redirect destination.
*
* @var \Drupal\Core\Routing\RedirectDestinationInterface
*/
protected $redirectDestination;
/**
* The entity repository.
*
* @var \Drupal\Core\Entity\EntityRepositoryInterface
*/
protected $entityRepository;
/**
* The entity.
*
* @var \Drupal\Core\Entity\ContentEntityInterface
*/
protected $entity;
/**
* The state field name.
*
* @var string
*/
protected $fieldName;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->redirectDestination = $container->get('redirect.destination');
$instance->entityRepository = $container->get('entity.repository');
return $instance;
}
/**
* {@inheritdoc}
*/
public function getEntity() {
return $this->entity;
}
/**
* {@inheritdoc}
*/
public function setEntity(ContentEntityInterface $entity) {
$this->entity = $this->entityRepository->getTranslationFromContext($entity);
return $this;
}
/**
* {@inheritdoc}
*/
public function getFieldName() {
return $this->fieldName;
}
/**
* {@inheritdoc}
*/
public function setFieldName($field_name) {
$this->fieldName = $field_name;
return $this;
}
/**
* {@inheritdoc}
*/
public function getBaseFormId() {
return 'state_machine_transition_form';
}
/**
* {@inheritdoc}
*/
public function getFormId() {
$entity = $this->getEntity();
if (!$entity) {
throw new \RuntimeException('No entity provided to StateTransitionForm.');
}
// Example ID: "state_machine_transition_form_commerce_order_state_1".
$form_id = $this->getBaseFormId();
$form_id .= '_' . $entity->getEntityTypeId() . '_' . $this->fieldName;
$form_id .= '_' . $entity->id();
return $form_id;
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $this->entity->get($this->fieldName)->first();
if (!isset($state_item)) {
return;
}
$form['actions'] = [
'#type' => 'container',
];
// Determine whether we should output links to the confirmation form,
// or submit buttons.
$require_confirmation = $form_state->get('require_confirmation');
foreach ($state_item->getTransitions() as $transition_id => $transition) {
if (!$require_confirmation) {
$form['actions'][$transition_id] = [
'#type' => 'submit',
'#value' => $transition->getLabel(),
'#submit' => ['::submitForm'],
'#transition' => $transition,
];
continue;
}
$url = $this->entity->toUrl('state-transition-form');
$route_parameters = $url->getRouteParameters() + [
$this->entity->getEntityTypeId() => $this->entity->id(),
'field_name' => $this->fieldName,
'transition_id' => $transition_id,
];
$form['actions'][$transition_id] = [
'#type' => 'link',
'#title' => $transition->getLabel(),
'#url' => Url::fromRoute("entity.{$this->entity->getEntityTypeId()}.state_transition_form", $route_parameters, [
'query' => $this->redirectDestination->getAsArray(),
]),
'#attributes' => [
'class' => [
'button',
],
],
];
if ($form_state->get('use_modal')) {
$form['actions'][$transition_id]['#attributes']['class'][] = 'use-ajax';
$form['actions'][$transition_id]['#attributes']['data-dialog-type'] = 'modal';
$form['actions'][$transition_id]['#attributes']['data-dialog-options'] = Json::encode([
'width' => 'auto',
]);
$form['#attached']['library'][] = 'core/drupal.dialog.ajax';
}
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$triggering_element = $form_state->getTriggeringElement();
/** @var \Drupal\state_machine\Plugin\Workflow\WorkflowTransition $transition */
$transition = $triggering_element['#transition'];
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $this->entity->get($this->fieldName)->first();
// Ensure the transition is still allowed before applying it.
if ($state_item->isTransitionAllowed($transition->getId())) {
$state_item->applyTransition($triggering_element['#transition']);
$this->entity->save();
}
}
}
@@ -0,0 +1,54 @@
<?php
namespace Drupal\state_machine\Form;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\BaseFormIdInterface;
/**
* Defines the interface for state transition forms.
*
* Used for applying a transition to the form entity's state field.
*/
interface StateTransitionFormInterface extends BaseFormIdInterface {
/**
* Gets the form entity.
*
* @return \Drupal\Core\Entity\EntityInterface
* The form entity.
*/
public function getEntity();
/**
* Sets the form entity.
*
* When the form is submitted, a transition will be applied to the entity,
* and the entity will be saved.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The form entity.
*
* @return $this
*/
public function setEntity(ContentEntityInterface $entity);
/**
* Gets the state field name.
*
* @return string
* The state field name.
*/
public function getFieldName();
/**
* Sets the state field name.
*
* @param string $field_name
* The state field name.
*
* @return $this
*/
public function setFieldName($field_name);
}
@@ -0,0 +1,59 @@
<?php
namespace Drupal\state_machine\Guard;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Default implementation of the guard factory.
*/
class GuardFactory implements GuardFactoryInterface {
/**
* The service container.
*
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected $container;
/**
* The guard service ids, grouped by workflow group ID.
*
* @var string[]
*/
protected $guardServiceIds;
/**
* Constructs a new GuardFactory object.
*
* @param \Symfony\Component\DependencyInjection\ContainerInterface $container
* The service container.
* @param string[] $guard_service_ids
* The guard service IDs, grouped by workflow group ID.
*/
public function __construct(ContainerInterface $container, array $guard_service_ids) {
$this->container = $container;
$this->guardServiceIds = $guard_service_ids;
}
/**
* {@inheritdoc}
*/
public function get($group_id) {
$service_ids = [];
if (isset($this->guardServiceIds[$group_id])) {
$service_ids = array_merge($service_ids, $this->guardServiceIds[$group_id]);
}
if (isset($this->guardServiceIds['_generic'])) {
$service_ids = array_merge($service_ids, $this->guardServiceIds['_generic']);
}
$guards = [];
foreach ($service_ids as $service_id) {
$guards[] = $this->container->get($service_id);
}
return $guards;
}
}
@@ -0,0 +1,21 @@
<?php
namespace Drupal\state_machine\Guard;
/**
* Defines the interface for guard factories.
*/
interface GuardFactoryInterface {
/**
* Gets the instantiated guards for the given group ID.
*
* @param string $group_id
* The group ID.
*
* @return \Drupal\state_machine\Guard\GuardInterface[]
* The instantiated guards.
*/
public function get($group_id);
}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\state_machine\Guard;
use Drupal\Core\Entity\EntityInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowTransition;
/**
* Defines the interface for guards.
*
* Allows for custom logic controlling the availability of specific transitions.
* Transitions could be restricted based on the current user's permissions, a
* parent entity field, etc.
*
* By default, a transition is allowed unless at least one guard returns FALSE.
*/
interface GuardInterface {
/**
* Checks whether the given transition is allowed.
*
* @param \Drupal\state_machine\Plugin\Workflow\WorkflowTransition $transition
* The transition.
* @param \Drupal\state_machine\Plugin\Workflow\WorkflowInterface $workflow
* The workflow.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The parent entity.
*
* @return bool
* TRUE if the transition is allowed, FALSE otherwise.
*/
public function allowed(WorkflowTransition $transition, WorkflowInterface $workflow, EntityInterface $entity);
}
@@ -0,0 +1,217 @@
<?php
namespace Drupal\state_machine\Plugin\Field\FieldFormatter;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\state_machine\Form\StateTransitionForm;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'state_transition_form' formatter.
*
* @FieldFormatter(
* id = "state_transition_form",
* label = @Translation("Transition form"),
* field_types = {
* "state",
* },
* )
*/
class StateTransitionFormFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
/**
* The class resolver.
*
* @var \Drupal\Core\DependencyInjection\ClassResolverInterface
*/
protected $classResolver;
/**
* The form builder.
*
* @var \Drupal\Core\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new StateTransitionFormFormatter object.
*
* @param string $plugin_id
* The plugin_id for the formatter.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The definition of the field to which the formatter is associated.
* @param array $settings
* The formatter settings.
* @param string $label
* The formatter label display setting.
* @param string $view_mode
* The view mode.
* @param array $third_party_settings
* Any third party settings.
* @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
* The class resolver.
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, ClassResolverInterface $class_resolver, FormBuilderInterface $form_builder, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->classResolver = $class_resolver;
$this->formBuilder = $form_builder;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('class_resolver'),
$container->get('form_builder'),
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
/** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
$entity = $items->getEntity();
// Do not show the form if the user isn't allowed to modify the entity.
if (!$entity->access('update')) {
return [];
}
/** @var \Drupal\state_machine\Form\StateTransitionFormInterface $form_object */
$form_object = $this->classResolver->getInstanceFromDefinition(StateTransitionForm::class);
$form_object->setEntity($entity);
$form_object->setFieldName($items->getFieldDefinition()->getName());
$form_state_additions = [];
if ($this->supportsConfirmationForm()) {
$form_state_additions += [
// Store in the form state whether a confirmation is required before
// applying the state transition.
'require_confirmation' => (bool) $this->getSetting('require_confirmation'),
'use_modal' => (bool) $this->getSetting('use_modal'),
];
}
$form_state = (new FormState())->setFormState($form_state_additions);
// $elements needs a value for each delta. State fields can't be multivalue,
// so it's safe to hardcode 0.
$elements = [];
$elements[0] = $this->formBuilder->buildForm($form_object, $form_state);
return $elements;
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'require_confirmation' => FALSE,
'use_modal' => FALSE,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$supports_confirmation_form = $this->supportsConfirmationForm();
$form['require_confirmation'] = [
'#title' => $this->t('Require confirmation before applying the state transition'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('require_confirmation'),
// We can't support confirmation forms for state transition forms without
// the "state-transition-form" link template.
'#access' => $supports_confirmation_form,
];
$form['use_modal'] = [
'#title' => $this->t('Display confirmation in a modal dialog'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('use_modal'),
'#states' => [
'visible' => [
':input[name*="require_confirmation"]' => ['checked' => TRUE],
],
],
'#access' => $supports_confirmation_form,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
if (!$this->supportsConfirmationForm()) {
return $summary;
}
if ($this->getSetting('require_confirmation')) {
$summary[] = $this->t('Require confirmation before applying the state transition.');
if ($this->getSetting('use_modal')) {
$summary[] = $this->t('Display confirmation in a modal dialog.');
}
}
else {
$summary[] = $this->t('Do not require confirmation before applying the state transition.');
}
return $summary;
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return $field_definition->getType() == 'state';
}
/**
* Gets whether the target entity type supports the confirmation form.
*
* @return bool
* Whether the target entity type supports the confirmation form.
*/
protected function supportsConfirmationForm() {
// If no "state-transition-form" link template is defined, we can't
// support the confirmation form/modal for applying state transitions.
$entity_type = $this->entityTypeManager->getDefinition($this->fieldDefinition->getTargetEntityTypeId());
return $entity_type->hasLinkTemplate('state-transition-form');
}
}
@@ -0,0 +1,485 @@
<?php
namespace Drupal\state_machine\Plugin\Field\FieldType;
use Drupal\Core\Entity\ContentEntityStorageInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\OptionsProviderInterface;
use Drupal\Core\Validation\Plugin\Validation\Constraint\AllowedValuesConstraint;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Drupal\state_machine\Plugin\Workflow\WorkflowState;
use Drupal\state_machine\Plugin\Workflow\WorkflowTransition;
/**
* Plugin implementation of the 'state' field type.
*
* @FieldType(
* id = "state",
* label = @Translation("State"),
* description = @Translation("Stores the current workflow state."),
* default_widget = "options_select",
* default_formatter = "list_default"
* )
*/
class StateItem extends FieldItemBase implements StateItemInterface, OptionsProviderInterface {
/**
* The original value, used to validate state changes.
*
* @var string
*/
protected $originalValue;
/**
* The transition to apply.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowTransition
*/
protected $transitionToApply;
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'type' => 'varchar_ascii',
'length' => 255,
],
],
];
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('string')
->setLabel(t('State'))
->setRequired(TRUE);
return $properties;
}
/**
* {@inheritdoc}
*/
public function getConstraints() {
$constraints = parent::getConstraints();
// Replace the 'AllowedValuesConstraint' constraint with the 'State' one.
foreach ($constraints as $key => $constraint) {
if ($constraint instanceof AllowedValuesConstraint) {
unset($constraints[$key]);
}
}
$manager = \Drupal::typedDataManager()->getValidationConstraintManager();
$constraints[] = $manager->create('State', []);
return $constraints;
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return [
'workflow' => '',
'workflow_callback' => '',
] + parent::defaultFieldSettings();
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = [];
// Allow the workflow to be changed if it's not determined by a callback.
if (!$this->getSetting('workflow_callback')) {
$workflow_manager = \Drupal::service('plugin.manager.workflow');
$workflows = $workflow_manager->getGroupedLabels($this->getEntity()->getEntityTypeId());
$element['workflow'] = [
'#type' => 'select',
'#title' => $this->t('Workflow'),
'#options' => $workflows,
'#default_value' => $this->getSetting('workflow'),
'#required' => TRUE,
];
}
return $element;
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
// Note that in this field's case the value will never be empty
// because of the default returned in applyDefaultValue().
return $this->value === NULL || $this->value === '';
}
/**
* {@inheritdoc}
*/
public function applyDefaultValue($notify = TRUE) {
if ($workflow = $this->getWorkflow()) {
$states = $workflow->getStates();
$initial_state = reset($states);
$this->setValue(['value' => $initial_state->getId()], $notify);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function setValue($values, $notify = TRUE) {
if (empty($this->originalValue)) {
// If no array is given, then the method received just the state value.
if (isset($values) && !is_array($values)) {
$values = ['value' => $values];
}
// Track the original field value to allow isValid() to validate changes
// and to react to transitions.
$this->originalValue = $values['value'];
}
parent::setValue($values, $notify);
}
/**
* {@inheritdoc}
*/
public function isValid() {
$workflow = $this->getWorkflow();
if (!$workflow) {
return FALSE;
}
// Validate that the state update was allowed.
if ($this->value != $this->originalValue) {
$transition = $workflow->findTransition($this->originalValue, $this->value);
return $transition && $workflow->isTransitionAllowed($transition, $this->getEntity());
}
// Otherwise, if the state didn't change, simply validate that the current
// state belongs to the workflow.
return !empty($workflow->getState($this->value));
}
/**
* {@inheritdoc}
*/
public function getPossibleValues(AccountInterface $account = NULL) {
return array_keys($this->getPossibleOptions($account));
}
/**
* {@inheritdoc}
*/
public function getPossibleOptions(AccountInterface $account = NULL) {
$workflow = $this->getWorkflow();
if (!$workflow) {
// The workflow is not known yet, the field is probably being created.
return [];
}
$state_labels = array_map(function (WorkflowState $state) {
return $state->getLabel();
}, $workflow->getStates());
return $state_labels;
}
/**
* {@inheritdoc}
*/
public function getSettableValues(AccountInterface $account = NULL) {
return array_keys($this->getSettableOptions($account));
}
/**
* {@inheritdoc}
*/
public function getSettableOptions(AccountInterface $account = NULL) {
// $this->value is unpopulated due to https://www.drupal.org/node/2629932
$field_name = $this->getFieldDefinition()->getName();
if (!$this->getEntity()->hasField($field_name)) {
return [];
}
$value = $this->getEntity()->get($field_name)->value;
$allowed_states = $this->getAllowedStates($value);
$state_labels = array_map(function (WorkflowState $state) {
return $state->getLabel();
}, $allowed_states);
return $state_labels;
}
/**
* Gets the next allowed states for the given field value.
*
* @param string $value
* The field value, representing the state ID.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowState[]
* The allowed states.
*/
protected function getAllowedStates($value) {
$workflow = $this->getWorkflow();
if (!$workflow) {
// The workflow is not known yet, the field is probably being created.
return [];
}
$allowed_states = [];
if (!empty($value) && ($current_state = $workflow->getState($value))) {
$allowed_states[$value] = $current_state;
}
$transitions = $workflow->getAllowedTransitions($value, $this->getEntity());
foreach ($transitions as $transition) {
$state = $transition->getToState();
$allowed_states[$state->getId()] = $state;
}
return $allowed_states;
}
/**
* {@inheritdoc}
*/
public function getWorkflow() {
if ($callback = $this->getSetting('workflow_callback')) {
$workflow_id = call_user_func($callback, $this->getEntity());
}
else {
$workflow_id = $this->getSetting('workflow');
}
if (empty($workflow_id)) {
return FALSE;
}
$workflow_manager = \Drupal::service('plugin.manager.workflow');
return $workflow_manager->createInstance($workflow_id);
}
/**
* {@inheritdoc}
*/
public function getOriginalId() {
return $this->originalValue;
}
/**
* {@inheritdoc}
*/
public function getId() {
return $this->value;
}
/**
* {@inheritdoc}
*/
public function getLabel() {
return $this->getStateLabel($this->value);
}
/**
* {@inheritdoc}
*/
public function getOriginalLabel() {
return $this->getStateLabel($this->originalValue);
}
/**
* Gets the state label for the given state ID.
*
* @param string $state_id
* The state ID.
*
* @return string
* The state label.
*/
protected function getStateLabel($state_id) {
$label = $state_id;
if ($workflow = $this->getWorkflow()) {
$state = $workflow->getState($state_id);
if ($state) {
$label = $state->getLabel();
}
}
return $label;
}
/**
* {@inheritdoc}
*/
public function getTransitions() {
$transitions = [];
if ($workflow = $this->getWorkflow()) {
$transitions = $workflow->getAllowedTransitions($this->value, $this->getEntity());
}
return $transitions;
}
/**
* {@inheritdoc}
*/
public function isTransitionAllowed($transition_id) {
$workflow = $this->getWorkflow();
if (!$workflow) {
return FALSE;
}
// We first check that the transition passed is a "possible" transition.
// Note that we don't call the getTransitions() method on purpose since
// it loops over all transitions and invoke the guards on each of them.
$possible_transitions = $workflow->getPossibleTransitions($this->value);
if (!isset($possible_transitions[$transition_id])) {
return FALSE;
}
return $workflow->isTransitionAllowed($possible_transitions[$transition_id], $this->getEntity());
}
/**
* {@inheritdoc}
*/
public function applyTransition(WorkflowTransition $transition) {
if (!$this->isTransitionAllowed($transition->getId())) {
throw new \InvalidArgumentException(sprintf('The transition "%s" is currently not allowed. (Current state: "%s".)', $transition->getId(), $this->getId()));
}
// Store the transition to apply, to ensure we're applying the requested
// transition instead of guessing based on the original state.
$this->transitionToApply = $transition;
$this->setValue(['value' => $transition->getToState()->getId()]);
}
/**
* {@inheritdoc}
*/
public function applyTransitionById($transition_id) {
$transition = NULL;
if ($workflow = $this->getWorkflow()) {
$transition = $workflow->getTransition($transition_id);
}
if (!$transition) {
throw new \InvalidArgumentException(sprintf('Unknown transition ID "%s".', $transition_id));
}
$this->applyTransition($transition);
}
/**
* {@inheritdoc}
*/
public function preSave() {
if ($this->value != $this->originalValue || $this->transitionToApply !== NULL) {
$this->dispatchTransitionEvent('pre_transition');
}
}
/**
* {@inheritdoc}
*/
public function postSave($update) {
if ($this->value != $this->originalValue || $this->transitionToApply !== NULL) {
$this->dispatchTransitionEvent('post_transition');
}
$this->originalValue = $this->value;
// Nullify the transition to apply, to ensure the next entity save
// doesn't trigger the same transition by mistake.
$this->transitionToApply = NULL;
}
/**
* Dispatches a transition event for the given phase.
*
* @param string $phase
* The phase: pre_transition OR post_transition.
*/
protected function dispatchTransitionEvent($phase) {
/** @var \Drupal\state_machine\Plugin\Workflow\WorkflowInterface $workflow */
$workflow = $this->getWorkflow();
$transition = $this->transitionToApply ?? $workflow->findTransition($this->originalValue, $this->value);
if ($transition) {
$field_name = $this->getFieldDefinition()->getName();
$group_id = $workflow->getGroup();
$transition_id = $transition->getId();
$event_dispatcher = \Drupal::getContainer()->get('event_dispatcher');
$event = new WorkflowTransitionEvent($transition, $workflow, $this->getEntity(), $field_name);
$events = [
// For example: 'commerce_order.place.pre_transition'.
$group_id . '.' . $transition_id . '.' . $phase,
// For example: 'commerce_order.pre_transition'.
$group_id . '.' . $phase,
// For example: 'state_machine.pre_transition'.
'state_machine.' . $phase,
];
foreach ($events as $event_id) {
$event_dispatcher->dispatch($event, $event_id);
}
}
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
// Attempt to determine the right workflow to use.
if ($callback = $field_definition->getSetting('workflow_callback')) {
$entity_type_id = $field_definition->getTargetEntityTypeId();
$entity_storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
if (!$entity_storage instanceof ContentEntityStorageInterface) {
return [];
}
$values = [];
// Attempt to create a sample entity with at least the bundle set.
if ($bundle_key = $entity_storage->getEntityType()->getKey('bundle')) {
if ($field_definition->getTargetBundle()) {
$bundle = $field_definition->getTargetBundle();
}
else {
$bundle_ids = \Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type_id);
$bundle = array_rand($bundle_ids);
}
$values[$bundle_key] = $bundle;
}
$entity = $entity_storage->create($values);
$workflow_id = call_user_func($callback, $entity);
}
else {
$workflow_id = $field_definition->getSetting('workflow');
}
// The workflow could not be determined, cannot generate a sample value.
if (empty($workflow_id)) {
return [];
}
/** @var \Drupal\state_machine\WorkflowManagerInterface $workflow_manager */
$workflow_manager = \Drupal::service('plugin.manager.workflow');
/** @var \Drupal\state_machine\Plugin\Workflow\WorkflowInterface $workflow */
$workflow = $workflow_manager->createInstance($workflow_id);
// Select states that allow at least one transition.
$candidate_states = $states = $workflow->getStates();
foreach ($candidate_states as $key => $candidate) {
if (empty($workflow->getPossibleTransitions($candidate->getId()))) {
unset($states[$key]);
}
}
$random_state = array_rand($states);
$values = ['value' => $states[$random_state]->getId()];
return $values;
}
}
@@ -0,0 +1,116 @@
<?php
namespace Drupal\state_machine\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowTransition;
/**
* Defines the interface for state field items.
*/
interface StateItemInterface extends FieldItemInterface {
/**
* Gets the workflow used by the field.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowInterface|false
* The workflow, or FALSE if unknown at this time.
*/
public function getWorkflow();
/**
* Gets the original state ID.
*
* If the state ID has been changed after the entity was constructed/loaded,
* the original ID will hold the previous value.
*
* Use this as an alternative to getting the state ID from $entity->original.
*
* @return string
* The original state ID.
*/
public function getOriginalId();
/**
* Gets the current state ID.
*
* @return string
* The current state ID.
*/
public function getId();
/**
* Gets the label of the current state.
*
* @return string
* The label of the current state.
*/
public function getLabel();
/**
* Gets the label of the original state.
*
* @return string
* The label of the original state.
*/
public function getOriginalLabel();
/**
* Gets the allowed transitions for the current state.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowTransition[]
* The allowed transitions, keyed by transition ID.
*/
public function getTransitions();
/**
* Gets whether the given transition is allowed.
*
* @param string $transition_id
* The transition ID.
*
* @return bool
* TRUE if the given transition is allowed, FALSE otherwise.
*/
public function isTransitionAllowed($transition_id);
/**
* Applies the given transition, changing the current state.
*
* @param \Drupal\state_machine\Plugin\Workflow\WorkflowTransition $transition
* The transition to apply.
*
* @throws \InvalidArgumentException
* Thrown when the transition is not allowed.
*/
public function applyTransition(WorkflowTransition $transition);
/**
* Applies a transition with the given ID, changing the current state.
*
* @param string $transition_id
* The transition ID.
*
* @throws \InvalidArgumentException
* Thrown when no matching transition was found.
*/
public function applyTransitionById($transition_id);
/**
* Gets whether the current state is valid.
*
* Drupal separates field validation into a separate step, allowing an
* invalid state to be set before validation is invoked. At that point
* validation has no access to the previous value, so it can't determine
* if the transition is allowed. Thus, the field item must track the state
* changes internally, and answer via this method if the current state is
* valid.
*
* @see \Drupal\state_machine\Plugin\Validation\Constraint\StateConstraintValidator
*
* @return bool
* TRUE if the current state is valid, FALSE otherwise.
*/
public function isValid();
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\state_machine\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Ensures the validity of the specified state.
*
* The state must exist on the used workflow, and be in the allowed transitions.
*
* @Constraint(
* id = "State",
* label = @Translation("State", context = "Validation")
* )
*/
class StateConstraint extends Constraint {
/**
* The default violation message.
*
* @var string
*/
public $message = "The state '@state' is invalid.";
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\state_machine\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the State constraint.
*
* @see \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface::isValid()
*/
class StateConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
if (!$value->isValid()) {
$this->context->addViolation($constraint->message, ['@state' => $value->value]);
}
}
}
@@ -0,0 +1,186 @@
<?php
namespace Drupal\state_machine\Plugin\Workflow;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\state_machine\Guard\GuardFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines the class for workflows.
*/
class Workflow extends PluginBase implements WorkflowInterface, ContainerFactoryPluginInterface {
/**
* The guard factory.
*
* @var \Drupal\state_machine\Guard\GuardFactoryInterface
*/
protected $guardFactory;
/**
* The initialized states.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowState[]
*/
protected $states = [];
/**
* The initialized transitions.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowTransition[]
*/
protected $transitions = [];
/**
* Constructs a new Workflow object.
*
* @param array $configuration
* The plugin configuration.
* @param string $plugin_id
* The workflow plugin_id.
* @param mixed $plugin_definition
* The workflow plugin implementation definition.
* @param \Drupal\state_machine\Guard\GuardFactoryInterface $guard_factory
* The guard factory.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, GuardFactoryInterface $guard_factory) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->guardFactory = $guard_factory;
// Populate value objects for states and transitions.
foreach ($plugin_definition['states'] as $id => $state_definition) {
$this->states[$id] = new WorkflowState($id, $state_definition['label']);
}
foreach ($plugin_definition['transitions'] as $id => $transition_definition) {
$label = $transition_definition['label'];
$from_states = [];
foreach ($transition_definition['from'] as $from_state) {
$from_states[$from_state] = $this->states[$from_state];
}
$to_state = $this->states[$transition_definition['to']];
$this->transitions[$id] = new WorkflowTransition($id, $label, $from_states, $to_state);
}
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('state_machine.guard_factory')
);
}
/**
* {@inheritdoc}
*/
public function getId() {
return $this->pluginDefinition['id'];
}
/**
* {@inheritdoc}
*/
public function getLabel() {
return $this->pluginDefinition['label'];
}
/**
* {@inheritdoc}
*/
public function getGroup() {
return $this->pluginDefinition['group'];
}
/**
* {@inheritdoc}
*/
public function getStates() {
return $this->states;
}
/**
* {@inheritdoc}
*/
public function getState($id) {
return $this->states[$id] ?? NULL;
}
/**
* {@inheritdoc}
*/
public function getTransitions() {
return $this->transitions;
}
/**
* {@inheritdoc}
*/
public function getTransition($id) {
return $this->transitions[$id] ?? NULL;
}
/**
* {@inheritdoc}
*/
public function getPossibleTransitions($state_id) {
if (empty($state_id)) {
return $this->transitions;
}
$possible_transitions = [];
foreach ($this->transitions as $id => $transition) {
if (array_key_exists($state_id, $transition->getFromStates())) {
$possible_transitions[$id] = $transition;
}
}
return $possible_transitions;
}
/**
* {@inheritdoc}
*/
public function getAllowedTransitions($state_id, EntityInterface $entity) {
$allowed_transitions = [];
foreach ($this->getPossibleTransitions($state_id) as $transition_id => $transition) {
if ($this->isTransitionAllowed($transition, $entity)) {
$allowed_transitions[$transition_id] = $transition;
}
}
return $allowed_transitions;
}
/**
* {@inheritdoc}
*/
public function findTransition($from_state_id, $to_state_id) {
foreach ($this->getPossibleTransitions($from_state_id) as $transition) {
if ($transition->getToState()->getId() == $to_state_id) {
return $transition;
}
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function isTransitionAllowed(WorkflowTransition $transition, EntityInterface $entity) {
foreach ($this->guardFactory->get($this->getGroup()) as $guard) {
if ($guard->allowed($transition, $this, $entity) === FALSE) {
return FALSE;
}
}
return TRUE;
}
}
@@ -0,0 +1,129 @@
<?php
namespace Drupal\state_machine\Plugin\Workflow;
use Drupal\Core\Entity\EntityInterface;
/**
* Defines the interface for workflows.
*/
interface WorkflowInterface {
/**
* Gets the workflow ID.
*
* @return string
* The workflow ID.
*/
public function getId();
/**
* Gets the translated label.
*
* @return string
* The translated label.
*/
public function getLabel();
/**
* Gets the workflow group.
*
* @return string
* The workflow group.
*/
public function getGroup();
/**
* Gets the workflow states.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowState[]
* The states, keyed by state ID.
*/
public function getStates();
/**
* Gets a workflow state with the given ID.
*
* @param string $id
* The state ID.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowState|null
* The requested state, or NULL if not found.
*/
public function getState($id);
/**
* Gets the workflow transitions.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowTransition[]
* The transitions, keyed by transition ID.
*/
public function getTransitions();
/**
* Gets a workflow transition with the given ID.
*
* @param string $id
* The transition ID.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowTransition|null
* The requested transition, or NULL if not found.
*/
public function getTransition($id);
/**
* Gets the possible workflow transitions for the given state ID.
*
* Note that a possible transition might not be allowed (because of a guard
* returning false).
*
* @param string $state_id
* The state ID.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowTransition[]
* The possible transitions, keyed by transition ID.
*/
public function getPossibleTransitions($state_id);
/**
* Gets the allowed workflow transitions for the given state ID.
*
* @param string $state_id
* The state ID.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The parent entity.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowTransition[]
* The allowed transitions, keyed by transition ID.
*/
public function getAllowedTransitions($state_id, EntityInterface $entity);
/**
* Finds the workflow transition for moving between two given states.
*
* @param string $from_state_id
* The ID of the "from" state.
* @param string $to_state_id
* The ID of the "to" state.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowTransition|null
* The transition, or NULL if not found.
*/
public function findTransition($from_state_id, $to_state_id);
/**
* Gets whether the given transition is allowed by the transition guards.
*
* Note that this method assumes the given transition is "possible".
*
* @param \Drupal\state_machine\Plugin\Workflow\WorkflowTransition $transition
* The transition.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The parent entity.
*
* @return bool
* TRUE if the transition is allowed, FALSE otherwise.
*/
public function isTransitionAllowed(WorkflowTransition $transition, EntityInterface $entity);
}
@@ -0,0 +1,71 @@
<?php
namespace Drupal\state_machine\Plugin\Workflow;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Defines the class for workflow states.
*/
class WorkflowState {
use StringTranslationTrait;
/**
* The state ID.
*
* @var string
*/
protected $id;
/**
* The state label.
*
* @var string
*/
protected $label;
/**
* Constructs a new WorkflowState object.
*
* @param string $id
* The state ID.
* @param string $label
* The state label.
*/
public function __construct($id, $label) {
$this->id = $id;
$this->label = $label;
}
/**
* Gets the ID.
*
* @return string
* The ID.
*/
public function getId() {
return $this->id;
}
/**
* Gets the translated label.
*
* @return string
* The translated label.
*/
public function getLabel() {
return (string) $this->t($this->label, [], ['context' => 'workflow state']);
}
/**
* Gets the string representation of the workflow state.
*
* @return string
* The string representation of the workflow state.
*/
public function __toString() {
return $this->getLabel();
}
}
@@ -0,0 +1,101 @@
<?php
namespace Drupal\state_machine\Plugin\Workflow;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Defines the class for workflow transitions.
*/
class WorkflowTransition {
use StringTranslationTrait;
/**
* The transition ID.
*
* @var string
*/
protected $id;
/**
* The transition label.
*
* @var string
*/
protected $label;
/**
* The "from" states.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowState[]
*/
protected $fromStates;
/**
* The "to" state.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowState
*/
protected $toState;
/**
* Constructs a new WorkflowTransition object.
*
* @param string $id
* The transition ID.
* @param string $label
* The transition label.
* @param \Drupal\state_machine\Plugin\Workflow\WorkflowState[] $from_states
* The "from" states.
* @param \Drupal\state_machine\Plugin\Workflow\WorkflowState $to_state
* The "to" state.
*/
public function __construct($id, $label, array $from_states, WorkflowState $to_state) {
$this->id = $id;
$this->label = $label;
$this->fromStates = $from_states;
$this->toState = $to_state;
}
/**
* Gets the ID.
*
* @return string
* The ID.
*/
public function getId() {
return $this->id;
}
/**
* Gets the translated label.
*
* @return string
* The translated label.
*/
public function getLabel() {
return (string) $this->t($this->label, [], ['context' => 'workflow transition']);
}
/**
* Gets the "from" states.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowState[]
* The "from" states.
*/
public function getFromStates() {
return $this->fromStates;
}
/**
* Gets the "to" state.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowState
* The "to" state.
*/
public function getToState() {
return $this->toState;
}
}
@@ -0,0 +1,40 @@
<?php
namespace Drupal\state_machine\Plugin\WorkflowGroup;
use Drupal\Core\Plugin\PluginBase;
/**
* Defines the class for workflow groups.
*/
class WorkflowGroup extends PluginBase implements WorkflowGroupInterface {
/**
* {@inheritdoc}
*/
public function getId() {
return $this->pluginDefinition['id'];
}
/**
* {@inheritdoc}
*/
public function getLabel() {
return $this->pluginDefinition['label'];
}
/**
* {@inheritdoc}
*/
public function getEntityTypeId() {
return $this->pluginDefinition['entity_type'];
}
/**
* {@inheritdoc}
*/
public function getWorkflowClass() {
return $this->pluginDefinition['workflow_class'];
}
}
@@ -0,0 +1,47 @@
<?php
namespace Drupal\state_machine\Plugin\WorkflowGroup;
/**
* Defines the interface for workflow groups.
*/
interface WorkflowGroupInterface {
/**
* Gets the workflow group ID.
*
* @return string
* The workflow group ID.
*/
public function getId();
/**
* Gets the translated label.
*
* @return string
* The translated label.
*/
public function getLabel();
/**
* Gets the entity type ID.
*
* For example, "node" if all workflows in the group are used on content.
*
* @return string
* The entity type ID.
*/
public function getEntityTypeId();
/**
* Gets the workflow class.
*
* By default all workflows use the same class. A group can choose to
* override the class for its workflows, to satisfy advanced use cases.
*
* @return string
* The workflow class.
*/
public function getWorkflowClass();
}
@@ -0,0 +1,38 @@
<?php
namespace Drupal\state_machine\Plugin\diff\Field;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\diff\Plugin\diff\Field\CoreFieldBuilder;
/**
* Plugin to compare state fields.
*
* @FieldDiffBuilder(
* id = "state_diff_builder",
* label = @Translation("State Field Diff"),
* field_types = {
* "state"
* },
* )
*/
class StateFieldBuilder extends CoreFieldBuilder {
/**
* {@inheritdoc}
*/
public function build(FieldItemListInterface $field_items) {
$result = [];
foreach ($field_items as $field_key => $field_item) {
if (!$field_item->isEmpty()) {
$value = $field_item->view(['label' => 'hidden', 'type' => 'default']);
$rendered_value = $this->renderer->renderPlain($value);
$result[$field_key][] = $rendered_value;
}
}
return $result;
}
}
@@ -0,0 +1,208 @@
<?php
namespace Drupal\state_machine\Plugin\views\filter;
use Drupal\Component\Utility\SortArray;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\views\Plugin\views\filter\InOperator;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Filter by workflow state.
*
* @ingroup views_filter_handlers
*
* @ViewsFilter("state_machine_state")
*/
class State extends InOperator {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* Constructs a new State 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\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->entityFieldManager = $entity_field_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('entity_field.manager')
);
}
/**
* {@inheritdoc}
*/
public function getValueOptions() {
if (!isset($this->valueOptions)) {
$entity_type_id = $this->getEntityType();
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
$field_name = $this->getFieldName();
$workflows = $this->getWorkflows($entity_type, $field_name);
// Merge the states of all workflows into one list, preserving their
// initial positions.
$states = [];
foreach ($workflows as $workflow) {
$weight = 0;
foreach ($workflow->getStates() as $state_id => $state) {
$states[$state_id] = [
'label' => $state->getLabel(),
'weight' => $weight,
];
$weight++;
}
}
uasort($states, [SortArray::class, 'sortByWeightElement']);
$this->valueOptions = array_map(function ($state) {
return $state['label'];
}, $states);
}
return $this->valueOptions;
}
/**
* Gets the name of the entity field on which this filter operates.
*
* @return string
* The field name.
*/
protected function getFieldName() {
if (isset($this->configuration['field_name'])) {
// Configurable field.
$field_name = $this->configuration['field_name'];
}
else {
// Base field.
$field_name = $this->configuration['entity field'];
}
return $field_name;
}
/**
* Gets the workflows used the current entity field.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The current entity type.
* @param string $field_name
* The current field name.
*
* @return \Drupal\state_machine\Plugin\Workflow\WorkflowInterface[]
* The workflows.
*/
protected function getWorkflows(EntityTypeInterface $entity_type, $field_name) {
// Only the StateItem knows which workflow it's using. This requires us
// to create an entity for each bundle in order to get the state field.
$storage = $this->entityTypeManager->getStorage($entity_type->id());
$bundles = $this->getBundles($entity_type, $field_name);
$workflows = [];
foreach ($bundles as $bundle) {
$values = [];
if ($bundle_key = $entity_type->getKey('bundle')) {
$values[$bundle_key] = $bundle;
}
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $storage->create($values);
if ($entity->hasField($field_name)) {
$workflow = $entity->get($field_name)->first()->getWorkflow();
$workflows[$workflow->getId()] = $workflow;
}
}
return $workflows;
}
/**
* Gets the bundles for the current entity field.
*
* If the view has a non-exposed bundle filter, the bundles are taken from
* there. Otherwise, the field's bundles are used.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The current entity type.
* @param string $field_name
* The current field name.
*
* @return string[]
* The bundles.
*/
protected function getBundles(EntityTypeInterface $entity_type, $field_name) {
$bundles = [];
$bundle_key = $entity_type->getKey('bundle');
if ($bundle_key) {
// Get any bundle filters for this entity type and bundle.
// It is unlikely, but there could be multiple.
/** @var \Drupal\views\Plugin\views\filter\FilterPluginBase[] $bundle_filters */
$bundle_filters = array_filter($this->view->filter ?? [], static function ($filter) use ($entity_type, $bundle_key) {
return $filter->getEntityType() === $entity_type->id() && $filter->realField === $bundle_key;
});
foreach ($bundle_filters as $bundle_filter) {
if ($bundle_filter->isExposed()) {
// If any bundle filters are exposed,
// we cannot return a subset of bundles.
$bundles = [];
break;
}
switch ($bundle_filter->operator) {
case 'in':
$bundles = array_merge($bundles, $bundle_filter->value);
break;
case 'not in':
$bundles = array_diff($bundles, $bundle_filter->value);
break;
}
}
// Remove the "all" option, if present.
if (array_key_exists('all', $bundles)) {
unset($bundles['all']);
}
}
// Fallback to the list of bundles the field is attached to.
if (empty($bundles)) {
$map = $this->entityFieldManager->getFieldMap();
$bundles = $map[$entity_type->id()][$field_name]['bundles'];
}
return $bundles;
}
}
@@ -0,0 +1,57 @@
<?php
namespace Drupal\state_machine\Routing;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Subscriber for state machine transition routes on entities.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new RouteSubscriber object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_manager) {
$this->entityTypeManager = $entity_manager;
}
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
if (!$entity_type->hasLinkTemplate('state-transition-form')) {
continue;
}
$route = new Route($entity_type->getLinkTemplate('state-transition-form'));
$route
->setDefaults([
'_entity_form' => "$entity_type_id.state-transition-confirm",
])
->setRequirement('_state_transition_access', "TRUE")
->setRequirement($entity_type_id, '\d+')
->setRequirement('transition_id', '[a-z0-9_]+')
->setRequirement('field_name', '[a-z0-9_]+')
->setOption('parameters', [
$entity_type_id => ['type' => 'entity:' . $entity_type_id],
]);
$collection->add("entity.$entity_type_id.state_transition_form", $route);
}
}
}
@@ -0,0 +1,21 @@
<?php
namespace Drupal\state_machine;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\state_machine\DependencyInjection\Compiler\GuardsPass;
/**
* Registers the guard compiler pass.
*/
class StateMachineServiceProvider implements ServiceProviderInterface {
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
$container->addCompilerPass(new GuardsPass());
}
}
@@ -0,0 +1,94 @@
<?php
namespace Drupal\state_machine;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator;
use Drupal\Core\Plugin\Discovery\YamlDiscovery;
use Drupal\state_machine\Plugin\Workflow\Workflow;
use Drupal\state_machine\Plugin\WorkflowGroup\WorkflowGroup;
/**
* Manages discovery and instantiation of workflow_group plugins.
*
* @see \Drupal\state_machine\Plugin\WorkflowGroup\WorkflowGroupInterface
* @see plugin_api
*/
class WorkflowGroupManager extends DefaultPluginManager implements WorkflowGroupManagerInterface {
/**
* Default values for each workflow_group plugin.
*
* @var array
*/
protected $defaults = [
'id' => '',
'label' => '',
'entity_type' => '',
'class' => WorkflowGroup::class,
// Groups can override the default workflow class for advanced use cases.
'workflow_class' => Workflow::class,
];
/**
* Constructs a new WorkflowGroupManager object.
*
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* The cache backend.
*/
public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache_backend) {
$this->moduleHandler = $module_handler;
$this->setCacheBackend($cache_backend, 'workflow_group', ['workflow_group']);
$this->alterInfo('workflow_groups');
}
/**
* {@inheritdoc}
*/
protected function getDiscovery() {
if (!isset($this->discovery)) {
$this->discovery = new YamlDiscovery('workflow_groups', $this->moduleHandler->getModuleDirectories());
$this->discovery->addTranslatableProperty('label', 'label_context');
$this->discovery = new ContainerDerivativeDiscoveryDecorator($this->discovery);
}
return $this->discovery;
}
/**
* {@inheritdoc}
*/
public function processDefinition(&$definition, $plugin_id) {
parent::processDefinition($definition, $plugin_id);
if ($plugin_id == 'state_machine') {
throw new PluginException('The "state_machine" workflow_group ID is reserved and must not be used.');
}
$definition['id'] = $plugin_id;
foreach (['label', 'entity_type'] as $required_property) {
if (empty($definition[$required_property])) {
throw new PluginException(sprintf('The workflow_group %s must define the %s property.', $plugin_id, $required_property));
}
}
}
/**
* {@inheritdoc}
*/
public function getDefinitionsByEntityType($entity_type_id = NULL) {
$definitions = $this->getDefinitions();
if ($entity_type_id) {
$definitions = array_filter($definitions, function ($definition) use ($entity_type_id) {
return $definition['entity_type'] == $entity_type_id;
});
}
return $definitions;
}
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\state_machine;
use Drupal\Component\Plugin\PluginManagerInterface;
/**
* Defines the interface for workflow_group plugin managers.
*/
interface WorkflowGroupManagerInterface extends PluginManagerInterface {
/**
* Gets the definitions filtered by entity type.
*
* @param string $entity_type_id
* The entity type ID.
*
* @return array
* The definitions.
*/
public function getDefinitionsByEntityType($entity_type_id = NULL);
}
@@ -0,0 +1,193 @@
<?php
namespace Drupal\state_machine;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator;
use Drupal\Core\Plugin\Discovery\YamlDiscovery;
/**
* Manages discovery and instantiation of workflow plugins.
*
* @see \Drupal\state_machine\Plugin\Workflow\WorkflowInterface
* @see plugin_api
*/
class WorkflowManager extends DefaultPluginManager implements WorkflowManagerInterface {
/**
* The workflow group manager.
*
* @var \Drupal\state_machine\WorkflowGroupManagerInterface
*/
protected $groupManager;
/**
* A cache of loaded workflows, keyed by workflow ID.
*
* @var \Drupal\state_machine\Plugin\Workflow\WorkflowInterface[]
*/
protected $plugins;
/**
* Default values for each workflow plugin.
*
* @var array
*/
protected $defaults = [
'id' => '',
'label' => '',
'group' => '',
'states' => [],
'transitions' => [],
];
/**
* Constructs a new WorkflowManager object.
*
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* The cache backend.
* @param \Drupal\state_machine\WorkflowGroupManagerInterface $group_manager
* The workflow group manager.
*/
public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache_backend, WorkflowGroupManagerInterface $group_manager) {
$this->moduleHandler = $module_handler;
$this->setCacheBackend($cache_backend, 'workflow', ['workflow']);
$this->groupManager = $group_manager;
$this->alterInfo('workflows');
}
/**
* {@inheritdoc}
*/
protected function getDiscovery() {
if (!isset($this->discovery)) {
$this->discovery = new YamlDiscovery('workflows', $this->moduleHandler->getModuleDirectories());
$this->discovery->addTranslatableProperty('label', 'label_context');
$this->discovery = new ContainerDerivativeDiscoveryDecorator($this->discovery);
}
return $this->discovery;
}
/**
* {@inheritdoc}
*/
public function createInstance($plugin_id, array $configuration = []) {
if (empty($this->plugins[$plugin_id])) {
$plugin_definition = $this->getDefinition($plugin_id);
if (empty($plugin_definition['group'])) {
throw new PluginException(sprintf('The workflow %s must define the group property.', $plugin_id));
}
$group_definition = $this->groupManager->getDefinition($plugin_definition['group']);
$plugin_class = $group_definition['workflow_class'];
if (is_subclass_of($plugin_class, ContainerFactoryPluginInterface::class)) {
$this->plugins[$plugin_id] = $plugin_class::create(\Drupal::getContainer(), $configuration, $plugin_id, $plugin_definition);
}
else {
$this->plugins[$plugin_id] = new $plugin_class($configuration, $plugin_id, $plugin_definition);
}
}
return $this->plugins[$plugin_id];
}
/**
* {@inheritdoc}
*/
public function processDefinition(&$definition, $plugin_id) {
parent::processDefinition($definition, $plugin_id);
$definition['id'] = $plugin_id;
foreach (['label', 'group', 'states', 'transitions'] as $required_property) {
if (empty($definition[$required_property])) {
throw new PluginException(sprintf('The workflow %s must define the %s property.', $plugin_id, $required_property));
}
}
foreach ($definition['states'] as $state_id => $state_definition) {
if (empty($state_definition['label'])) {
throw new PluginException(sprintf('The workflow state %s must define the label property.', $state_id));
}
}
foreach ($definition['transitions'] as $transition_id => $transition_definition) {
foreach (['label', 'from', 'to'] as $required_property) {
if (empty($transition_definition[$required_property])) {
throw new PluginException(sprintf('The workflow transition %s must define the %s property.', $transition_id, $required_property));
}
}
// Validate the referenced "from" and "to" states.
foreach ($transition_definition['from'] as $from_state) {
if (!isset($definition['states'][$from_state])) {
throw new PluginException(sprintf('The workflow transition %s specified an invalid "from" property: %s.', $transition_id, $from_state));
}
}
$to_state = $transition_definition['to'];
if (!isset($definition['states'][$to_state])) {
throw new PluginException(sprintf('The workflow transition %s specified an invalid "to" property.', $transition_id));
}
}
}
/**
* {@inheritdoc}
*/
public function getGroupedLabels($entity_type_id = NULL) {
$definitions = $this->getSortedDefinitions();
$group_labels = $this->getGroupLabels($entity_type_id);
$grouped_definitions = [];
foreach ($definitions as $id => $definition) {
$group_id = $definition['group'];
if (!isset($group_labels[$group_id])) {
// Don't return workflows for groups ignored due to their entity type.
continue;
}
$group_label = $group_labels[$group_id];
$grouped_definitions[$group_label][$id] = $definition['label'];
}
return $grouped_definitions;
}
/**
* Gets the sorted workflow plugin definitions.
*
* @return array
* The workflow plugin definitions, sorted by group and label.
*/
protected function getSortedDefinitions() {
// Sort the plugins first by group, then by label.
$definitions = $this->getDefinitions();
uasort($definitions, function ($a, $b) {
if ($a['group'] != $b['group']) {
return strnatcasecmp($a['group'], $b['group']);
}
return strnatcasecmp($a['label'], $b['label']);
});
return $definitions;
}
/**
* Gets a list of group labels for the given entity type ID.
*
* @param string $entity_type_id
* The entity type ID.
*
* @return array
* A list of groups labels keyed by ID.
*/
protected function getGroupLabels($entity_type_id = NULL) {
$group_definitions = $this->groupManager->getDefinitionsByEntityType($entity_type_id);
$group_labels = array_map(function ($group_definition) {
return (string) $group_definition['label'];
}, $group_definitions);
natcasesort($group_labels);
return $group_labels;
}
}
@@ -0,0 +1,25 @@
<?php
namespace Drupal\state_machine;
use Drupal\Component\Plugin\PluginManagerInterface;
/**
* Defines the interface for workflow plugin managers.
*/
interface WorkflowManagerInterface extends PluginManagerInterface {
/**
* Gets the grouped workflow labels.
*
* @param string $entity_type_id
* (optional) The entity type id to filter by. If provided, only workflows
* that belong to groups with the specified entity type will be returned.
*
* @return array
* Keys are group labels, and values are arrays of which the keys are
* workflow IDs and the values are workflow labels.
*/
public function getGroupedLabels($entity_type_id = NULL);
}
@@ -0,0 +1,35 @@
<?php
/**
* @file
* Hooks provided by the State Machine module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Alter workflows.
*
* @param array $workflows
* Workflow definitions, keyed by plugin ID.
*/
function hook_workflows_alter(array &$workflows) {
$workflows['default']['label'] = 'Altered label';
}
/**
* Alter workflow groups.
*
* @param array $workflow_groups
* Workflow group definitions, keyed by plugin ID.
*/
function hook_workflow_groups_alter(array &$workflow_groups) {
$workflow_groups['default']['label'] = 'Altered label';
}
/**
* @} End of "addtogroup hooks".
*/
@@ -0,0 +1,12 @@
name: State Machine
type: module
description: Provides code-driven workflow functionality.
package: Other
core_version_requirement: ^9.2 || ^10.1 || ^11
dependencies:
- drupal:options
# Information added by Drupal.org packaging script on 2024-07-23
version: '8.x-1.12'
project: 'state_machine'
datestamp: 1721740594
@@ -0,0 +1,38 @@
<?php
/**
* @file
* Provides workflow functionality.
*/
use Drupal\state_machine\Form\StateTransitionConfirmForm;
/**
* Implements hook_field_widget_info_alter().
*/
function state_machine_field_widget_info_alter(array &$info) {
$info['options_select']['field_types'][] = 'state';
}
/**
* Implements hook_field_formatter_info_alter().
*/
function state_machine_field_formatter_info_alter(array &$info) {
$info['list_default']['field_types'][] = 'state';
}
/**
* Implements hook_entity_type_alter().
*/
function state_machine_entity_type_alter(array &$entity_types) {
/** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
foreach ($entity_types as $entity_type) {
// Sets a default state-transition-confirm form class for all entity types
// defining a "state-transition-form" link template.
if (!$entity_type->hasLinkTemplate('state-transition-form') ||
$entity_type->getFormClass('state-transition-confirm')) {
continue;
}
$entity_type->setFormClass('state-transition-confirm', StateTransitionConfirmForm::class);
}
}
@@ -0,0 +1,8 @@
workflow:
label: Workflow
plugin_manager_service_id: plugin.manager.workflow
plugin_definition_decorator_class: \Drupal\plugin\PluginDefinition\ArrayPluginDefinitionDecorator
workflow_group:
label: Workflow group
plugin_manager_service_id: plugin.manager.workflow_group
plugin_definition_decorator_class: \Drupal\plugin\PluginDefinition\ArrayPluginDefinitionDecorator
@@ -0,0 +1,24 @@
services:
access_check.state_transition:
class: Drupal\state_machine\Access\StateTransitionAccessCheck
arguments: [ '@entity_type.manager' ]
tags:
- { name: access_check, applies_to: _state_transition_access }
state_machine.guard_factory:
class: Drupal\state_machine\Guard\GuardFactory
arguments: ['@service_container']
state_machine.route_subscriber:
class: Drupal\state_machine\Routing\RouteSubscriber
arguments: ['@entity_type.manager']
tags:
- { name: event_subscriber }
plugin.manager.workflow:
class: Drupal\state_machine\WorkflowManager
arguments: ['@module_handler', '@cache.discovery', '@plugin.manager.workflow_group']
plugin.manager.workflow_group:
class: Drupal\state_machine\WorkflowGroupManager
arguments: ['@module_handler', '@cache.discovery']
@@ -0,0 +1,25 @@
<?php
/**
* @file
* Provide Views data for the State Machine module.
*
* @ingroup views_module_handlers
*/
use Drupal\field\FieldStorageConfigInterface;
/**
* Implements hook_field_views_data().
*
* Views integration for state fields.
*/
function state_machine_field_views_data(FieldStorageConfigInterface $field) {
$data = views_field_default_views_data($field);
$field_name = $field->getName();
foreach ($data as $table_name => $table_data) {
$data[$table_name][$field_name . '_value']['filter']['id'] = 'state_machine_state';
}
return $data;
}
@@ -0,0 +1,6 @@
langcode: en
status: true
dependencies: { }
id: first
label: First
description: ''
@@ -0,0 +1,6 @@
langcode: en
status: true
dependencies: { }
id: fourth
label: Fourth
description: ''
@@ -0,0 +1,6 @@
langcode: en
status: true
dependencies: { }
id: second
label: Second
description: ''
@@ -0,0 +1,6 @@
langcode: en
status: true
dependencies: { }
id: third
label: Third
description: ''
@@ -0,0 +1,21 @@
langcode: en
status: true
dependencies:
config:
- entity_test.entity_test_bundle.first
- field.storage.entity_test_with_bundle.field_state
module:
- state_machine
id: entity_test_with_bundle.first.field_state
field_name: field_state
entity_type: entity_test_with_bundle
bundle: first
label: State
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
workflow: default
field_type: state
@@ -0,0 +1,21 @@
langcode: en
status: true
dependencies:
config:
- entity_test.entity_test_bundle.fourth
- field.storage.entity_test_with_bundle.field_state
module:
- state_machine
id: entity_test_with_bundle.fourth.field_state
field_name: field_state
entity_type: entity_test_with_bundle
bundle: fourth
label: State
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
workflow: same_transition
field_type: state
@@ -0,0 +1,21 @@
langcode: en
status: true
dependencies:
config:
- entity_test.entity_test_bundle.second
- field.storage.entity_test_with_bundle.field_state
module:
- state_machine
id: entity_test_with_bundle.second.field_state
field_name: field_state
entity_type: entity_test_with_bundle
bundle: second
label: State
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
workflow_callback: 'state_machine_test_workflow_callback'
field_type: state
@@ -0,0 +1,21 @@
langcode: en
status: true
dependencies:
config:
- entity_test.entity_test_bundle.third
- field.storage.entity_test_with_bundle.field_state
module:
- state_machine
id: entity_test_with_bundle.third.field_state
field_name: field_state
entity_type: entity_test_with_bundle
bundle: third
label: State
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
workflow: two_transitions
field_type: state
@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- state_machine
- entity_test
id: entity_test_with_bundle.field_state
field_name: field_state
entity_type: entity_test_with_bundle
type: state
settings: { }
module: state_machine
locked: false
cardinality: 1
translatable: false
indexes: { }
persist_with_no_fields: false
custom_storage: false
@@ -0,0 +1,334 @@
langcode: en
status: true
dependencies:
config:
- field.storage.entity_test_with_bundle.field_state
module:
- entity_test
- options
- state_machine
id: state_machine_test
label: 'State Machine Test'
module: views
description: ''
tag: ''
base_table: entity_test_with_bundle_field_data
base_field: id
core: 8.x
display:
default:
display_plugin: default
id: default
display_title: Master
position: 0
display_options:
access:
type: none
options: { }
cache:
type: tag
options: { }
query:
type: views_query
options:
disable_sql_rewrite: false
distinct: false
replica: false
query_comment: ''
query_tags: { }
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
pager:
type: mini
options:
items_per_page: 10
offset: 0
id: 0
total_pages: null
expose:
items_per_page: false
items_per_page_label: 'Items per page'
items_per_page_options: '5, 10, 25, 50'
items_per_page_options_all: false
items_per_page_options_all_label: '- All -'
offset: false
offset_label: Offset
tags:
previous: ‹‹
next: ››
style:
type: table
row:
type: fields
fields:
name:
table: entity_test_with_bundle_field_data
field: name
id: name
entity_type: null
entity_field: name
plugin_id: field
relationship: none
group_type: group
admin_label: ''
label: Name
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: string
settings: { }
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
field_state:
id: field_state
table: entity_test_with_bundle__field_state
field: field_state
relationship: none
group_type: group
admin_label: ''
label: State
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: list_default
settings: { }
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
plugin_id: field
field_state_1:
id: field_state_1
table: entity_test_with_bundle__field_state
field: field_state
relationship: none
group_type: group
admin_label: ''
label: Actions
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: state_transition_form
settings: { }
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
plugin_id: field
filters:
field_state_value:
id: field_state_value
table: entity_test_with_bundle__field_state
field: field_state_value
relationship: none
group_type: group
admin_label: ''
operator: in
value: { }
group: 1
exposed: true
expose:
operator_id: field_state_value_op
label: State
description: ''
use_operator: false
operator: field_state_value_op
identifier: field_state_value
required: false
remember: false
multiple: false
remember_roles:
authenticated: authenticated
anonymous: '0'
administrator: '0'
merchant: '0'
reduce: false
is_grouped: false
group_info:
label: ''
description: ''
identifier: ''
optional: true
widget: select
multiple: false
remember: false
default_group: All
default_group_multiple: { }
group_items: { }
plugin_id: state_machine_state
sorts: { }
title: 'State Machine Test'
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url
- url.query_args
tags:
- 'config:field.storage.entity_test_with_bundle.field_state'
page_1:
display_plugin: page
id: page_1
display_title: Page
position: 1
display_options:
display_extenders: { }
path: state-machine-test
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url
- url.query_args
tags:
- 'config:field.storage.entity_test_with_bundle.field_state'
@@ -0,0 +1,123 @@
<?php
namespace Drupal\state_machine_test\EventSubscriber;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class WorkflowTransitionEventSubscriber implements EventSubscriberInterface {
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Constructs a new WorkflowTransitionEventSubscriber object.
*
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(MessengerInterface $messenger) {
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [
'entity_test_with_bundle.create.pre_transition' => 'onPreTransition',
'entity_test_with_bundle.create.post_transition' => 'onPostTransition',
'entity_test_with_bundle.pre_transition' => 'onGroupPreTransition',
'entity_test_with_bundle.post_transition' => 'onGroupPostTransition',
'state_machine.pre_transition' => 'onGenericPreTransition',
'state_machine.post_transition' => 'onGenericPostTransition',
];
return $events;
}
/**
* Reacts to the 'entity_test_with_bundle.create.pre_transition' event.
*
* @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
* The transition event.
*/
public function onPreTransition(WorkflowTransitionEvent $event) {
$this->setMessage($event, 'pre-transition');
}
/**
* Reacts to the 'entity_test_with_bundle.create.post_transition' event.
*
* @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
* The transition event.
*/
public function onPostTransition(WorkflowTransitionEvent $event) {
$this->setMessage($event, 'post-transition');
}
/**
* Reacts to the 'entity_test_with_bundle.pre_transition' event.
*
* @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
* The transition event.
*/
public function onGroupPreTransition(WorkflowTransitionEvent $event) {
$this->setMessage($event, 'group pre-transition');
}
/**
* Reacts to the 'entity_test_with_bundle.post_transition' event.
*
* @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
* The transition event.
*/
public function onGroupPostTransition(WorkflowTransitionEvent $event) {
$this->setMessage($event, 'group post-transition');
}
/**
* Reacts to the 'state_machine.pre_transition' event.
*
* @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
* The transition event.
*/
public function onGenericPreTransition(WorkflowTransitionEvent $event) {
$this->setMessage($event, 'generic pre-transition');
}
/**
* Reacts to the 'state_machine.post_transition' event.
*
* @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
* The transition event.
*/
public function onGenericPostTransition(WorkflowTransitionEvent $event) {
$this->setMessage($event, 'generic post-transition');
}
/**
* Sets a message with event information for test purposes.
*
* @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
* The transition event.
* @param string $phase
* The phase during which the event occurred.
*/
protected function setMessage(WorkflowTransitionEvent $event, $phase) {
$this->messenger->addMessage(new TranslatableMarkup('@entity_label (@field_name) - @state_label at @phase (workflow: @workflow, transition: @transition).', [
'@entity_label' => (string) $event->getEntity()->label(),
'@field_name' => $event->getFieldName(),
'@state_label' => $event->getTransition()->getToState()->getLabel(),
'@workflow' => $event->getWorkflow()->getId(),
'@transition' => $event->getTransition()->getId(),
'@phase' => $phase,
]));
}
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\state_machine_test\Guard;
use Drupal\Core\Entity\EntityInterface;
use Drupal\state_machine\Guard\GuardInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowTransition;
class FulfillmentGuard implements GuardInterface {
/**
* {@inheritdoc}
*/
public function allowed(WorkflowTransition $transition, WorkflowInterface $workflow, EntityInterface $entity) {
// Don't allow entities in fulfillment to be cancelled.
if ($transition->getId() == 'cancel' && $entity->field_state->first()->value == 'fulfillment') {
return FALSE;
}
return TRUE;
}
}
@@ -0,0 +1,42 @@
<?php
namespace Drupal\state_machine_test\Guard;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\state_machine\Guard\GuardInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowInterface;
use Drupal\state_machine\Plugin\Workflow\WorkflowTransition;
class GenericGuard implements GuardInterface {
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Constructs a new GenericGuard object.
*
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(AccountInterface $current_user) {
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public function allowed(WorkflowTransition $transition, WorkflowInterface $workflow, EntityInterface $entity) {
// Only a "supervisor" user can cancel an entity in validation.
if ($transition->getId() == 'cancel' && $entity->field_state->first()->value == 'validation') {
return (bool) array_intersect(['merchant'], $this->currentUser->getRoles());
}
return TRUE;
}
}
@@ -0,0 +1,11 @@
name: State Machine Test
type: module
package: Testing
dependencies:
- drupal:entity_test
- state_machine:state_machine
# Information added by Drupal.org packaging script on 2024-07-23
version: '8.x-1.12'
project: 'state_machine'
datestamp: 1721740594
@@ -0,0 +1,46 @@
<?php
/**
* @file
* Test module for State Machine.
*/
use Drupal\views\EntityViewsData;
/**
* Implements hook_entity_type_build().
*/
function state_machine_test_entity_type_build(array &$entity_types) {
$entity_types['entity_test_with_bundle']->setHandlerClass('views_data', EntityViewsData::class);
}
/**
* Workflow callback for the "Second" bundle of entity_test_with_bundle.
*/
function state_machine_test_workflow_callback() {
return 'validation';
}
/**
* Implements hook_entity_type_alter().
*/
function state_machine_test_entity_type_alter(array &$entity_types) {
/** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
if (isset($entity_types['entity_test_with_bundle'])) {
$entity_types['entity_test_with_bundle']->setLinkTemplate('state-transition-form', '/entity_test_with_bundle/{entity_test_with_bundle}/{field_name}/{transition_id}');
}
}
/**
* Implements hook_module_implements_alter().
*/
function state_machine_test_module_implements_alter(&$implementations, $hook) {
// Ensure state_machine_entity_type_alter() runs after
// state_machine_test_entity_type_alter() which specifies the link template
// which is checked in state_machine_entity_type_alter().
if ($hook === 'entity_type_alter') {
$group = $implementations['state_machine'];
unset($implementations['state_machine']);
$implementations['state_machine'] = $group;
}
}
@@ -0,0 +1,17 @@
services:
state_machine_test.fulfillment_guard:
class: Drupal\state_machine_test\Guard\FulfillmentGuard
tags:
- { name: state_machine.guard, group: entity_test_with_bundle }
state_machine_test.generic_guard:
class: Drupal\state_machine_test\Guard\GenericGuard
arguments: ['@current_user']
tags:
- { name: state_machine.guard }
state_machine_test.event_subscriber:
class: Drupal\state_machine_test\EventSubscriber\WorkflowTransitionEventSubscriber
arguments: ['@messenger']
tags:
- { name: event_subscriber }
@@ -0,0 +1,3 @@
entity_test_with_bundle:
label: Test
entity_type: entity_test_with_bundle
@@ -0,0 +1,101 @@
default:
id: default
label: Default
group: entity_test_with_bundle
states:
new:
label: New
fulfillment:
label: Fulfillment
completed:
label: Completed
canceled:
label: Canceled
transitions:
create:
label: Create
from: [new]
to: fulfillment
fulfill:
label: Fulfill
from: [fulfillment]
to: completed
cancel:
label: Cancel
from: [new, fulfillment]
to: canceled
validation:
id: validation
label: Validation
group: entity_test_with_bundle
states:
new:
label: New
validation:
label: Validation
fulfillment:
label: Fulfillment
completed:
label: Completed
canceled:
label: Canceled
transitions:
create:
label: Create
from: [new]
to: validation
validate:
label: Validate
from: [validation]
to: fulfillment
fulfill:
label: Fulfill
from: [fulfillment]
to: completed
cancel:
label: Cancel
from: [new, validation, fulfillment]
to: canceled
two_transitions:
id: two_transitions
label: Two transitions
group: entity_test_with_bundle
states:
new:
label: New
completed:
label: Completed
transitions:
complete1:
label: Complete1
from: [new]
to: completed
complete2:
label: Complete2
from: [new]
to: completed
same_transition:
id: same_transition
label: Contains transition to same state.
group: entity_test_with_bundle
states:
new:
label: New
completed:
label: Completed
transitions:
complete1:
label: Complete1
from: [new]
to: completed
complete2:
label: Complete2
from: [new]
to: completed
same:
label: Stay same
from: [new]
to: new
@@ -0,0 +1,82 @@
<?php
namespace Drupal\Tests\state_machine\Functional;
use Drupal\entity_test\Entity\EntityTestWithBundle;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the Views state filter.
*
* @group state_machine
*/
class StateFilterTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'entity_test',
'options',
'state_machine',
'state_machine_test',
'views',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$user = $this->drupalCreateUser(['administer entity_test content']);
$this->drupalLogin($user);
}
/**
* Tests the filter.
*/
public function testFilter() {
$first_entity = EntityTestWithBundle::create([
'type' => 'first',
'name' => 'First',
]);
$first_entity->save();
$second_entity = EntityTestWithBundle::create([
'type' => 'second',
'name' => 'Second',
'field_state' => 'validation',
]);
$second_entity->save();
$this->drupalGet('/state-machine-test');
$this->assertSession()->pageTextContains('First');
$this->assertSession()->pageTextContains('New');
$this->assertSession()->pageTextContains('Second');
$this->assertSession()->pageTextContains('Validation');
// Confirm that the states from both workflows are in the dropdown.
$expected_options = [
'All' => '- Any -',
'new' => 'New',
'validation' => 'Validation',
'fulfillment' => 'Fulfillment',
'completed' => 'Completed',
'canceled' => 'Canceled',
];
$elements = $this->xpath('//select[@name="field_state_value"]/option');
$found_options = [];
foreach ($elements as $element) {
$found_options[$element->getValue()] = $element->getText();
}
$this->assertEquals($expected_options, $found_options);
}
}
@@ -0,0 +1,153 @@
<?php
namespace Drupal\Tests\state_machine\Functional;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTestWithBundle;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the state transition form.
*
* @group state_machine
*/
class StateTransitionFormTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'entity_test',
'options',
'state_machine',
'state_machine_test',
'views',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$user = $this->drupalCreateUser(['administer entity_test content', 'view test entity']);
$this->drupalLogin($user);
}
/**
* Tests the transition form.
*/
public function testForm() {
$first_entity = EntityTestWithBundle::create([
'type' => 'first',
'name' => 'First',
]);
$first_entity->save();
$second_entity = EntityTestWithBundle::create([
'type' => 'second',
'name' => 'Second',
'field_state' => 'validation',
]);
$second_entity->save();
$this->drupalGet('/state-machine-test');
$this->assertSession()->pageTextContains('First');
$this->assertSession()->pageTextContains('New');
$buttons = $this->xpath('//form[@id="state-machine-transition-form-entity-test-with-bundle-field-state-1"]/div/input');
$this->assertCount(2, $buttons);
$this->assertEquals('Create', $buttons[0]->getValue());
$this->assertEquals('Cancel', $buttons[1]->getValue());
$this->assertSession()->pageTextContains('Second');
$this->assertSession()->pageTextContains('Validation');
$buttons = $this->xpath('//form[@id="state-machine-transition-form-entity-test-with-bundle-field-state-2"]/div/input');
$this->assertCount(1, $buttons);
$this->assertEquals('Validate', $buttons[0]->getValue());
// Click the Validate button.
$buttons[0]->click();
$this->assertSession()->pageTextContains('First');
$this->assertSession()->pageTextContains('New');
$buttons = $this->xpath('//form[@id="state-machine-transition-form-entity-test-with-bundle-field-state-1"]/div/input');
$this->assertCount(2, $buttons);
$this->assertEquals('Create', $buttons[0]->getValue());
$this->assertEquals('Cancel', $buttons[1]->getValue());
$this->assertSession()->buttonExists('Create');
$this->assertSession()->pageTextContains('Second');
$this->assertSession()->pageTextContains('Fulfillment');
$buttons = $this->xpath('//form[@id="state-machine-transition-form-entity-test-with-bundle-field-state-2"]/div/input');
$this->assertCount(1, $buttons);
$this->assertEquals('Fulfill', $buttons[0]->getValue());
}
/**
* Tests the confirmation form.
*/
public function testConfirmationForm() {
$view_display = EntityViewDisplay::create([
'targetEntityType' => 'entity_test_with_bundle',
'bundle' => 'first',
'mode' => 'default',
'status' => TRUE,
]);
$view_display->setComponent('field_state', [
'type' => 'state_transition_form',
'settings' => [
'require_confirmation' => TRUE,
],
]);
$view_display->save();
$first_entity = EntityTestWithBundle::create([
'type' => 'first',
'name' => 'First',
]);
$first_entity->save();
$this->drupalGet($first_entity->toUrl('canonical'));
$this->assertSession()->pageTextContains('First');
$buttons = $this->xpath('//form[@id="state-machine-transition-form-entity-test-with-bundle-field-state-1"]/div/a');
$this->assertCount(2, $buttons);
$this->assertEquals('Create', $buttons[0]->getText());
$this->assertEquals('Cancel', $buttons[1]->getText());
$this->assertSession()->linkExists('Create');
// Click the Create button.
$buttons[0]->click();
$this->assertSession()->pageTextContains('Are you sure you want to apply this transition?');
$this->assertSession()->pageTextContains('From: New');
$this->assertSession()->pageTextContains('To: Fulfillment');
$this->assertSession()->pageTextContains('Transition: Create');
$this->assertSession()->pageTextContains('Test entity with bundle: First');
$this->assertSession()->pageTextContains('This action cannot be undone.');
$this->assertSession()->linkExists('Cancel');
$this->submitForm([], 'Confirm');
$buttons = $this->xpath('//form[@id="state-machine-transition-form-entity-test-with-bundle-field-state-1"]/div/a');
$this->assertCount(1, $buttons);
$this->assertEquals('Fulfill', $buttons[0]->getText());
$transitions = [
'create' => 403,
'cancel' => 403,
'fulfill' => 200,
];
// Ensure the state transition form route doesn't allow access for
// transitions that are not allowed.
foreach ($transitions as $transition_id => $expected_status_code) {
$route = Url::fromRoute('entity.entity_test_with_bundle.state_transition_form', [
'entity_test_with_bundle' => $first_entity->id(),
'field_name' => 'field_state',
'transition_id' => $transition_id,
]);
$this->drupalGet($route);
$this->assertSession()->statusCodeEquals($expected_status_code);
}
}
}
@@ -0,0 +1,82 @@
<?php
namespace Drupal\Tests\state_machine\FunctionalJavascript;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\entity_test\Entity\EntityTestWithBundle;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests the state transition form.
*
* @group state_machine
*/
class StateTransitionFormTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'entity_test',
'state_machine_test',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$user = $this->drupalCreateUser(['administer entity_test content', 'view test entity']);
$this->drupalLogin($user);
}
/**
* Tests the confirmation form rendered in a modal.
*/
public function testConfirmationFormWithModal() {
$view_display = EntityViewDisplay::create([
'targetEntityType' => 'entity_test_with_bundle',
'bundle' => 'first',
'mode' => 'default',
'status' => TRUE,
]);
$view_display->setComponent('field_state', [
'type' => 'state_transition_form',
'settings' => [
'require_confirmation' => TRUE,
'use_modal' => TRUE,
],
]);
$view_display->save();
$first_entity = EntityTestWithBundle::create([
'type' => 'first',
'name' => 'First',
]);
$first_entity->save();
$this->drupalGet($first_entity->toUrl('canonical'));
$this->assertSession()->pageTextContains('First');
$buttons = $this->xpath('//form[@id="state-machine-transition-form-entity-test-with-bundle-field-state-1"]/div/a');
$this->assertCount(2, $buttons);
$this->assertEquals('Create', $buttons[0]->getText());
$this->assertEquals('Cancel', $buttons[1]->getText());
// Click the Create link.
$buttons[0]->click();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->pageTextContains('Are you sure you want to apply this transition?');
$this->assertSession()->pageTextContains('From: New');
$this->assertSession()->pageTextContains('To: Fulfillment');
$this->assertSession()->pageTextContains('Transition: Create');
$this->assertSession()->pageTextContains('Test entity with bundle: First');
$this->assertSession()->pageTextContains('This action cannot be undone.');
$this->assertSession()->linkExists('Cancel');
$this->assertSession()->buttonExists('Confirm');
}
}
@@ -0,0 +1,196 @@
<?php
namespace Drupal\Tests\state_machine\Kernel;
use Drupal\entity_test\Entity\EntityTestWithBundle;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
/**
* @coversDefaultClass \Drupal\state_machine\Plugin\Field\FieldType\StateItem
* @group state_machine
*/
class StateItemTest extends FieldKernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'entity_test',
'field',
'user',
'state_machine',
'state_machine_test',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('user');
$this->installEntitySchema('entity_test_with_bundle');
$this->installConfig(['state_machine_test']);
}
/**
* @covers ::applyTransitionById
*/
public function testInvalidTransitionApply() {
$entity = EntityTestWithBundle::create([
'name' => 'first',
'type' => 'first',
]);
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $entity->get('field_state')->first();
$this->expectException(\InvalidArgumentException::class);
$state_item->applyTransitionById('INVALID');
}
/**
* @dataProvider providerTestField
*/
public function testField($initial_state, $allowed_transitions, $invalid_new_state, $valid_transition, $expected_new_state) {
$entity = EntityTestWithBundle::create([
'name' => 'second',
'type' => 'second',
'field_state' => $initial_state,
]);
$this->assertEquals($initial_state, $entity->get('field_state')->value);
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $entity->get('field_state')->first();
// Confirm that the transitions are correct.
$transitions = $state_item->getTransitions();
$this->assertCount(count($allowed_transitions), $transitions);
$this->assertEquals($allowed_transitions, array_keys($transitions));
if (count($allowed_transitions) > 0) {
foreach ($allowed_transitions as $transition_id) {
$this->assertTrue($state_item->isTransitionAllowed($transition_id));
}
}
$this->assertFalse($state_item->isTransitionAllowed('foo'));
// Confirm that invalid states are recognized.
if ($invalid_new_state) {
$state_item->value = $invalid_new_state;
$this->assertEquals($initial_state, $state_item->getOriginalId());
$this->assertEquals($invalid_new_state, $state_item->getId());
$this->assertFalse($state_item->isValid());
}
// Revert to the initial state because the valid transaction could be
// invalid from the invalid_new_state.
$state_item->value = $initial_state;
// Retrieve all workflow transitions.
$workflow = $state_item->getWorkflow();
$all_transitions = $workflow->getTransitions();
// Pick a random invalid transition and assert it throws an Exception.
$invalid_transitions = array_diff_key($all_transitions, $transitions);
if ($invalid_transitions) {
$random_key = array_rand($invalid_transitions);
$this->expectException(\InvalidArgumentException::class);
$state_item->applyTransition($invalid_transitions[$random_key]);
// Also try applying by ID.
$this->expectException(\InvalidArgumentException::class);
$state_item->applyTransitionById($random_key);
}
$state_item->applyTransitionById($valid_transition);
$this->assertEquals($initial_state, $state_item->getOriginalId());
$this->assertEquals($expected_new_state, $state_item->getId());
$this->assertTrue($state_item->isValid());
}
/**
* Data provider for ::testField.
*
* @return array
* A list of testField function arguments.
*/
public static function providerTestField() {
$data = [];
$data['new->validation'] = ['new', ['create', 'cancel'], 'fulfillment', 'create', 'validation'];
$data['new->canceled'] = ['new', ['create', 'cancel'], 'completed', 'cancel', 'canceled'];
// The workflow defines validation->fulfillment and validation->canceled
// transitions, but the second one is forbidden by the GenericGuard.
$data['validation->fulfillment'] = ['validation', ['validate'], 'completed', 'validate', 'fulfillment'];
// The workflow defines fulfillment->completed and fulfillment->canceled
// transitions, but the second one is forbidden by the FulfillmentGuard.
$data['fulfillment->completed'] = ['fulfillment', ['fulfill'], 'new', 'fulfill', 'completed'];
return $data;
}
/**
* @dataProvider providerSettableOptions
*/
public function testSettableOptions($initial_state, $available_options) {
$entity = EntityTestWithBundle::create([
'name' => 'second',
'type' => 'second',
'field_state' => $initial_state,
]);
$this->assertEquals($initial_state, $entity->get('field_state')->value);
// An invalid state should not have any settable options.
$this->assertEquals($available_options, $entity->get('field_state')->first()->getSettableOptions());
}
/**
* Data provider for ::providerSettableOptions.
*
* @return array
* A list of providerSettableOptions function arguments.
*/
public static function providerSettableOptions() {
$data = [];
$data['new'] = ['new', ['canceled' => 'Canceled', 'validation' => 'Validation', 'new' => 'New']];
$data['invalid'] = ['invalid', []];
return $data;
}
/**
* @covers ::generateSampleValue
*/
public function testGenerateSampleValue() {
$entity = EntityTestWithBundle::create([
'name' => 'first',
'type' => 'first',
'field_state' => NULL,
]);
$entity->field_state->generateSampleItems();
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $entity->get('field_state')->first();
$this->assertEquals('default', $state_item->getWorkflow()->getId());
$this->assertNotEmpty($state_item->getId());
$this->assertTrue(in_array($state_item->getId(), array_keys($state_item->getWorkflow()->getStates())));
$this->entityValidateAndSave($entity);
$entity = EntityTestWithBundle::create([
'name' => 'second',
'type' => 'second',
'field_state' => NULL,
]);
$entity->field_state->generateSampleItems();
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $entity->get('field_state')->first();
$this->assertNotEmpty($state_item->getId());
$this->assertTrue(in_array($state_item->getId(), array_keys($state_item->getWorkflow()->getStates())));
$this->entityValidateAndSave($entity);
$entity = EntityTestWithBundle::create([
'name' => 'third',
'type' => 'third',
'field_state' => NULL,
]);
$entity->field_state->generateSampleItems();
/** @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state_item */
$state_item = $entity->get('field_state')->first();
$this->assertEquals('two_transitions', $state_item->getWorkflow()->getId());
$this->assertNotEmpty($state_item->getId());
$this->assertTrue(in_array($state_item->getId(), array_keys($state_item->getWorkflow()->getStates())));
$this->entityValidateAndSave($entity);
}
}
@@ -0,0 +1,155 @@
<?php
namespace Drupal\Tests\state_machine\Kernel;
use Drupal\entity_test\Entity\EntityTestWithBundle;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests the TransitionEvent.
*
* @group state_machine
*/
class WorkflowTransitionEventTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'entity_test',
'field',
'user',
'state_machine',
'state_machine_test',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('user');
$this->installEntitySchema('entity_test_with_bundle');
$this->installConfig(['state_machine_test']);
}
/**
* Tests the transition event.
*/
public function testTransitionEvent() {
$entity = EntityTestWithBundle::create([
'type' => 'first',
'name' => 'Test entity',
'field_state' => 'new',
]);
$entity->save();
$entity->get('field_state')->first()->applyTransitionById('create');
$entity->save();
$messages = \Drupal::messenger()->all();
$message = reset($messages);
$this->assertCount(6, $message);
$this->assertEquals('Test entity (field_state) - Fulfillment at pre-transition (workflow: default, transition: create).', (string) $message[0]);
$this->assertEquals('Test entity (field_state) - Fulfillment at group pre-transition (workflow: default, transition: create).', (string) $message[1]);
$this->assertEquals('Test entity (field_state) - Fulfillment at generic pre-transition (workflow: default, transition: create).', (string) $message[2]);
$this->assertEquals('Test entity (field_state) - Fulfillment at post-transition (workflow: default, transition: create).', (string) $message[3]);
$this->assertEquals('Test entity (field_state) - Fulfillment at group post-transition (workflow: default, transition: create).', (string) $message[4]);
$this->assertEquals('Test entity (field_state) - Fulfillment at generic post-transition (workflow: default, transition: create).', (string) $message[5]);
\Drupal::messenger()->deleteAll();
$entity->get('field_state')->first()->applyTransitionById('fulfill');
$entity->save();
$messages = \Drupal::messenger()->all();
$message = reset($messages);
$this->assertCount(4, $message);
$this->assertEquals('Test entity (field_state) - Completed at group pre-transition (workflow: default, transition: fulfill).', (string) $message[0]);
$this->assertEquals('Test entity (field_state) - Completed at generic pre-transition (workflow: default, transition: fulfill).', (string) $message[1]);
$this->assertEquals('Test entity (field_state) - Completed at group post-transition (workflow: default, transition: fulfill).', (string) $message[2]);
$this->assertEquals('Test entity (field_state) - Completed at generic post-transition (workflow: default, transition: fulfill).', (string) $message[3]);
\Drupal::messenger()->deleteAll();
$entity = EntityTestWithBundle::create([
'type' => 'first',
'name' => 'Test entity 2',
'field_state' => 'new',
]);
$entity->save();
$entity->get('field_state')->first()->applyTransitionById('create');
$entity->save();
$messages = \Drupal::messenger()->all();
$message = reset($messages);
$this->assertCount(6, $message);
$this->assertEquals('Test entity 2 (field_state) - Fulfillment at pre-transition (workflow: default, transition: create).', (string) $message[0]);
$this->assertEquals('Test entity 2 (field_state) - Fulfillment at group pre-transition (workflow: default, transition: create).', (string) $message[1]);
$this->assertEquals('Test entity 2 (field_state) - Fulfillment at generic pre-transition (workflow: default, transition: create).', (string) $message[2]);
$this->assertEquals('Test entity 2 (field_state) - Fulfillment at post-transition (workflow: default, transition: create).', (string) $message[3]);
$this->assertEquals('Test entity 2 (field_state) - Fulfillment at group post-transition (workflow: default, transition: create).', (string) $message[4]);
$this->assertEquals('Test entity 2 (field_state) - Fulfillment at generic post-transition (workflow: default, transition: create).', (string) $message[5]);
\Drupal::messenger()->deleteAll();
// Ensure manually setting the state to "create", triggers the cancel
// transition and not the 'fulfill' transition previously applied.
$entity->set('field_state', 'canceled');
$entity->save();
$messages = \Drupal::messenger()->all();
$message = reset($messages);
$this->assertCount(4, $message);
$this->assertEquals('Test entity 2 (field_state) - Canceled at group pre-transition (workflow: default, transition: cancel).', (string) $message[0]);
$this->assertEquals('Test entity 2 (field_state) - Canceled at generic pre-transition (workflow: default, transition: cancel).', (string) $message[1]);
$this->assertEquals('Test entity 2 (field_state) - Canceled at group post-transition (workflow: default, transition: cancel).', (string) $message[2]);
$this->assertEquals('Test entity 2 (field_state) - Canceled at generic post-transition (workflow: default, transition: cancel).', (string) $message[3]);
}
/**
* Tests the transition event with two identical to and from states.
*/
public function testTransitionEventTwoTransitions() {
$entity = EntityTestWithBundle::create([
'type' => 'third',
'name' => 'Test entity',
'field_state' => 'new',
]);
$entity->save();
// Test that applying the second transition also throws the second transition's event.
$entity->get('field_state')->first()->applyTransitionById('complete2');
$entity->save();
$messages = \Drupal::messenger()->all();
$message = reset($messages);
$this->assertCount(4, $message);
$this->assertEquals('Test entity (field_state) - Completed at group pre-transition (workflow: two_transitions, transition: complete2).', (string) $message[0]);
$this->assertEquals('Test entity (field_state) - Completed at generic pre-transition (workflow: two_transitions, transition: complete2).', (string) $message[1]);
$this->assertEquals('Test entity (field_state) - Completed at group post-transition (workflow: two_transitions, transition: complete2).', (string) $message[2]);
$this->assertEquals('Test entity (field_state) - Completed at generic post-transition (workflow: two_transitions, transition: complete2).', (string) $message[3]);
}
/**
* Tests the transition event when a state transition occurs to same value.
*/
public function testTransitionEventSameState() {
$entity = EntityTestWithBundle::create([
'type' => 'fourth',
'name' => 'Test entity',
'field_state' => 'new',
]);
$entity->save();
// Test that explicitly specifying the transition to same fires event.
$entity->get('field_state')->first()->applyTransitionById('same');
$entity->save();
$messages = \Drupal::messenger()->all();
$this->assertCount(4, $messages['status']);
\Drupal::messenger()->deleteAll();
// Test that simply setting the value to same as existing does not dispatch.
$entity->get('field_state')->first()->setValue('new');
$entity->save();
$this->assertEmpty(\Drupal::messenger()->all());
}
}
@@ -0,0 +1,246 @@
<?php
namespace Drupal\Tests\state_machine\Unit\Plugin\Workflow;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\state_machine\Guard\GuardFactoryInterface;
use Drupal\state_machine\Guard\GuardInterface;
use Drupal\state_machine\Plugin\Workflow\Workflow;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\state_machine\Plugin\Workflow\Workflow
* @group state_machine
*/
class WorkflowTest extends UnitTestCase {
/**
* @covers ::getId
*/
public function testGetId() {
$guard_factory = $this->prophesize(GuardFactoryInterface::class);
$plugin_definition = [
'id' => 'test id',
'label' => 'test label',
'states' => [],
'transitions' => [],
];
$workflow = new Workflow([], 'test', $plugin_definition, $guard_factory->reveal());
$this->assertEquals('test id', $workflow->getId());
}
/**
* @covers ::getLabel
*/
public function testGetLabel() {
$guard_factory = $this->prophesize(GuardFactoryInterface::class);
$plugin_definition = [
'states' => [],
'transitions' => [],
'label' => 'test label',
];
$workflow = new Workflow([], 'test', $plugin_definition, $guard_factory->reveal());
$this->assertEquals('test label', $workflow->getLabel());
}
/**
* @covers ::getStates
* @covers ::getState
*/
public function testGetStates() {
$guard_factory = $this->prophesize(GuardFactoryInterface::class);
$translation = $this->prophesize(TranslationInterface::class);
$translation->translateString(Argument::type(TranslatableMarkup::class))
->willReturn('Draft');
$plugin_definition = [
'states' => [
'draft' => [
'label' => 'Draft',
],
],
'transitions' => [],
];
$workflow = new Workflow([], 'test', $plugin_definition, $guard_factory->reveal());
$workflow->setStringTranslation($translation->reveal());
$state = $workflow->getState('draft');
$this->assertEquals('draft', $state->getId());
$state->setStringTranslation($translation->reveal());
$this->assertEquals('Draft', $state->getLabel());
$this->assertEquals(['draft' => $state], $workflow->getStates());
}
/**
* @covers ::getTransitions
* @covers ::getTransition
*/
public function testGetTransitions() {
$translation = $this->prophesize(TranslationInterface::class);
$translation->translateString(Argument::type(TranslatableMarkup::class))
->willReturn('Publish');
$guard_factory = $this->prophesize(GuardFactoryInterface::class);
$plugin_definition = [
'states' => [
'draft' => [
'label' => 'Draft',
],
'published' => [
'label' => 'Published',
],
],
'transitions' => [
'publish' => [
'label' => 'Publish',
'from' => ['draft'],
'to' => 'published',
],
],
];
$workflow = new Workflow([], 'test', $plugin_definition, $guard_factory->reveal());
$transition = $workflow->getTransition('publish');
$transition->setStringTranslation($translation->reveal());
$this->assertEquals('publish', $transition->getId());
$this->assertEquals('Publish', $transition->getLabel());
$this->assertEquals(['draft' => $workflow->getState('draft')], $transition->getFromStates());
$this->assertEquals($workflow->getState('published'), $transition->getToState());
$this->assertEquals(['publish' => $transition], $workflow->getTransitions());
}
/**
* @covers ::getPossibleTransitions
*/
public function testGetPossibleTransitions() {
$guard_factory = $this->prophesize(GuardFactoryInterface::class);
$plugin_definition = [
'states' => [
'draft' => [
'label' => 'Draft',
],
'review' => [
'label' => 'Review',
],
'published' => [
'label' => 'Published',
],
],
'transitions' => [
'send_to_review' => [
'label' => 'Send to review',
'from' => ['draft'],
'to' => 'review',
],
'publish' => [
'label' => 'Publish',
'from' => ['review'],
'to' => 'published',
],
],
];
$workflow = new Workflow([], 'test', $plugin_definition, $guard_factory->reveal());
$transition = $workflow->getTransition('send_to_review');
$this->assertEquals(['send_to_review' => $transition], $workflow->getPossibleTransitions('draft'));
$transition = $workflow->getTransition('publish');
$this->assertEquals(['publish' => $transition], $workflow->getPossibleTransitions('review'));
$this->assertEquals([], $workflow->getPossibleTransitions('published'));
// Passing an empty state should return all transitions.
$this->assertEquals($workflow->getTransitions(), $workflow->getPossibleTransitions(''));
}
/**
* @covers ::getAllowedTransitions
*/
public function testGetAllowedTransitions() {
$plugin_definition = [
'states' => [
'draft' => [
'label' => 'Draft',
],
'review' => [
'label' => 'Review',
],
'published' => [
'label' => 'Published',
],
],
'transitions' => [
'send_to_review' => [
'label' => 'Send to review',
'from' => ['draft'],
'to' => 'review',
],
'publish' => [
'label' => 'Publish',
'from' => ['review'],
'to' => 'published',
],
],
'group' => 'default',
];
$guard_allow = $this->prophesize(GuardInterface::class);
$guard_allow
->allowed(Argument::cetera())
->willReturn(TRUE);
$guard_deny_publish = $this->prophesize(GuardInterface::class);
$guard_deny_publish
->allowed(Argument::cetera())
->will(function ($args) {
// Allow only the send_to_review transition.
return $args[0]->getId() == 'send_to_review';
});
$guard_factory = $this->prophesize(GuardFactoryInterface::class);
$guard_factory
->get('default')
->willReturn([$guard_allow->reveal(), $guard_deny_publish->reveal()]);
$workflow = new Workflow([], 'test', $plugin_definition, $guard_factory->reveal());
$entity = $this->prophesize(EntityInterface::class)->reveal();
$transition = $workflow->getTransition('send_to_review');
$this->assertEquals(['send_to_review' => $transition], $workflow->getAllowedTransitions('draft', $entity));
$this->assertEquals([], $workflow->getAllowedTransitions('review', $entity));
}
/**
* @covers ::findTransition
*/
public function testFindTransition() {
$guard_factory = $this->prophesize(GuardFactoryInterface::class);
$plugin_definition = [
'states' => [
'draft' => [
'label' => 'Draft',
],
'review' => [
'label' => 'Review',
],
'published' => [
'label' => 'Published',
],
],
'transitions' => [
'send_to_review' => [
'label' => 'Send to review',
'from' => ['draft'],
'to' => 'review',
],
'publish' => [
'label' => 'Publish',
'from' => ['review'],
'to' => 'published',
],
],
];
$workflow = new Workflow([], 'test', $plugin_definition, $guard_factory->reveal());
$transition = $workflow->getTransition('send_to_review');
$this->assertEquals($transition, $workflow->findTransition('draft', 'review'));
$this->assertNull($workflow->findTransition('foo', 'bar'));
}
}
@@ -0,0 +1,72 @@
<?php
namespace Drupal\Tests\state_machine\Unit\Plugin\WorkflowGroup;
use Drupal\state_machine\Plugin\Workflow\Workflow;
use Drupal\state_machine\Plugin\WorkflowGroup\WorkflowGroup;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\state_machine\Plugin\WorkflowGroup\WorkflowGroup
* @group state_machine
*/
class WorkflowGroupTest extends UnitTestCase {
/**
* The workflow group.
*
* @var \Drupal\state_machine\Plugin\WorkflowGroup\WorkflowGroup
*/
protected $workflowGroup;
/**
* The plugin definition array.
*
* @var array
*/
protected $definition = [
'id' => 'entity_test',
'label' => 'Entity Test',
'entity_type' => 'entity_test',
'class' => WorkflowGroup::class,
'workflow_class' => Workflow::class,
'provider' => 'state_machine_test',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->workflowGroup = new WorkflowGroup([], 'order', $this->definition);
}
/**
* @covers ::getId
*/
public function testGetId() {
$this->assertEquals($this->definition['id'], $this->workflowGroup->getId());
}
/**
* @covers ::getLabel
*/
public function testGetLabel() {
$this->assertEquals($this->definition['label'], $this->workflowGroup->getLabel(), 'Workflow group label matches the expected one');
}
/**
* @covers ::getEntityTypeId
*/
public function testGetEntityTypeId() {
$this->assertEquals($this->definition['entity_type'], $this->workflowGroup->getEntityTypeId(), 'Workflow group entity type id matches the expected one');
}
/**
* @covers ::getWorkflowClass
*/
public function testGetWorkflowClass() {
$this->assertEquals($this->definition['workflow_class'], $this->workflowGroup->getWorkflowClass(), 'Workflow group class matches the expected one');
}
}
@@ -0,0 +1,155 @@
<?php
namespace Drupal\Tests\state_machine\Unit;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\state_machine\Guard\GuardFactoryInterface;
use Drupal\state_machine\Plugin\Workflow\Workflow;
use Drupal\state_machine\Plugin\Workflow\WorkflowInterface;
use Drupal\state_machine\WorkflowGroupManagerInterface;
use Drupal\state_machine\WorkflowManager;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Tests the cache of the workflow manager.
*
* @coversDefaultClass \Drupal\state_machine\WorkflowManager
* @group state_machine
*/
class WorkflowManagerCacheTest extends UnitTestCase {
/**
* An instance of the WorkflowManager. This is the system under test.
*
* @var \Drupal\state_machine\WorkflowManager
*/
protected $workflowManager;
/**
* A mocked instance of the dependency injection container.
*
* @var \Symfony\Component\DependencyInjection\ContainerInterface|\Prophecy\Prophecy\ObjectProphecy
*/
protected $container;
/**
* A mocked instance of the module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface|\Prophecy\Prophecy\ObjectProphecy
*/
protected $moduleHandler;
/**
* A mocked instance of a cache backend.
*
* @var \Drupal\Core\Cache\CacheBackendInterface|\Prophecy\Prophecy\ObjectProphecy
*/
protected $cacheBackend;
/**
* A mocked instance of the workflow group manager.
*
* @var \Drupal\state_machine\WorkflowGroupManagerInterface|\Prophecy\Prophecy\ObjectProphecy
*/
protected $workflowGroupManager;
/**
* The ID of a mocked workflow plugin used in the test.
*
* @var string
*/
protected $pluginId = 'test_workflow';
/**
* The ID of a mocked workflow group used in the test.
*
* @var string
*/
protected $groupId = 'test_group';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->container = $this->prophesize(ContainerInterface::class);
\Drupal::setContainer($this->container->reveal());
// Mock the dependencies to inject into the workflow manager.
$this->moduleHandler = $this->prophesize(ModuleHandlerInterface::class);
$this->cacheBackend = $this->prophesize(CacheBackendInterface::class);
$this->workflowGroupManager = $this->prophesize(WorkflowGroupManagerInterface::class);
// Instantiate the workflow manager. This is the system under test.
$this->workflowManager = new WorkflowManager(
$this->moduleHandler->reveal(),
$this->cacheBackend->reveal(),
$this->workflowGroupManager->reveal()
);
}
/**
* Tests that workflow plugins are cached upon creation.
*
* @covers ::createInstance
*/
public function testCreateInstance() {
// In this test we will ask the workflow manager repeatedly for an instance
// of a single workflow plugin. Since the manager is supposed to cache the
// plugins, it is expected that the GuardFactory (which is a dependency of
// the Workflow plugin) is not retrieved more than once from the container.
$guard_factory = $this->prophesize(GuardFactoryInterface::class);
$this->container->get('state_machine.guard_factory')
->willReturn($guard_factory->reveal())
->shouldBeCalledOnce();
// It is expected that the workflow manager will retrieve the complete list
// of workflows from the cache backend in order to look up the definition of
// the workflow plugin that we are creating. Even though we are creating
// multiple instances, this should only be called once since the result
// should be cached in memory.
$this->cacheBackend->get('workflow')
->willReturn((object) [
'data' => $this->getMockWorkflowDefinitions(),
])
->shouldBeCalledOnce();
// Once it found the workflow definition, it is expected that the workflow
// group manager will be asked for the definition of the workflow plugin
// that is used by the group. The workflow manager requires this data in
// order to discover the class name of the workflow plugin so that it can be
// instantiated. This too should be called only once.
$this->workflowGroupManager->getDefinition($this->groupId)
->willReturn([
'workflow_class' => Workflow::class,
])
->shouldBeCalledOnce();
// Request the same plugin instance multiple times from the workflow
// manager. The first instance is cached, and all subsequent invocations
// will retrieve the instance from cache.
for ($i = 0; $i < 5; $i++) {
$plugin = $this->workflowManager->createInstance($this->pluginId);
$this->assertInstanceOf(WorkflowInterface::class, $plugin);
}
}
/**
* Gets a mocked workflow plugin definition.
*
* @return array
* The mocked workflow definition.
*/
protected function getMockWorkflowDefinitions() {
return [
'test_workflow' => [
'group' => $this->groupId,
'states' => [],
'transitions' => [],
],
];
}
}
@@ -0,0 +1,4 @@
"*.workflow.yml":
- label
"*.workflow_groups.yml":
- label