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

+98
View File
@@ -0,0 +1,98 @@
################
# 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'
- '/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:
OPT_IN_TEST_PREVIOUS_MINOR: 1
_PHPUNIT_CONCURRENT: 1
###################################################################################
#
# *
# /(
# ((((,
# /(((((((
# ((((((((((*
# ,(((((((((((((((
# ,(((((((((((((((((((
# ((((((((((((((((((((((((*
# *(((((((((((((((((((((((((((((
# ((((((((((((((((((((((((((((((((((*
# *(((((((((((((((((( .((((((((((((((((((
# ((((((((((((((((((. /(((((((((((((((((*
# /((((((((((((((((( .(((((((((((((((((,
# ,(((((((((((((((((( ((((((((((((((((((
# .(((((((((((((((((((( .(((((((((((((((((
# ((((((((((((((((((((((( ((((((((((((((((/
# (((((((((((((((((((((((((((/ ,(((((((((((((((*
# .((((((((((((((/ /(((((((((((((. ,(((((((((((((((
# *(((((((((((((( ,(((((((((((((/ *((((((((((((((.
# ((((((((((((((, /(((((((((((((. ((((((((((((((,
# (((((((((((((/ ,(((((((((((((* ,(((((((((((((,
# *((((((((((((( .((((((((((((((( ,(((((((((((((
# ((((((((((((/ /((((((((((((((((((. ,((((((((((((/
# ((((((((((((( *(((((((((((((((((((((((* *((((((((((((
# ((((((((((((( ,(((((((((((((..((((((((((((( *((((((((((((
# ((((((((((((, /((((((((((((* /((((((((((((/ ((((((((((((
# ((((((((((((( /((((((((((((/ (((((((((((((* ((((((((((((
# (((((((((((((/ /(((((((((((( ,((((((((((((, *((((((((((((
# (((((((((((((( *(((((((((((/ *((((((((((((. ((((((((((((/
# *((((((((((((((((((((((((((, /(((((((((((((((((((((((((
# ((((((((((((((((((((((((( ((((((((((((((((((((((((,
# .(((((((((((((((((((((((/ ,(((((((((((((((((((((((
# ((((((((((((((((((((((/ ,(((((((((((((((((((((/
# *((((((((((((((((((((( (((((((((((((((((((((,
# ,(((((((((((((((((((((, ((((((((((((((((((((/
# ,(((((((((((((((((((((* /((((((((((((((((((((
# ((((((((((((((((((((((, ,/((((((((((((((((((((,
# ,(((((((((((((((((((((((((((((((((((((((((((((((((((
# .(((((((((((((((((((((((((((((((((((((((((((((
# .((((((((((((((((((((((((((((((((((((,.
# .,(((((((((((((((((((((((((.
#
###################################################################################
+58
View File
@@ -0,0 +1,58 @@
language: php
sudo: false
php:
- 5.5
- 5.6
- 7
- hhvm
matrix:
allow_failures:
# We cannot use hhvm-nightly since that does not work in Travis CI's old
# Ubuntu 12.04.
- php: hhvm
# Don't wait for the allowed failures to build.
fast_finish: true
mysql:
database: entity
username: root
encoding: utf8
before_script:
# Remove Xdebug as we don't need it and it causes
# PHP Fatal error: Maximum function nesting level of '256' reached.
# We also don't care if that file exists or not on PHP 7.
- phpenv config-rm xdebug.ini || true
# Remember the current entity test directory for later use in the Drupal
# installation.
- TESTDIR=$(pwd)
# Navigate out of module directory to prevent blown stack by recursive module
# lookup.
- cd ..
# Create database.
- mysql -e 'create database entity'
# Export database variable for kernel tests.
- export SIMPLETEST_DB=mysql://root:@127.0.0.1/entity
# Download Drupal 8 core.
- travis_retry git clone --branch 8.5.x --depth 1 http://git.drupal.org/project/drupal.git
- cd drupal
- composer self-update
- composer install -n
# Reference entity in build site.
- ln -s $TESTDIR modules/entity
# Start a web server on port 8888, run in the background; wait for
# initialization.
- nohup php -S localhost:8888 > /dev/null 2>&1 &
# Export web server URL for browser tests.
- export SIMPLETEST_BASE_URL=http://localhost:8888
script:
# Run the PHPUnit tests which also include the kernel tests.
- ./vendor/phpunit/phpunit/phpunit -c ./core/phpunit.xml.dist --verbose ./modules/entity
+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.
+7
View File
@@ -0,0 +1,7 @@
This file was automatically generated by Composer Patches (https://github.com/cweagans/composer-patches)
Patches applied to this directory:
Issue #3206703: Provide reverse relationships for bundle plugin entity_reference fields.
Source: https://www.drupal.org/files/issues/2024-08-30/3206703-12.patch
+16
View File
@@ -0,0 +1,16 @@
Entity API module
-----------------
Provides improvements and extensions to the Drupal 8 Entity system.
Acts as a staging ground for Drupal core, with each core minor release (8.5, 8.6, 8.7)
receiving a portion of this module's functionality.
Current functionality:
- Local action providers (core issue: #2976861)
- Local task providers
- Permission providers (core issue: #2809177)
- Query access API (Change record: https://www.drupal.org/node/3002038, core issue: #777578)
- Bundle plugin API (plugin-based entity bundles, currently not proposed for core inclusion)
- A generic UI for revisions (WIP, see #2625122)
- Duplicate entity UI
- EntityViewsData handler with many improvements over the one in core.
+11
View File
@@ -0,0 +1,11 @@
{
"name": "drupal/entity",
"description": "Provides expanded entity APIs, which will be moved to Drupal core one day.",
"type": "drupal-module",
"license": "GPL-2.0-or-later",
"homepage": "https://www.drupal.org/project/entity",
"support": {
"issues": "https://www.drupal.org/project/issues/entity",
"source": "https://git.drupalcode.org/project/entity"
}
}
@@ -0,0 +1,11 @@
action.configuration.entity_delete_action:*:
type: action_configuration_default
label: 'Delete entity configuration'
views.field.entity_link_revision:
type: views.field.entity_link
label: 'Entity revision link'
views.field.entity_link_revision_revert:
type: views.field.entity_link
label: 'Entity revision revert link'
+9
View File
@@ -0,0 +1,9 @@
name: Entity
description: Provides expanded entity APIs, which will be moved to Drupal core one day.
type: module
core_version_requirement: "^10.1 || ^11"
# Information added by Drupal.org packaging script on 2024-08-11
version: '8.x-1.5'
project: 'entity'
datestamp: 1723380065
@@ -0,0 +1,2 @@
entity.entity_actions:
deriver: Drupal\entity\Plugin\Derivative\EntityActionsDeriver
+2
View File
@@ -0,0 +1,2 @@
entity.entity_tasks:
deriver: Drupal\entity\Plugin\Derivative\EntityTasksDeriver
+221
View File
@@ -0,0 +1,221 @@
<?php
/**
* @file
* Provides expanded entity APIs.
*/
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\entity\BundlePlugin\BundlePluginHandler;
use Drupal\entity\QueryAccess\Condition;
use Drupal\entity\QueryAccess\EntityQueryAlter;
use Drupal\entity\QueryAccess\ViewsQueryAlter;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ViewExecutable;
/**
* Implements hook_entity_operation().
*/
function entity_entity_operation(EntityInterface $entity) {
$operations = [];
$entity_type = $entity->getEntityType();
if ($entity_type->hasLinkTemplate('duplicate-form') && $entity->access('duplicate')) {
$operations['duplicate'] = [
'title' => t('Duplicate'),
'weight' => 40,
'url' => $entity->toUrl('duplicate-form'),
];
}
return $operations;
}
/**
* Gets the entity types which use bundle plugins.
*
* @return \Drupal\Core\Entity\EntityTypeInterface[]
* The entity types.
*/
function entity_get_bundle_plugin_entity_types() {
$entity_types = \Drupal::entityTypeManager()->getDefinitions();
$entity_types = array_filter($entity_types, function (EntityTypeInterface $entity_type) {
return $entity_type->hasHandlerClass('bundle_plugin');
});
return $entity_types;
}
/**
* Implements hook_entity_type_build().
*/
function entity_entity_type_build(array &$entity_types) {
foreach ($entity_types as $entity_type) {
if ($entity_type->get('bundle_plugin_type')) {
if (!$entity_type->hasKey('bundle')) {
throw new \LogicException(sprintf('The %s entity type uses a bundle plugin type but has no bundle key.', $entity_type->id()));
}
if (!$entity_type->hasHandlerClass('bundle_plugin')) {
$entity_type->setHandlerClass('bundle_plugin', BundlePluginHandler::class);
}
}
}
}
/**
* Implements hook_entity_type_alter().
*/
function entity_entity_type_alter(array &$entity_types) {
/** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
foreach ($entity_types as $entity_type_id => $entity_type) {
// Sets a default query_access handler for all entity types that have none.
if (!$entity_type->hasHandlerClass('query_access')) {
// Query access does not apply to config entities.
if (!$entity_type->entityClassImplements(ConfigEntityInterface::class)) {
// Query access only works for SQL storages.
if (is_subclass_of($entity_type->getStorageClass(), SqlEntityStorageInterface::class)) {
$entity_type->setHandlerClass('query_access', 'Drupal\entity\QueryAccess\EventOnlyQueryAccessHandler');
}
}
}
}
}
/**
* Implements hook_entity_bundle_info().
*/
function entity_entity_bundle_info() {
$bundles = [];
foreach (entity_get_bundle_plugin_entity_types() as $entity_type) {
/** @var \Drupal\entity\BundlePlugin\BundlePluginHandler $bundle_handler */
$bundle_handler = \Drupal::entityTypeManager()->getHandler($entity_type->id(), 'bundle_plugin');
$bundles[$entity_type->id()] = $bundle_handler->getBundleInfo();
}
return $bundles;
}
/**
* Implements hook_entity_field_storage_info().
*/
function entity_entity_field_storage_info(EntityTypeInterface $entity_type) {
if ($entity_type->hasHandlerClass('bundle_plugin')) {
/** @var \Drupal\entity\BundlePlugin\BundlePluginHandler $bundle_handler */
$bundle_handler = \Drupal::entityTypeManager()->getHandler($entity_type->id(), 'bundle_plugin');
return $bundle_handler->getFieldStorageDefinitions();
}
}
/**
* Implements hook_entity_bundle_field_info().
*/
function entity_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle) {
if ($entity_type->hasHandlerClass('bundle_plugin')) {
/** @var \Drupal\entity\BundlePlugin\BundlePluginHandler $bundle_handler */
$bundle_handler = \Drupal::entityTypeManager()->getHandler($entity_type->id(), 'bundle_plugin');
return $bundle_handler->getFieldDefinitions($bundle);
}
}
/**
* Implements hook_modules_installed().
*/
function entity_modules_installed($modules) {
foreach (entity_get_bundle_plugin_entity_types() as $entity_type) {
\Drupal::service('entity.bundle_plugin_installer')->installBundles($entity_type, $modules);
}
}
/**
* Implements hook_module_preuninstall().
*/
function entity_module_preuninstall($module) {
foreach (entity_get_bundle_plugin_entity_types() as $entity_type) {
\Drupal::service('entity.bundle_plugin_installer')->uninstallBundles($entity_type, [$module]);
}
}
/**
* Implements hook_query_TAG_alter().
*/
function entity_query_entity_query_alter(AlterableInterface $query) {
if (!$query instanceof SelectInterface) {
return;
}
$entity_type_id = $query->getMetaData('entity_type');
if ($query->hasTag($entity_type_id . '_access')) {
$entity_type_manager = \Drupal::entityTypeManager();
$entity_type = $entity_type_manager->getDefinition($entity_type_id);
\Drupal::service('class_resolver')
->getInstanceFromDefinition(EntityQueryAlter::class)
->alter($query, $entity_type);
}
}
/**
* Implements hook_views_query_alter().
*/
function entity_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($query instanceof Sql && empty($query->options['disable_sql_rewrite'])) {
\Drupal::service('class_resolver')
->getInstanceFromDefinition(ViewsQueryAlter::class)
->alter($query, $view);
}
}
/**
* Implements hook_jsonapi_entity_filter_access().
*
* Controls access to JSON:API filtering for entity types with a query_access
* handler. Only maps condition groups consisting of "owner" and/or "published"
* field conditions.
*/
function entity_jsonapi_entity_filter_access(EntityTypeInterface $entity_type, AccountInterface $account) {
if (!$entity_type->hasHandlerClass('query_access')) {
return [];
}
/** @var \Drupal\entity\QueryAccess\QueryAccessHandlerInterface $query_access */
$query_access = \Drupal::entityTypeManager()->getHandler($entity_type->id(), 'query_access');
$conditions = $query_access->getConditions('view', $account);
if ($conditions->isAlwaysFalse()) {
return [];
}
$allowed = AccessResult::allowed()->addCacheableDependency($conditions);
$result = [];
if ($conditions->count() === 0) {
$result[JSONAPI_FILTER_AMONG_ALL] = $allowed;
}
elseif ($conditions->count() === 1 || $conditions->getConjunction() === 'OR') {
$published_key = $entity_type->getKey('published');
$owner_key = $entity_type->getKey('owner');
foreach ($conditions->getConditions() as $condition) {
if (!($condition instanceof Condition)) {
// Nested condition groups imply logic that is too complex to be mapped.
return [];
}
if ($published_key && $condition->getField() === $published_key && $condition->getOperator() === '=' && (string) $condition->getValue() === '1') {
$result[JSONAPI_FILTER_AMONG_PUBLISHED] = $allowed;
}
elseif ($owner_key && $condition->getField() === $owner_key && $condition->getOperator() === '=' && $condition->getValue() === $account->id()) {
$result[JSONAPI_FILTER_AMONG_OWN] = $allowed;
}
else {
// Unsupported condition, no access can be granted.
return [];
}
}
}
return $result;
}
@@ -0,0 +1,2 @@
permission_callbacks:
- \Drupal\entity\EntityPermissions::buildPermissions
+26
View File
@@ -0,0 +1,26 @@
services:
access_checker.entity_revision:
class: \Drupal\entity\Access\EntityRevisionRouteAccessChecker
arguments: ['@entity_type.manager', '@current_route_match']
tags:
- { name: access_check, applies_to: _entity_access_revision }
entity.entity_duplicate_subscriber:
class: Drupal\entity\EventSubscriber\EntityDuplicateSubscriber
arguments: ['@entity.bundle_entity_duplicator']
tags:
- { name: event_subscriber }
entity.bundle_entity_duplicator:
class: Drupal\entity\BundleEntityDuplicator
arguments: ['@entity_type.manager']
entity.bundle_plugin_installer:
class: Drupal\entity\BundlePlugin\BundlePluginInstaller
arguments: ['@entity_type.manager', '@entity_bundle.listener', '@field_storage_definition.listener', '@field_definition.listener']
entity.bundle_plugin.uninstall_validator:
class: Drupal\entity\BundlePlugin\BundlePluginUninstallValidator
tags:
- { name: module_install.uninstall_validator }
arguments: ['@entity_type.manager', '@string_translation']
+46
View File
@@ -0,0 +1,46 @@
<?php
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Implements hook_views_data().
*/
function entity_views_data() {
$entity_types = \Drupal::entityTypeManager()->getDefinitions();
$entity_types = array_filter($entity_types, function (EntityTypeInterface $entity_type) {
return $entity_type->entityClassImplements(ContentEntityInterface::class);
});
$data = [];
foreach ($entity_types as $entity_type) {
/** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type */
if ($entity_type->isRevisionable()) {
$entity_type_id = $entity_type->id();
$revision_table = $entity_type->getRevisionDataTable() ?: $entity_type->getRevisionTable();
if ($entity_type->hasLinkTemplate('revision')) {
$data[$revision_table]['view_revision_' . $entity_type_id] = [
'field' => [
'title' => t('Link to revision'),
'help' => t('Provide a simple link to the revision.'),
'id' => 'entity_link_revision',
'click sortable' => FALSE,
],
];
}
if ($entity_type->hasLinkTemplate('revision-revert-form')) {
$data[$revision_table]['revert_revision_' . $entity_type_id] = [
'field' => [
'title' => t('Link to revert revision'),
'help' => t('Provide a simple link to revert to the revision.'),
'id' => 'entity_link_revision_revert',
'click sortable' => FALSE,
],
];
}
}
}
return $data;
}
@@ -0,0 +1,176 @@
<?php
namespace Drupal\entity\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\Routing\Route;
/**
* Checks access to a entity revision.
*/
class EntityRevisionRouteAccessChecker implements AccessInterface {
/**
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Stores calculated access check results.
*
* @var array
*/
protected $accessCache = [];
/**
* The currently active route match object.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* Creates a new EntityRevisionRouteAccessChecker instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity manager.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The currently active route match object.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, RouteMatchInterface $route_match) {
$this->entityTypeManager = $entity_type_manager;
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public function access(Route $route, AccountInterface $account, RouteMatchInterface $route_match = NULL) {
if (empty($route_match)) {
$route_match = $this->routeMatch;
}
$operation = $route->getRequirement('_entity_access_revision');
list($entity_type_id, $operation) = explode('.', $operation, 2);
if ($operation === 'list') {
$_entity = $route_match->getParameter($entity_type_id);
return AccessResult::allowedIf($this->checkAccess($_entity, $account, $operation))->cachePerPermissions();
}
else {
$_entity_revision = $route_match->getParameter($entity_type_id . '_revision');
return AccessResult::allowedIf($_entity_revision && $this->checkAccess($_entity_revision, $account, $operation))->cachePerPermissions();
}
}
/**
* Performs access checks.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity for which to check access.
* @param \Drupal\Core\Session\AccountInterface $account
* The user for which to check access.
* @param string $operation
* The entity operation. Usually one of 'view', 'view label', 'update' or
* 'delete'.
*
* @return bool
* The access result.
*/
protected function checkAccess(ContentEntityInterface $entity, AccountInterface $account, $operation = 'view') {
$entity_type = $entity->getEntityType();
$entity_type_id = $entity->getEntityTypeId();
$entity_access = $this->entityTypeManager->getAccessControlHandler($entity_type_id);
/** @var \Drupal\Core\Entity\EntityStorageInterface $entity_storage */
$entity_storage = $this->entityTypeManager->getStorage($entity_type_id);
$map = [
'view' => "view all $entity_type_id revisions",
'list' => "view all $entity_type_id revisions",
'update' => "revert all $entity_type_id revisions",
'delete' => "delete all $entity_type_id revisions",
];
$bundle = $entity->bundle();
$type_map = [
'view' => "view $entity_type_id $bundle revisions",
'list' => "view $entity_type_id $bundle revisions",
'update' => "revert $entity_type_id $bundle revisions",
'delete' => "delete $entity_type_id $bundle revisions",
];
if (!$entity || !isset($map[$operation]) || !isset($type_map[$operation])) {
// If there was no node to check against, or the $op was not one of the
// supported ones, we return access denied.
return FALSE;
}
// Statically cache access by revision ID, language code, user account ID,
// and operation.
$langcode = $entity->language()->getId();
$cid = $entity->getRevisionId() . ':' . $langcode . ':' . $account->id() . ':' . $operation;
if (!isset($this->accessCache[$cid])) {
$admin_permission = $entity_type->getAdminPermission();
// Perform basic permission checks first.
if (!$account->hasPermission($map[$operation]) && !$account->hasPermission($type_map[$operation]) && ($admin_permission && !$account->hasPermission($admin_permission))) {
$this->accessCache[$cid] = FALSE;
return FALSE;
}
if (($admin_permission = $entity_type->getAdminPermission()) && $account->hasPermission($admin_permission)) {
$this->accessCache[$cid] = TRUE;
}
else {
// Entity access handlers are generally not aware of the "list" operation.
$operation = $operation == 'list' ? 'view' : $operation;
// First check the access to the default revision and finally, if the
// node passed in is not the default revision then access to that, too.
$this->accessCache[$cid] = $entity_access->access($entity_storage->load($entity->id()), $operation, $account) && ($entity->isDefaultRevision() || $entity_access->access($entity, $operation, $account));
}
}
return $this->accessCache[$cid];
}
/**
* Counts the number of revisions in the default language.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity.
* @param \Drupal\Core\Entity\EntityStorageInterface $entity_storage
* The entity storage.
*
* @return int
* The number of revisions in the default language.
*/
protected function countDefaultLanguageRevisions(ContentEntityInterface $entity, EntityStorageInterface $entity_storage) {
$entity_type = $entity->getEntityType();
$count = $entity_storage->getQuery()
->allRevisions()
->condition($entity_type->getKey('id'), $entity->id())
->condition($entity_type->getKey('default_langcode'), 1)
->count()
->accessCheck(TRUE)
->execute();
return $count;
}
/**
* Resets the access cache.
*
* @return $this
*/
public function resetAccessCache() {
$this->accessCache = [];
return $this;
}
}
@@ -0,0 +1,223 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\system\ActionConfigEntityInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a list builder that allows using bulk actions.
*/
class BulkFormEntityListBuilder extends EntityListBuilder implements FormInterface {
/**
* The key to use for the form element containing the entities.
*
* @var string
*/
protected $entitiesKey = 'entities';
/**
* The entities being listed.
*
* @var \Drupal\Core\Entity\EntityInterface[]
*/
protected $entities = [];
/**
* The bulk operations.
*
* @todo Change the type hint to ActionConfigEntityInterface when
* https://www.drupal.org/project/drupal/issues/3017214 is in.
*
* @var \Drupal\system\Entity\Action[]
*/
protected $actions;
/**
* The action storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $actionStorage;
/**
* The form builder.
*
* @var \Drupal\Core\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* Constructs a new BulkFormEntityListBuilder object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param \Drupal\Core\Entity\EntityStorageInterface $entity_storage
* The entity storage.
* @param \Drupal\Core\Entity\EntityStorageInterface $action_storage
* The action storage.
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $entity_storage, EntityStorageInterface $action_storage, FormBuilderInterface $form_builder) {
parent::__construct($entity_type, $entity_storage);
$this->actionStorage = $action_storage;
$this->formBuilder = $form_builder;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('entity_type.manager')->getStorage($entity_type->id()),
$container->get('entity_type.manager')->getStorage('action'),
$container->get('form_builder')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return $this->entityTypeId . '_list';
}
/**
* {@inheritdoc}
*/
public function render() {
// Filter the actions to only include those for this entity type.
$entity_type_id = $this->entityTypeId;
$this->actions = array_filter($this->actionStorage->loadMultiple(), function (ActionConfigEntityInterface $action) use ($entity_type_id) {
return $action->getType() == $entity_type_id;
});
$this->entities = $this->load();
if ($this->entities) {
return $this->formBuilder->getForm($this);
}
return parent::render();
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form[$this->entitiesKey] = [
'#type' => 'table',
'#header' => $this->buildHeader(),
'#empty' => $this->t('There are no @label yet.', ['@label' => $this->entityType->getPluralLabel()]),
'#tableselect' => TRUE,
'#attached' => [
'library' => ['core/drupal.tableselect'],
],
];
$this->entities = $this->load();
foreach ($this->entities as $entity) {
$form[$this->entitiesKey][$entity->id()] = $this->buildRow($entity);
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Apply to selected items'),
'#button_type' => 'primary',
];
// Ensure a consistent container for filters/operations in the view header.
$form['header'] = [
'#type' => 'container',
'#weight' => -100,
];
$action_options = [];
foreach ($this->actions as $id => $action) {
$action_options[$id] = $action->label();
}
$form['header']['action'] = [
'#type' => 'select',
'#title' => $this->t('Action'),
'#options' => $action_options,
];
// Duplicate the form actions into the action container in the header.
$form['header']['actions'] = $form['actions'];
// Only add the pager if a limit is specified.
if ($this->limit) {
$form['pager'] = [
'#type' => 'pager',
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$selected = array_filter($form_state->getValue($this->entitiesKey));
if (empty($selected)) {
$form_state->setErrorByName($this->entitiesKey, $this->t('No items selected.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$selected = array_filter($form_state->getValue($this->entitiesKey));
$entities = [];
$action = $this->actions[$form_state->getValue('action')];
$count = 0;
foreach ($selected as $id) {
$entity = $this->entities[$id];
// Skip execution if the user did not have access.
if (!$action->getPlugin()->access($entity)) {
$this->messenger()->addError($this->t('No access to execute %action on the @entity_type_label %entity_label.', [
'%action' => $action->label(),
'@entity_type_label' => $entity->getEntityType()->getLabel(),
'%entity_label' => $entity->label(),
]));
continue;
}
$count++;
$entities[$id] = $entity;
}
// Don't perform any action unless there are some elements affected.
// @see https://www.drupal.org/project/drupal/issues/3018148
if (!$count) {
return;
}
$action->execute($entities);
$operation_definition = $action->getPluginDefinition();
if (!empty($operation_definition['confirm_form_route_name'])) {
$options = [
'query' => $this->getDestinationArray(),
];
$form_state->setRedirect($operation_definition['confirm_form_route_name'], [], $options);
}
else {
$this->messenger()->addStatus($this->formatPlural($count, '%action was applied to @count item.', '%action was applied to @count items.', [
'%action' => $action->label(),
]));
}
}
}
@@ -0,0 +1,49 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler as CoreEntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Controls access to bundle entities.
*
* Allows the bundle entity label to be viewed if the account has
* access to view entities of that bundle.
*/
class BundleEntityAccessControlHandler extends CoreEntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected $viewLabelOperation = TRUE;
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
if ($operation === 'view label') {
$bundle = $entity->id();
$entity_type_id = $this->entityType->getBundleOf();
$permissions = [
$this->entityType->getAdminPermission() ?: "administer $entity_type_id",
// View permissions provided by EntityPermissionProvider.
"view $entity_type_id",
"view $bundle $entity_type_id",
// View permissions provided by UncacheableEntityPermissionProvider.
"view own $entity_type_id",
"view any $entity_type_id",
"view own $bundle $entity_type_id",
"view any $bundle $entity_type_id",
];
return AccessResult::allowedIfHasPermissions($account, $permissions, 'OR');
}
else {
return parent::checkAccess($entity, $operation, $account);
}
}
}
@@ -0,0 +1,128 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class BundleEntityDuplicator implements BundleEntityDuplicatorInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new BundleEntityDuplicator object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public function duplicate(ConfigEntityInterface $bundle_entity, array $values) {
$entity_type = $bundle_entity->getEntityType();
if (!$entity_type->getBundleOf()) {
throw new \InvalidArgumentException(sprintf('The "%s" entity type is not a bundle entity type.', $entity_type->id()));
}
$id_key = $entity_type->getKey('id');
if (empty($values[$id_key])) {
throw new \InvalidArgumentException(sprintf('The $values[\'%s\'] key is empty or missing.', $id_key));
}
$entity = $bundle_entity->createDuplicate();
foreach ($values as $property_name => $value) {
$entity->set($property_name, $value);
}
$entity->save();
$this->duplicateFields($bundle_entity, $entity->id());
$this->duplicateDisplays($bundle_entity, $entity->id());
return $entity;
}
/**
* {@inheritdoc}
*/
public function duplicateFields(ConfigEntityInterface $bundle_entity, $target_bundle_id) {
$entity_type = $bundle_entity->getEntityType();
$bundle_of = $entity_type->getBundleOf();
if (!$bundle_of) {
throw new \InvalidArgumentException(sprintf('The "%s" entity type is not a bundle entity type.', $entity_type->id()));
}
if (empty($target_bundle_id)) {
throw new \InvalidArgumentException('The $target_bundle_id must not be empty.');
}
$id_prefix = $bundle_of . '.' . $bundle_entity->id() . '.';
$fields = $this->loadEntities('field_config', $id_prefix);
foreach ($fields as $field) {
/** @var \Drupal\Core\Field\FieldConfigInterface $field */
$duplicate_field = $field->createDuplicate();
$duplicate_field->set('id', $bundle_of . '.' . $target_bundle_id . '.' . $field->getName());
$duplicate_field->set('bundle', $target_bundle_id);
$duplicate_field->save();
}
}
/**
* {@inheritdoc}
*/
public function duplicateDisplays(ConfigEntityInterface $bundle_entity, $target_bundle_id) {
$entity_type = $bundle_entity->getEntityType();
$bundle_of = $entity_type->getBundleOf();
if (!$bundle_of) {
throw new \InvalidArgumentException(sprintf('The "%s" entity type is not a bundle entity type.', $entity_type->id()));
}
if (empty($target_bundle_id)) {
throw new \InvalidArgumentException('The $target_bundle_id must not be empty.');
}
$id_prefix = $bundle_of . '.' . $bundle_entity->id() . '.';
$form_displays = $this->loadEntities('entity_form_display', $id_prefix);
$view_displays = $this->loadEntities('entity_view_display', $id_prefix);
foreach ($form_displays as $form_display) {
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$duplicate_form_display = $form_display->createDuplicate();
$duplicate_form_display->set('id', $bundle_of . '.' . $target_bundle_id . '.' . $form_display->getMode());
$duplicate_form_display->set('bundle', $target_bundle_id);
$duplicate_form_display->save();
}
foreach ($view_displays as $view_display) {
/** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
$duplicate_view_display = $view_display->createDuplicate();
$duplicate_view_display->set('id', $bundle_of . '.' . $target_bundle_id . '.' . $view_display->getMode());
$duplicate_view_display->set('bundle', $target_bundle_id);
$duplicate_view_display->save();
}
}
/**
* Loads config entities with the given ID prefix.
*
* @param string $entity_type_id
* The entity type ID.
* @param string $id_prefix
* The ID prefix.
*
* @return \Drupal\Core\Config\Entity\ConfigEntityInterface[]
* The loaded config entities.
*/
protected function loadEntities($entity_type_id, $id_prefix) {
$storage = $this->entityTypeManager->getStorage($entity_type_id);
$ids = $storage->getQuery()
->condition('id', $id_prefix, 'STARTS_WITH')
->accessCheck(TRUE)
->execute();
return $ids ? $storage->loadMultiple($ids) : [];
}
}
@@ -0,0 +1,56 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Duplicates bundle entities, their fields and displays.
*/
interface BundleEntityDuplicatorInterface {
/**
* Duplicates the bundle entity, its fields and displays.
*
* @param \Drupal\Core\Config\Entity\ConfigEntityInterface $bundle_entity
* The bundle entity.
* @param array $values
* An array of values to set, keyed by property name. Needs to at least
* contain a new ID.
*
* @return \Drupal\Core\Config\Entity\ConfigEntityInterface
* The new bundle entity, after it has been saved.
*
* @throws \InvalidArgumentException
* Thrown if the given entity is not a bundle entity, or if $values does
* not contain a new ID.
*/
public function duplicate(ConfigEntityInterface $bundle_entity, array $values);
/**
* Duplicates the bundle entity's fields.
*
* @param \Drupal\Core\Config\Entity\ConfigEntityInterface $bundle_entity
* The bundle entity.
* @param string $target_bundle_id
* The target bundle ID.
*
* @throws \InvalidArgumentException
* Thrown if the given entity is not a bundle entity.
*/
public function duplicateFields(ConfigEntityInterface $bundle_entity, $target_bundle_id);
/**
* Duplicates the bundle entity's view/form displays.
*
* @param \Drupal\Core\Config\Entity\ConfigEntityInterface $bundle_entity
* The bundle entity.
* @param string $target_bundle_id
* The target bundle ID.
*
* @throws \InvalidArgumentException
* Thrown if the given entity is not a bundle entity.
*/
public function duplicateDisplays(ConfigEntityInterface $bundle_entity, $target_bundle_id);
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Field\BaseFieldDefinition;
/**
* Provides a field definition class for bundle fields.
*
* Core currently doesn't provide one, the hook_entity_bundle_field_info()
* example uses BaseFieldDefinition, which is wrong. Tracked in #2346347.
*
* Note that this class implements both FieldStorageDefinitionInterface and
* FieldDefinitionInterface. This is a simplification for DX reasons,
* allowing code to return just the bundle definitions instead of having to
* return both storage definitions and bundle definitions.
*/
class BundleFieldDefinition extends BaseFieldDefinition {
/**
* {@inheritdoc}
*/
public function isBaseField() {
return FALSE;
}
}
@@ -0,0 +1,102 @@
<?php
namespace Drupal\entity\BundlePlugin;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BundlePluginHandler implements BundlePluginHandlerInterface {
/**
* The entity type.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* The bundle plugin manager.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $pluginManager;
/**
* Constructs a new BundlePluginHandler object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param \Drupal\Component\Plugin\PluginManagerInterface $plugin_manager
* The bundle plugin manager.
*/
public function __construct(EntityTypeInterface $entity_type, PluginManagerInterface $plugin_manager) {
$this->entityType = $entity_type;
$this->pluginManager = $plugin_manager;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('plugin.manager.' . $entity_type->get('bundle_plugin_type'))
);
}
/**
* {@inheritdoc}
*/
public function getBundleInfo() {
$bundles = [];
foreach ($this->pluginManager->getDefinitions() as $plugin_id => $definition) {
$bundles[$plugin_id] = [
'label' => $definition['label'],
'description' => isset($definition['description']) ? $definition['description'] : '',
'translatable' => $this->entityType->isTranslatable(),
'provider' => $definition['provider'],
];
}
return $bundles;
}
/**
* {@inheritdoc}
*/
public function getFieldStorageDefinitions() {
$definitions = [];
foreach (array_keys($this->pluginManager->getDefinitions()) as $plugin_id) {
$plugin = $this->pluginManager->createInstance($plugin_id);
assert($plugin instanceof BundlePluginInterface);
$definitions += $plugin->buildFieldDefinitions();
}
// Ensure the presence of required keys which aren't set by the plugin.
foreach ($definitions as $field_name => $definition) {
$definition->setName($field_name);
$definition->setTargetEntityTypeId($this->entityType->id());
$definitions[$field_name] = $definition;
}
return $definitions;
}
/**
* {@inheritdoc}
*/
public function getFieldDefinitions($bundle) {
$plugin = $this->pluginManager->createInstance($bundle);
assert($plugin instanceof BundlePluginInterface);
$definitions = $plugin->buildFieldDefinitions();
// Ensure the presence of required keys which aren't set by the plugin.
foreach ($definitions as $field_name => $definition) {
$definition->setName($field_name);
$definition->setTargetEntityTypeId($this->entityType->id());
$definition->setTargetBundle($bundle);
$definitions[$field_name] = $definition;
}
return $definitions;
}
}
@@ -0,0 +1,37 @@
<?php
namespace Drupal\entity\BundlePlugin;
use Drupal\Core\Entity\EntityHandlerInterface;
/**
* Handles plugin-provided bundles.
*/
interface BundlePluginHandlerInterface extends EntityHandlerInterface {
/**
* Gets the bundle info.
*
* @return array
* An array of bundle information keyed by the bundle name.
* The format expected by hook_entity_bundle_info().
*/
public function getBundleInfo();
/**
* Gets the field storage definitions.
*/
public function getFieldStorageDefinitions();
/**
* Gets the field definitions for a specific bundle.
*
* @param string $bundle
* The bundle name.
*
* @return \Drupal\entity\BundleFieldDefinition[]
* An array of bundle field definitions, keyed by field name.
*/
public function getFieldDefinitions($bundle);
}
@@ -0,0 +1,109 @@
<?php
namespace Drupal\entity\BundlePlugin;
use Drupal\Core\Entity\EntityBundleListenerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionListenerInterface;
use Drupal\Core\Field\FieldStorageDefinitionListenerInterface;
class BundlePluginInstaller implements BundlePluginInstallerInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity bundle listener.
*
* @var \Drupal\Core\Entity\EntityBundleListenerInterface
*/
protected $entityBundleListener;
/**
* The field storage definition listener.
*
* @var \Drupal\Core\Field\FieldStorageDefinitionListenerInterface
*/
protected $fieldStorageDefinitionListener;
/**
* The field definition listener.
*
* @var \Drupal\Core\Field\FieldDefinitionListenerInterface
*/
protected $fieldDefinitionListener;
/**
* Constructs a new BundlePluginInstaller object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityBundleListenerInterface $entity_bundle_listener
* The entity bundle listener.
* @param \Drupal\Core\Field\FieldStorageDefinitionListenerInterface $field_storage_definition_listener
* The field storage definition listener.
* @param \Drupal\Core\Field\FieldDefinitionListenerInterface $field_definition_listener
* The field definition listener.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityBundleListenerInterface $entity_bundle_listener, FieldStorageDefinitionListenerInterface $field_storage_definition_listener, FieldDefinitionListenerInterface $field_definition_listener) {
$this->entityTypeManager = $entity_type_manager;
$this->entityBundleListener = $entity_bundle_listener;
$this->fieldStorageDefinitionListener = $field_storage_definition_listener;
$this->fieldDefinitionListener = $field_definition_listener;
}
/**
* {@inheritdoc}
*/
public function installBundles(EntityTypeInterface $entity_type, array $modules) {
$bundle_handler = $this->entityTypeManager->getHandler($entity_type->id(), 'bundle_plugin');
$bundles = array_filter($bundle_handler->getBundleInfo(), function ($bundle_info) use ($modules) {
return in_array($bundle_info['provider'], $modules, TRUE);
});
foreach (array_keys($bundles) as $bundle) {
$this->entityBundleListener->onBundleCreate($bundle, $entity_type->id());
foreach ($bundle_handler->getFieldDefinitions($bundle) as $definition) {
$this->fieldStorageDefinitionListener->onFieldStorageDefinitionCreate($definition);
$this->fieldDefinitionListener->onFieldDefinitionCreate($definition);
}
}
}
/**
* {@inheritdoc}
*/
public function uninstallBundles(EntityTypeInterface $entity_type, array $modules) {
$bundle_handler = $this->entityTypeManager->getHandler($entity_type->id(), 'bundle_plugin');
$bundles = array_filter($bundle_handler->getBundleInfo(), function ($bundle_info) use ($modules) {
return in_array($bundle_info['provider'], $modules, TRUE);
});
/**
* We need to uninstall the field storage definitions in a separate loop.
*
* This way we can allow a module to re-use the same field within multiple
* bundles, allowing e.g to subclass a bundle plugin.
*
* @var \Drupal\entity\BundleFieldDefinition[] $field_storage_definitions
*/
$field_storage_definitions = [];
foreach (array_keys($bundles) as $bundle) {
$this->entityBundleListener->onBundleDelete($bundle, $entity_type->id());
foreach ($bundle_handler->getFieldDefinitions($bundle) as $definition) {
$this->fieldDefinitionListener->onFieldDefinitionDelete($definition);
$field_storage_definitions[$definition->getName()] = $definition;
}
}
foreach ($field_storage_definitions as $definition) {
$this->fieldStorageDefinitionListener->onFieldStorageDefinitionDelete($definition);
}
}
}
@@ -0,0 +1,34 @@
<?php
namespace Drupal\entity\BundlePlugin;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Installs and uninstalls bundle plugins.
*
* Ensures that the fields provided by the bundle plugins are created/deleted.
*/
interface BundlePluginInstallerInterface {
/**
* Installs the bundle plugins provided by the specified modules.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param array $modules
* The modules.
*/
public function installBundles(EntityTypeInterface $entity_type, array $modules);
/**
* Uninstalls the bundle plugins provided by the specified modules.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param array $modules
* The modules.
*/
public function uninstallBundles(EntityTypeInterface $entity_type, array $modules);
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\entity\BundlePlugin;
use Drupal\Component\Plugin\PluginInspectionInterface;
/**
* Interface for plugins which act as entity bundles.
*/
interface BundlePluginInterface extends PluginInspectionInterface {
/**
* Builds the field definitions for entities of this bundle.
*
* Important:
* Field names must be unique across all bundles.
* It is recommended to prefix them with the bundle name (plugin ID).
*
* @return \Drupal\entity\BundleFieldDefinition[]
* An array of bundle field definitions, keyed by field name.
*/
public function buildFieldDefinitions();
}
@@ -0,0 +1,77 @@
<?php
namespace Drupal\entity\BundlePlugin;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleUninstallValidatorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
/**
* Prevents uninstalling modules with bundle plugins in case of found data.
*/
class BundlePluginUninstallValidator implements ModuleUninstallValidatorInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs the object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, TranslationInterface $string_translation) {
$this->entityTypeManager = $entity_type_manager;
$this->stringTranslation = $string_translation;
}
/**
* {@inheritdoc}
*/
public function validate($module) {
$reasons = [];
foreach (entity_get_bundle_plugin_entity_types() as $entity_type) {
/** @var \Drupal\entity\BundlePlugin\BundlePluginHandler $bundle_handler */
$bundle_handler = $this->entityTypeManager->getHandler($entity_type->id(), 'bundle_plugin');
$bundles = $bundle_handler->getBundleInfo();
// We find all bundles which have to be removed due to the uninstallation.
$bundles_filtered_by_module = array_filter($bundles, function ($bundle_info) use ($module) {
return $module === $bundle_info['provider'];
});
if (!empty($bundles_filtered_by_module)) {
$bundle_keys_with_content = array_filter(array_keys($bundles_filtered_by_module), function ($bundle) use ($entity_type) {
$result = $this->entityTypeManager->getStorage($entity_type->id())->getQuery()
->condition($entity_type->getKey('bundle'), $bundle)
->range(0, 1)
->accessCheck(TRUE)
->execute();
return !empty($result);
});
$bundles_with_content = array_intersect_key($bundles_filtered_by_module, array_flip($bundle_keys_with_content));
foreach ($bundles_with_content as $bundle) {
$reasons[] = $this->t('There is data for the bundle @bundle on the entity type @entity_type. Please remove all content before uninstalling the module.', [
'@bundle' => $bundle['label'],
'@entity_type' => $entity_type->getLabel(),
]);
}
}
}
return $reasons;
}
}
@@ -0,0 +1,110 @@
<?php
namespace Drupal\entity\Controller;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntityDuplicateController implements ContainerInjectionInterface {
use StringTranslationTrait;
/**
* The entity repository.
*
* @var \Drupal\Core\Entity\EntityRepositoryInterface
*/
protected $entityRepository;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The form builder.
*
* @var \Drupal\Core\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* Constructs a new EntityDuplicateController object.
*
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
*/
public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeManagerInterface $entity_type_manager, FormBuilderInterface $form_builder, TranslationInterface $string_translation) {
$this->entityRepository = $entity_repository;
$this->entityTypeManager = $entity_type_manager;
$this->formBuilder = $form_builder;
$this->stringTranslation = $string_translation;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.repository'),
$container->get('entity_type.manager'),
$container->get('form_builder'),
$container->get('string_translation')
);
}
/**
* Builds the duplicate form.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*
* @return array
* The rendered form.
*/
public function form(RouteMatchInterface $route_match) {
$entity_type_id = $route_match->getRouteObject()->getDefault('entity_type_id');
$source_entity = $route_match->getParameter($entity_type_id);
$entity = $source_entity->createDuplicate();
/** @var \Drupal\entity\Form\EntityDuplicateFormInterface $form_object */
$form_object = $this->entityTypeManager->getFormObject($entity_type_id, 'duplicate');
$form_object->setEntity($entity);
$form_object->setSourceEntity($source_entity);
$form_state = new FormState();
return $this->formBuilder->buildForm($form_object, $form_state);
}
/**
* Provides the duplicate form title.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*
* @return string
* The duplicate form title.
*/
public function title(RouteMatchInterface $route_match) {
$entity_type_id = $route_match->getRouteObject()->getDefault('entity_type_id');
$source_entity = $route_match->getParameter($entity_type_id);
$source_entity = $this->entityRepository->getTranslationFromContext($source_entity);
return $this->t('Duplicate %label', ['%label' => $source_entity->label()]);
}
}
@@ -0,0 +1,194 @@
<?php
namespace Drupal\entity\Controller;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Entity\EntityInterface;
/**
* Defines a trait for common revision UI functionality.
*/
trait RevisionControllerTrait {
/**
* Returns the entity type manager.
*
* @return \Drupal\Core\Entity\EntityTypeManagerInterface
*/
abstract protected function entityTypeManager();
/**
* Returns the language manager.
*
* @return \Drupal\Core\Language\LanguageManagerInterface
*/
abstract public function languageManager();
/**
* Determines if the user has permission to revert revisions.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to check revert access for.
*
* @return bool
* TRUE if the user has revert access.
*/
abstract protected function hasRevertRevisionAccess(EntityInterface $entity);
/**
* Determines if the user has permission to delete revisions.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to check delete revision access for.
*
* @return bool
* TRUE if the user has delete revision access.
*/
abstract protected function hasDeleteRevisionAccess(EntityInterface $entity);
/**
* Builds a link to revert an entity revision.
*
* @param \Drupal\Core\Entity\EntityInterface $entity_revision
* The entity to build a revert revision link for.
*
* @return array
* A link render array.
*/
abstract protected function buildRevertRevisionLink(EntityInterface $entity_revision);
/**
* Builds a link to delete an entity revision.
*
* @param \Drupal\Core\Entity\EntityInterface $entity_revision
* The entity to build a delete revision link for.
*
* @return array
* A link render array.
*/
abstract protected function buildDeleteRevisionLink(EntityInterface $entity_revision);
/**
* Returns a string providing details of the revision.
*
* E.g. Node describes its revisions using {date} by {username}. For the
* non-current revision, it also provides a link to view that revision.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $revision
* The entity revision.
* @param bool $is_current
* TRUE if the revision is the current revision.
*
* @return string
* Returns a string to provide the details of the revision.
*/
abstract protected function getRevisionDescription(ContentEntityInterface $revision, $is_current = FALSE);
/**
* Loads all revision IDs of an entity sorted by revision ID descending.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity.
*
* @return mixed[]
*/
protected function revisionIds(ContentEntityInterface $entity) {
$entity_type = $entity->getEntityType();
$result = $this->entityTypeManager()->getStorage($entity_type->id())->getQuery()
->allRevisions()
->condition($entity_type->getKey('id'), $entity->id())
->sort($entity_type->getKey('revision'), 'DESC')
->accessCheck(TRUE)
->execute();
return array_keys($result);
}
/**
* Generates an overview table of older revisions of an entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* An entity object.
*
* @return array
* A render array.
*/
protected function revisionOverview(ContentEntityInterface $entity) {
$langcode = $this->languageManager()
->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
->getId();
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $entity_storage */
$entity_storage = $this->entityTypeManager()->getStorage($entity->getEntityTypeId());
$revision_ids = $this->revisionIds($entity);
$entity_revisions = $entity_storage->loadMultipleRevisions($revision_ids);
$translatable = $entity->getEntityType()->isTranslatable();
$header = [$this->t('Revision'), $this->t('Operations')];
$rows = [];
foreach ($entity_revisions as $revision) {
$row = [];
/** @var \Drupal\Core\Entity\ContentEntityInterface $revision */
if (!$translatable || ($revision->hasTranslation($langcode) && $revision->getTranslation($langcode)->isRevisionTranslationAffected())) {
$row[] = $this->getRevisionDescription($revision, $revision->isDefaultRevision());
if ($revision->isDefaultRevision()) {
$row[] = [
'data' => [
'#prefix' => '<em>',
'#markup' => $this->t('Current revision'),
'#suffix' => '</em>',
],
];
foreach ($row as &$current) {
$current['class'] = ['revision-current'];
}
}
else {
$links = $this->getOperationLinks($revision);
$row[] = [
'data' => [
'#type' => 'operations',
'#links' => $links,
],
];
}
}
$rows[] = $row;
}
$build[$entity->getEntityTypeId() . '_revisions_table'] = [
'#theme' => 'table',
'#rows' => $rows,
'#header' => $header,
];
// We have no clue about caching yet.
$build['#cache']['max-age'] = 0;
return $build;
}
/**
* Get the links of the operations for an entity revision.
*
* @param \Drupal\Core\Entity\EntityInterface $entity_revision
* The entity to build the revision links for.
*
* @return array
* The operation links.
*/
protected function getOperationLinks(EntityInterface $entity_revision) {
$links = [];
if ($this->hasRevertRevisionAccess($entity_revision)) {
$links['revert'] = $this->buildRevertRevisionLink($entity_revision);
}
if ($this->hasDeleteRevisionAccess($entity_revision)) {
$links['delete'] = $this->buildDeleteRevisionLink($entity_revision);
}
return array_filter($links);
}
}
@@ -0,0 +1,160 @@
<?php
namespace Drupal\entity\Controller;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a controller which shows the revision history.
*
* This controller leverages the revision controller trait, which is agnostic to
* any entity type, by using \Drupal\Core\Entity\RevisionLogInterface.
*/
class RevisionOverviewController extends ControllerBase {
use RevisionControllerTrait;
/**
* The date formatter.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Creates a new RevisionOverviewController instance.
*
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter.
*/
public function __construct(DateFormatterInterface $date_formatter, RendererInterface $renderer) {
$this->dateFormatter = $date_formatter;
$this->renderer = $renderer;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('date.formatter'), $container->get('renderer'));
}
/**
* {@inheritdoc}
*/
protected function hasDeleteRevisionAccess(EntityInterface $entity) {
return $this->currentUser()->hasPermission("delete all {$entity->getEntityTypeId()} revisions");
}
/**
* {@inheritdoc}
*/
protected function buildRevertRevisionLink(EntityInterface $entity_revision) {
if ($entity_revision->hasLinkTemplate('revision-revert-form')) {
return [
'title' => $this->t('Revert'),
'url' => $entity_revision->toUrl('revision-revert-form'),
];
}
}
/**
* {@inheritdoc}
*/
protected function buildDeleteRevisionLink(EntityInterface $entity_revision) {
if ($entity_revision->hasLinkTemplate('revision-delete-form')) {
return [
'title' => $this->t('Delete'),
'url' => $entity_revision->toUrl('revision-delete-form'),
];
}
}
/**
* Generates an overview table of older revisions of an entity.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*
* @return array
* A render array.
*/
public function revisionOverviewController(RouteMatchInterface $route_match) {
return $this->revisionOverview($route_match->getParameter($route_match->getRouteObject()->getOption('entity_type_id')));
}
/**
* {@inheritdoc}
*/
protected function getRevisionDescription(ContentEntityInterface $revision, $is_default = FALSE) {
/** @var \Drupal\Core\Entity\ContentEntityInterface|\Drupal\user\EntityOwnerInterface|\Drupal\Core\Entity\RevisionLogInterface $revision */
if ($revision instanceof RevisionLogInterface) {
// Use revision link to link to revisions that are not active.
$date = $this->dateFormatter->format($revision->getRevisionCreationTime(), 'short');
$link = $revision->toLink($date, 'revision');
// @todo: Simplify this when https://www.drupal.org/node/2334319 lands.
$username = [
'#theme' => 'username',
'#account' => $revision->getRevisionUser(),
];
$username = $this->renderer->render($username);
}
else {
$link = $revision->toLink($revision->label(), 'revision');
$username = '';
}
$markup = '';
if ($revision instanceof RevisionLogInterface) {
$markup = $revision->getRevisionLogMessage();
}
if ($username) {
$template = '{% trans %}{{ date }} by {{ username }}{% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}';
}
else {
$template = '{% trans %} {{ date }} {% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}';
}
$column = [
'data' => [
'#type' => 'inline_template',
'#template' => $template,
'#context' => [
'date' => $link->toString(),
'username' => $username,
'message' => ['#markup' => $markup, '#allowed_tags' => Xss::getHtmlTagList()],
],
],
];
return $column;
}
/**
* {@inheritdoc}
*/
protected function hasRevertRevisionAccess(EntityInterface $entity) {
return AccessResult::allowedIfHasPermission($this->currentUser(), "revert all {$entity->getEntityTypeId()} revisions")->orIf(
AccessResult::allowedIfHasPermission($this->currentUser(), "revert {$entity->bundle()} {$entity->getEntityTypeId()} revisions")
);
}
}
@@ -0,0 +1,14 @@
<?php
namespace Drupal\entity\Entity;
use Drupal\Core\Entity\RevisionableEntityBundleInterface as CoreRevisionableEntityBundleInterface;
@trigger_error('\Drupal\entity\Entity\RevisionableEntityBundleInterface has been deprecated in favor of \Drupal\Core\Entity\RevisionableEntityBundleInterface. Use that instead.');
/**
* @deprecated in favor of
* \Drupal\Core\Entity\RevisionableEntityBundleInterface. Use that instead.
*/
interface RevisionableEntityBundleInterface extends CoreRevisionableEntityBundleInterface {
}
@@ -0,0 +1,60 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Controls access based on the generic entity permissions.
*
* @see \Drupal\entity\UncacheableEntityPermissionProvider
*/
class EntityAccessControlHandler extends EntityAccessControlHandlerBase {
/**
* {@inheritdoc}
*/
public function __construct(EntityTypeInterface $entity_type) {
parent::__construct($entity_type);
if (!$entity_type->hasHandlerClass('permission_provider') || !is_a($entity_type->getHandlerClass('permission_provider'), EntityPermissionProvider::class, TRUE)) {
throw new \Exception('\Drupal\entity\EntityAccessControlHandler requires the \Drupal\entity\EntityPermissionProvider permission provider.');
}
}
/**
* {@inheritdoc}
*/
protected function checkEntityOwnerPermissions(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\user\EntityOwnerInterface $entity */
if ($operation === 'view') {
if ($entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
if ($account->id() != $entity->getOwnerId()) {
// There's no permission for viewing other user's unpublished entity.
return AccessResult::neutral()->cachePerUser();
}
$permissions = [
"view own unpublished {$entity->getEntityTypeId()}",
];
$result = AccessResult::allowedIfHasPermissions($account, $permissions)->cachePerUser();
}
else {
$result = AccessResult::allowedIfHasPermissions($account, [
"view {$entity->getEntityTypeId()}",
"view {$entity->bundle()} {$entity->getEntityTypeId()}",
], 'OR');
}
}
else {
$result = parent::checkEntityOwnerPermissions($entity, $operation, $account);
}
return $result;
}
}
@@ -0,0 +1,121 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler as CoreEntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\EntityOwnerInterface;
/**
* @internal
*/
class EntityAccessControlHandlerBase extends CoreEntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
$account = $this->prepareUser($account);
/** @var \Drupal\Core\Access\AccessResult $result */
$result = parent::checkAccess($entity, $operation, $account);
if ($result->isNeutral()) {
if ($entity instanceof EntityOwnerInterface) {
$result = $this->checkEntityOwnerPermissions($entity, $operation, $account);
}
else {
$result = $this->checkEntityPermissions($entity, $operation, $account);
}
}
// Ensure that access is evaluated again when the entity changes.
return $result->addCacheableDependency($entity);
}
/**
* Checks the entity operation and bundle permissions.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity for which to check access.
* @param string $operation
* The entity operation. Usually one of 'view', 'view label', 'update',
* 'duplicate' or 'delete'.
* @param \Drupal\Core\Session\AccountInterface $account
* The user for which to check access.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
protected function checkEntityPermissions(EntityInterface $entity, $operation, AccountInterface $account) {
$permissions = [
"$operation {$entity->getEntityTypeId()}",
"$operation {$entity->bundle()} {$entity->getEntityTypeId()}",
];
return AccessResult::allowedIfHasPermissions($account, $permissions, 'OR');
}
/**
* Checks the entity operation and bundle permissions, with owners.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity for which to check access.
* @param string $operation
* The entity operation. Usually one of 'view', 'view label', 'update',
* 'duplicate' or 'delete'.
* @param \Drupal\Core\Session\AccountInterface $account
* The user for which to check access.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
protected function checkEntityOwnerPermissions(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\user\EntityOwnerInterface $entity */
// The "any" permission grants access regardless of the entity owner.
$any_result = AccessResult::allowedIfHasPermissions($account, [
"$operation any {$entity->getEntityTypeId()}",
"$operation any {$entity->bundle()} {$entity->getEntityTypeId()}",
], 'OR');
if ($any_result->isAllowed()) {
return $any_result;
}
if ($account->id() == $entity->getOwnerId()) {
$own_result = AccessResult::allowedIfHasPermissions($account, [
"$operation own {$entity->getEntityTypeId()}",
"$operation own {$entity->bundle()} {$entity->getEntityTypeId()}",
], 'OR');
}
else {
$own_result = AccessResult::neutral()->cachePerPermissions();
}
// The "own" permission is based on the current user's ID, so the result
// must be cached per user.
return $own_result->cachePerUser();
}
/**
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
$result = parent::checkCreateAccess($account, $context, $entity_bundle);
if ($result->isNeutral()) {
$permissions = [
$this->entityType->getAdminPermission() ?: 'administer ' . $this->entityTypeId,
'create ' . $this->entityTypeId,
];
if ($entity_bundle) {
$permissions[] = 'create ' . $entity_bundle . ' ' . $this->entityTypeId;
}
$result = AccessResult::allowedIfHasPermissions($account, $permissions, 'OR');
}
return $result;
}
}
@@ -0,0 +1,98 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Provides generic entity permissions.
*
* Intended for content entity types, since config entity types usually rely
* on a single "administer" permission.
*
* Provided permissions:
* - The declared "admin_permission" of the entity type (or
* "administer $entity_type" if the entity type does not declare an
* administrative permission)
* - access $entity_type overview
* - view own unpublished $entity_type
* - view ($bundle) $entity_type
* - update (own|any) ($bundle) $entity_type
* - duplicate (own|any) ($bundle) $entity_type
* - delete (own|any) ($bundle) $entity_type
* - create $bundle $entity_type
*
* Does not provide "view own ($bundle) $entity_type" permissions, because
* they require caching pages per user. Please use
* \Drupal\entity\UncacheableEntityPermissionProvider if those permissions
* are necessary.
*
* Example annotation:
* @code
* handlers = {
* "access" = "Drupal\entity\EntityAccessControlHandler",
* "permission_provider" = "Drupal\entity\EntityPermissionProvider",
* }
* @endcode
*
* @see \Drupal\entity\EntityAccessControlHandler
* @see \Drupal\entity\EntityPermissions
*/
class EntityPermissionProvider extends EntityPermissionProviderBase {
/**
* Builds permissions for the entity_type granularity.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array
* The permissions.
*/
protected function buildEntityTypePermissions(EntityTypeInterface $entity_type) {
$permissions = parent::buildEntityTypePermissions($entity_type);
$entity_type_id = $entity_type->id();
$plural_label = $entity_type->getPluralLabel();
$permissions["view {$entity_type_id}"] = [
'title' => $this->t('View @type', [
'@type' => $plural_label,
]),
];
return $permissions;
}
/**
* Builds permissions for the bundle granularity.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array
* The permissions.
*/
protected function buildBundlePermissions(EntityTypeInterface $entity_type) {
$permissions = parent::buildBundlePermissions($entity_type);
$entity_type_id = $entity_type->id();
$bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
$plural_label = $entity_type->getPluralLabel();
$permissions["view {$entity_type_id}"] = [
'title' => $this->t('View @type', [
'@type' => $plural_label,
]),
];
foreach ($bundles as $bundle_name => $bundle_info) {
$permissions["view {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: View @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
}
return $permissions;
}
}
@@ -0,0 +1,278 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\user\EntityOwnerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* @internal
*/
class EntityPermissionProviderBase implements EntityPermissionProviderInterface, EntityHandlerInterface {
use StringTranslationTrait;
/**
* The entity type bundle info.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* Constructs a new EntityPermissionProvider object.
*
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
*/
public function __construct(EntityTypeBundleInfoInterface $entity_type_bundle_info) {
$this->entityTypeBundleInfo = $entity_type_bundle_info;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$container->get('entity_type.bundle.info')
);
}
/**
* {@inheritdoc}
*/
public function buildPermissions(EntityTypeInterface $entity_type) {
$entity_type_id = $entity_type->id();
$has_owner = $entity_type->entityClassImplements(EntityOwnerInterface::class);
$plural_label = $entity_type->getPluralLabel();
$permissions = [];
$admin_permission = $entity_type->getAdminPermission() ?: "administer {$entity_type_id}";
$permissions[$admin_permission] = [
'title' => $this->t('Administer @type', ['@type' => $plural_label]),
'restrict access' => TRUE,
];
if ($entity_type->hasLinkTemplate('collection')) {
$permissions["access {$entity_type_id} overview"] = [
'title' => $this->t('Access the @type overview page', ['@type' => $plural_label]),
];
}
if ($has_owner && $entity_type->entityClassImplements(EntityPublishedInterface::class)) {
$permissions["view own unpublished {$entity_type_id}"] = [
'title' => $this->t('View own unpublished @type', [
'@type' => $plural_label,
]),
];
}
// Generate the other permissions based on granularity.
if ($entity_type->getPermissionGranularity() === 'entity_type') {
$permissions += $this->buildEntityTypePermissions($entity_type);
}
else {
$permissions += $this->buildBundlePermissions($entity_type);
}
return $this->processPermissions($permissions, $entity_type);
}
/**
* Adds the provider and converts the titles to strings to allow sorting.
*
* @param array $permissions
* The array of permissions.
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array
* An array of processed permissions.
*/
protected function processPermissions(array $permissions, EntityTypeInterface $entity_type) {
foreach ($permissions as $name => $permission) {
// Permissions are grouped by provider on admin/people/permissions.
$permissions[$name]['provider'] = $entity_type->getProvider();
// TranslatableMarkup objects don't sort properly.
$permissions[$name]['title'] = (string) $permission['title'];
}
return $permissions;
}
/**
* Builds permissions for the entity_type granularity.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array
* The permissions.
*/
protected function buildEntityTypePermissions(EntityTypeInterface $entity_type) {
$entity_type_id = $entity_type->id();
$has_owner = $entity_type->entityClassImplements(EntityOwnerInterface::class);
$has_duplicate_form = $entity_type->hasLinkTemplate('duplicate-form');
$singular_label = $entity_type->getSingularLabel();
$plural_label = $entity_type->getPluralLabel();
$permissions = [];
$permissions["create {$entity_type_id}"] = [
'title' => $this->t('Create @type', [
'@type' => $plural_label,
]),
];
if ($has_owner) {
$permissions["update any {$entity_type_id}"] = [
'title' => $this->t('Update any @type', [
'@type' => $singular_label,
]),
];
$permissions["update own {$entity_type_id}"] = [
'title' => $this->t('Update own @type', [
'@type' => $plural_label,
]),
];
if ($has_duplicate_form) {
$permissions["duplicate any {$entity_type_id}"] = [
'title' => $this->t('Duplicate any @type', [
'@type' => $singular_label,
]),
];
$permissions["duplicate own {$entity_type_id}"] = [
'title' => $this->t('Duplicate own @type', [
'@type' => $plural_label,
]),
];
}
$permissions["delete any {$entity_type_id}"] = [
'title' => $this->t('Delete any @type', [
'@type' => $singular_label,
]),
];
$permissions["delete own {$entity_type_id}"] = [
'title' => $this->t('Delete own @type', [
'@type' => $plural_label,
]),
];
}
else {
$permissions["update {$entity_type_id}"] = [
'title' => $this->t('Update @type', [
'@type' => $plural_label,
]),
];
if ($has_duplicate_form) {
$permissions["duplicate {$entity_type_id}"] = [
'title' => $this->t('Duplicate @type', [
'@type' => $plural_label,
]),
];
}
$permissions["delete {$entity_type_id}"] = [
'title' => $this->t('Delete @type', [
'@type' => $plural_label,
]),
];
}
return $permissions;
}
/**
* Builds permissions for the bundle granularity.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array
* The permissions.
*/
protected function buildBundlePermissions(EntityTypeInterface $entity_type) {
$entity_type_id = $entity_type->id();
$bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
$has_owner = $entity_type->entityClassImplements(EntityOwnerInterface::class);
$has_duplicate_form = $entity_type->hasLinkTemplate('duplicate-form');
$singular_label = $entity_type->getSingularLabel();
$plural_label = $entity_type->getPluralLabel();
$permissions = [];
foreach ($bundles as $bundle_name => $bundle_info) {
$permissions["create {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Create @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
if ($has_owner) {
$permissions["update any {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Update any @type', [
'@bundle' => $bundle_info['label'],
'@type' => $singular_label,
]),
];
$permissions["update own {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Update own @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
if ($has_duplicate_form) {
$permissions["duplicate any {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Duplicate any @type', [
'@bundle' => $bundle_info['label'],
'@type' => $singular_label,
]),
];
$permissions["duplicate own {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Duplicate own @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
}
$permissions["delete any {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Delete any @type', [
'@bundle' => $bundle_info['label'],
'@type' => $singular_label,
]),
];
$permissions["delete own {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Delete own @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
}
else {
$permissions["update {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Update @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
if ($has_duplicate_form) {
$permissions["duplicate {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Duplicate @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
}
$permissions["delete {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: Delete @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
}
}
return $permissions;
}
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Allows entity types to provide permissions.
*/
interface EntityPermissionProviderInterface {
/**
* Builds permissions for the given entity type.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array
* The permissions.
*/
public function buildPermissions(EntityTypeInterface $entity_type);
}
@@ -0,0 +1,63 @@
<?php
namespace Drupal\entity;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Generates entity permissions via their permission providers.
*
* @see \Drupal\entity\EntityPermissionProvider
* @see \Drupal\entity\UncacheableEntityPermissionProvider
*/
class EntityPermissions implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new EntityPermissions object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager')
);
}
/**
* Builds a list of permissions for the participating entity types.
*
* @return array
* The permissions.
*/
public function buildPermissions() {
$permissions = [];
/** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
foreach ($this->entityTypeManager->getDefinitions() as $entity_type) {
if ($entity_type->hasHandlerClass('permission_provider')) {
$permission_provider_class = $entity_type->getHandlerClass('permission_provider');
$permission_provider = $this->entityTypeManager->createHandlerInstance($permission_provider_class, $entity_type);
$permissions += $permission_provider->buildPermissions($entity_type);
}
}
return $permissions;
}
}
@@ -0,0 +1,17 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Entity\EntityViewBuilder as CoreEntityViewBuilder;
@trigger_error('\Drupal\entity\EntityViewBuilder has been deprecated in favor of \Drupal\Core\Entity\EntityViewBuilder. Use that instead.');
/**
* Provides a entity view builder with contextual links support.
*
* @deprecated in favor of \Drupal\Core\Entity\EntityViewBuilder. Use that
* instead.
*/
class EntityViewBuilder extends CoreEntityViewBuilder {
}
+449
View File
@@ -0,0 +1,449 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Entity\ContentEntityType;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\Sql\TableMappingInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\views\EntityViewsData as CoreEntityViewsData;
/**
* Provides improvements to core's generic views integration for entities.
*
* Contains special handling for the following base field types:
* - datetime
* - list_float, list_integer, list_string
* Workaround for core issue #2337515.
*
* Provides views data for bundle plugin fields,
* as a workaround for core issue #2898635.
*
* Provides the missing delta field for multi-value fields,
* as a workaround for core issue #3097568.
*
* Fixes handling of fields with multiple properties,
* as a workaround for core issue #3097636.
*
* Provides reverse relationships for base entity_reference fields,
* as a workaround for core issue #2706431.
*/
class EntityViewsData extends CoreEntityViewsData {
/**
* The table mapping.
*
* @var \Drupal\Core\Entity\Sql\DefaultTableMapping
*/
protected $tableMapping;
/**
* {@inheritdoc}
*/
public function getViewsData() {
$data = parent::getViewsData();
$this->tableMapping = $this->storage->getTableMapping();
$entity_type_id = $this->entityType->id();
// Workaround for core issue #3004300.
if ($this->entityType->isRevisionable()) {
$revision_table = $this->tableMapping->getRevisionTable();
$data[$revision_table]['table']['entity revision'] = TRUE;
}
// Add missing reverse relationships for base fields. Workaround for core issue #2706431.
// Only add reverse relationships if the field has been created in the DB.
$base_fields = $this->getEntityFieldManager()->getBaseFieldDefinitions($entity_type_id);
$entity_reference_fields = array_filter($base_fields, function (BaseFieldDefinition $field) {
return !$field->hasCustomStorage() && $field->getType() == 'entity_reference' && !empty($this->tableMapping->getAllFieldTableNames($field->getName()));
});
// Add views integration for bundle plugin fields.
// Workaround for core issue #2898635.
if ($this->entityType->hasHandlerClass('bundle_plugin')) {
$bundles = $this->getEntityTypeBundleInfo()->getBundleInfo($entity_type_id);
foreach (array_keys($bundles) as $bundle) {
$field_definitions = $this->getEntityFieldManager()->getFieldDefinitions($entity_type_id, $bundle);
foreach ($field_definitions as $field_name => $field_definition) {
if ($field_definition instanceof BundleFieldDefinition) {
$this->addBundleFieldData($data, $field_definition);
// Add reverse relationships for bundle plugin entity_reference fields.
// Only add reverse relationships if the field has been created in the DB.
if (!$field_definition->hasCustomStorage() && $field_definition->getType() == 'entity_reference' && !empty($this->tableMapping->getAllFieldTableNames($field_name))) {
$entity_reference_fields[$field_name] = $field_definition;
}
}
}
}
}
// Add reverse relationships for both base and bundle plugin entity_reference fields.
$this->addReverseRelationships($data, $entity_reference_fields);
return $data;
}
/**
* Adds views data for the given bundle field.
*
* Based on views_field_default_views_data(), which is only invoked
* for configurable fields.
*
* Assumes that the bundle field is not shared between bundles, since
* the bundle plugin API doesn't support that.
*
* @param array $data
* The views data.
* @param \Drupal\entity\BundleFieldDefinition $bundle_field
* The bundle field.
*/
protected function addBundleFieldData(array &$data, BundleFieldDefinition $bundle_field) {
$field_name = $bundle_field->getName();
$entity_type_id = $this->entityType->id();
$base_table = $this->getViewsTableForEntityType($this->entityType);
$revision_table = '';
if ($this->entityType->isRevisionable()) {
$revision_table = $this->tableMapping->getRevisionDataTable();
if (!$revision_table) {
$revision_table = $this->tableMapping->getRevisionTable();
}
}
$field_tables = [];
$field_tables[EntityStorageInterface::FIELD_LOAD_CURRENT] = [
'table' => $this->tableMapping->getDedicatedDataTableName($bundle_field),
'alias' => "{$entity_type_id}__{$field_name}",
];
if ($this->entityType->isRevisionable()) {
$field_tables[EntityStorageInterface::FIELD_LOAD_REVISION] = [
'table' => $this->tableMapping->getDedicatedRevisionTableName($bundle_field),
'alias' => "{$entity_type_id}_revision__{$field_name}",
];
}
$table_alias = $field_tables[EntityStorageInterface::FIELD_LOAD_CURRENT]['alias'];
$data[$table_alias]['table']['group'] = $this->entityType->getLabel();
$data[$table_alias]['table']['join'][$base_table] = [
'table' => $this->tableMapping->getDedicatedDataTableName($bundle_field),
'left_field' => $this->entityType->getKey('id'),
'field' => 'entity_id',
'extra' => [
['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
],
];
if ($bundle_field->isTranslatable()) {
$data[$table_alias]['table']['join'][$base_table]['extra'][] = [
'left_field' => 'langcode',
'field' => 'langcode',
];
}
if ($this->entityType->isRevisionable()) {
$table_alias = $field_tables[EntityStorageInterface::FIELD_LOAD_REVISION]['alias'];
$data[$table_alias]['table']['group'] = $this->t('@group (historical data)', [
'@group' => $this->entityType->getLabel(),
]);
$data[$table_alias]['table']['join'][$revision_table] = [
'table' => $this->tableMapping->getDedicatedRevisionTableName($bundle_field),
'left_field' => $this->entityType->getKey('revision'),
'field' => 'revision_id',
'extra' => [
['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
],
];
if ($bundle_field->isTranslatable()) {
$data[$table_alias]['table']['join'][$revision_table]['extra'][] = [
'left_field' => 'langcode',
'field' => 'langcode',
];
}
}
foreach ($field_tables as $type => $table_info) {
$table_alias = $table_info['alias'];
$data[$table_alias]['table']['title'] = $bundle_field->getLabel();
$data[$table_alias]['table']['help'] = $bundle_field->getDescription();
$data[$table_alias]['table']['entity type'] = $this->entityType->id();
$data[$table_alias]['table']['provider'] = $this->entityType->getProvider();
$this->mapFieldDefinition($table_info['table'], $field_name, $bundle_field, $this->tableMapping, $data[$table_alias]);
}
}
/**
* {@inheritDoc}
*/
protected function mapFieldDefinition($table, $field_name, FieldDefinitionInterface $field_definition, TableMappingInterface $table_mapping, &$table_data) {
$field_column_mapping = $table_mapping->getColumnNames($field_name);
$field_storage = $this->getFieldStorageDefinitions()[$field_name];
$field_schema = $field_storage->getSchema();
$field_definition_type = $field_definition->getType();
// Add all properties to views table data. We need an entry for each
// column of each field, with the main one given special treatment.
$main_property = $field_storage->getMainPropertyName();
if (!$main_property) {
// The mapSingleFieldViewsData() method always expects a main property,
// so there must be a fallback to the first defined property.
// See #2337517 for the related core issue.
$property_names = array_keys($field_column_mapping);
$main_property = reset($property_names);
}
foreach ($field_column_mapping as $field_column_name => $schema_field_name) {
$first = ($main_property == $field_column_name);
$table_data[$schema_field_name] = $this->mapSingleFieldViewsData($table, $field_name, $field_definition_type, $field_column_name, $field_schema['columns'][$field_column_name]['type'], $first, $field_definition);
$table_data[$schema_field_name]['entity field'] = $field_name;
// By default core makes every property render the entire field, which
// confuses users. Fix that so only the property itself is rendered.
// Workaround for core issue #3097636.
if (!$first && $table_data[$schema_field_name]['field']['id'] == 'field') {
$table_data[$schema_field_name]['field']['id'] = 'standard';
}
// Many handlers (datetime, list) crash without the field_name defined.
foreach (['argument', 'filter', 'sort'] as $handler_type) {
if (isset($table_data[$schema_field_name][$handler_type])) {
$table_data[$schema_field_name][$handler_type]['field_name'] = $field_name;
}
}
}
// Expose additional delta column for multiple value fields.
// Workaround for core issue #3097568.
if ($field_storage->isMultiple()) {
$label = $field_definition->getLabel();
$table_data['delta'] = [
'title' => $this->t('@label (@name:delta)', ['@label' => $label, '@name' => $field_name]),
'title short' => $this->t('@label:delta', ['@label' => $label]),
];
$table_data['delta']['field'] = [
'id' => 'numeric',
];
$table_data['delta']['argument'] = [
'field' => 'delta',
'table' => $table,
'id' => 'numeric',
'empty field name' => $this->t('- No value -'),
'field_name' => $field_name,
'entity_type' => $this->entityType->id(),
];
$table_data['delta']['filter'] = [
'field' => 'delta',
'table' => $table,
'id' => 'numeric',
'field_name' => $field_name,
'entity_type' => $this->entityType->id(),
'allow empty' => TRUE,
];
$table_data['delta']['sort'] = [
'field' => 'delta',
'table' => $table,
'id' => 'standard',
'field_name' => $field_name,
'entity_type' => $this->entityType->id(),
];
}
}
/**
* Corrects the views data for datetime base fields.
*
* Based on datetime_field_views_data().
*
* @param string $table
* The table name.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition.
* @param array $views_field
* The views field data.
* @param string $field_column_name
* The field column being processed.
*/
protected function processViewsDataForDatetime($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
if ($field_column_name == 'value') {
$views_field['filter']['id'] = 'datetime';
$views_field['argument']['id'] = 'datetime';
$views_field['sort']['id'] = 'datetime';
}
}
/**
* Corrects the views data for list_float base fields.
*
* Based on options_field_views_data().
*
* @param string $table
* The table name.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition.
* @param array $views_field
* The views field data.
* @param string $field_column_name
* The field column being processed.
*/
protected function processViewsDataForListFloat($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
$this->processViewsDataForListInteger($table, $field_definition, $views_field, $field_column_name);
}
/**
* Corrects the views data for list_integer base fields.
*
* Based on options_field_views_data().
*
* @param string $table
* The table name.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition.
* @param array $views_field
* The views field data.
* @param string $field_column_name
* The field column being processed.
*/
protected function processViewsDataForListInteger($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
if ($field_column_name == 'value') {
$views_field['filter']['id'] = 'list_field';
$views_field['argument']['id'] = 'number_list_field';
}
}
/**
* Corrects the views data for list_string base fields.
*
* Based on options_field_views_data().
*
* @param string $table
* The table name.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition.
* @param array $views_field
* The views field data.
* @param string $field_column_name
* The field column being processed.
*/
protected function processViewsDataForListString($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
if ($field_column_name == 'value') {
$views_field['filter']['id'] = 'list_field';
$views_field['argument']['id'] = 'string_list_field';
}
}
/**
* Adds reverse relationships for the base entity reference fields.
*
* @param array $data
* The views data.
* @param \Drupal\Core\Field\BaseFieldDefinition[] $fields
* The entity reference fields.
*/
protected function addReverseRelationships(array &$data, array $fields) {
$entity_type_id = $this->entityType->id();
$base_table = $this->getViewsTableForEntityType($this->entityType);
assert($this->entityType instanceof ContentEntityType);
$revision_metadata_field_names = array_flip($this->entityType->getRevisionMetadataKeys());
foreach ($fields as $field) {
$target_entity_type_id = $field->getSettings()['target_type'];
$target_entity_type = $this->getEntityTypeManager()->getDefinition($target_entity_type_id);
if (!($target_entity_type instanceof ContentEntityType)) {
continue;
}
$target_table = $this->getViewsTableForEntityType($target_entity_type);
$field_name = $field->getName();
$field_storage = $field->getFieldStorageDefinition();
$args = [
'@label' => $target_entity_type->getSingularLabel(),
'@entity' => $this->entityType->getLabel(),
'@field_name' => $field_name,
];
$pseudo_field_name = 'reverse__' . $entity_type_id . '__' . $field_name;
$relationship_data = [
'label' => $this->entityType->getLabel(),
'group' => $target_entity_type->getLabel(),
'entity_type' => $entity_type_id,
];
if ($this->tableMapping->requiresDedicatedTableStorage($field_storage)) {
$data[$target_table][$pseudo_field_name]['relationship'] = [
'id' => 'entity_reverse',
'title' => $this->t('@entity using @field_name', $args),
'help' => $this->t('Relate each @entity with a @field_name field set to the @label.', $args),
'base' => $base_table,
'base field' => $this->entityType->getKey('id'),
'field_name' => $field_name,
'field table' => $this->tableMapping->getFieldTableName($field_name),
'field field' => $this->tableMapping->getFieldColumnName($field_storage, 'target_id'),
] + $relationship_data;
}
elseif (isset($revision_metadata_field_names[$field_name])) {
// Revision metadata fields exist only on the revision table, so the
// relationship has to be to that rather than to the base table.
$revision_table = $this->tableMapping->getRevisionTable();
$data[$target_table][$pseudo_field_name]['relationship'] = [
'id' => 'standard',
'title' => $this->t('@entity revision using @field_name', $args),
'help' => $this->t('Relate each @entity revision with a @field_name field set to the @label.', $args),
'base' => $revision_table,
'base field' => $this->tableMapping->getFieldColumnName($field_storage, 'target_id'),
'relationship field' => $target_entity_type->getKey('id'),
] + $relationship_data;
}
else {
// The data is on the base table.
$data[$target_table][$pseudo_field_name]['relationship'] = [
'id' => 'standard',
'title' => $this->t('@entity using @field_name', $args),
'help' => $this->t('Relate each @entity with a @field_name field set to the @label.', $args),
'base' => $base_table,
'base field' => $this->tableMapping->getFieldColumnName($field_storage, 'target_id'),
'relationship field' => $target_entity_type->getKey('id'),
] + $relationship_data;
}
}
}
/**
* Gets the entity field manager.
*
* @todo Remove when support for Drupal 8.7 is dropped.
*
* @return \Drupal\Core\Entity\EntityFieldManagerInterface
* The entity field manager.
*/
protected function getEntityFieldManager() {
if (!isset($this->entityFieldManager)) {
return \Drupal::service('entity_field.manager');
}
return $this->entityFieldManager;
}
/**
* Gets the entity type bundle info.
*
* @todo Remove when support for Drupal 8.7 is dropped.
*
* @return \Drupal\Core\Entity\EntityTypeBundleInfoInterface
* The entity type bundle info.
*/
protected function getEntityTypeBundleInfo() {
if (!isset($this->entityTypeBundleInfo)) {
return \Drupal::service('entity_type.bundle.info');
}
return $this->entityTypeBundleInfo;
}
/**
* Gets the entity type manager.
*
* @todo Remove when support for Drupal 8.7 is dropped.
*
* @return \Drupal\Core\Entity\EntityTypeManagerInterface
* The entity type manager.
*/
protected function getEntityTypeManager() {
if (!isset($this->entityTypeManager)) {
return \Drupal::entityTypeManager();
}
return $this->entityTypeManager;
}
}
@@ -0,0 +1,62 @@
<?php
namespace Drupal\entity\Event;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Component\EventDispatcher\Event;
/**
* Defines the entity duplicate event.
*
* @see \Drupal\entity\Event\EntityEvents
*/
class EntityDuplicateEvent extends Event {
/**
* The entity.
*
* @var \Drupal\Core\Entity\EntityInterface
*/
protected $entity;
/**
* The source entity.
*
* @var \Drupal\Core\Entity\EntityInterface
*/
protected $sourceEntity;
/**
* Constructs a new EntityDuplicateEvent object.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
* @param \Drupal\Core\Entity\EntityInterface $source_entity
* The source entity.
*/
public function __construct(EntityInterface $entity, EntityInterface $source_entity) {
$this->entity = $entity;
$this->sourceEntity = $source_entity;
}
/**
* Gets the entity.
*
* @return \Drupal\Core\Entity\EntityInterface
* The entity.
*/
public function getEntity() {
return $this->entity;
}
/**
* Gets the source entity.
*
* @return \Drupal\Core\Entity\EntityInterface
* The source entity.
*/
public function getSourceEntity() {
return $this->sourceEntity;
}
}
@@ -0,0 +1,19 @@
<?php
namespace Drupal\entity\Event;
/**
* Defines events for the Entity module.
*/
final class EntityEvents {
/**
* Name of the event fired after saving a duplicated entity.
*
* @Event
*
* @see \Drupal\entity\Event\EntityDuplicateEvent
*/
const ENTITY_DUPLICATE = 'entity.duplicate';
}
@@ -0,0 +1,55 @@
<?php
namespace Drupal\entity\EventSubscriber;
use Drupal\entity\BundleEntityDuplicatorInterface;
use Drupal\entity\Event\EntityDuplicateEvent;
use Drupal\entity\Event\EntityEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EntityDuplicateSubscriber implements EventSubscriberInterface {
/**
* The bundle entity duplicator.
*
* @var \Drupal\entity\BundleEntityDuplicatorInterface
*/
protected $bundleEntityDuplicator;
/**
* Constructs a new EntityDuplicateSubscriber object.
*
* @param \Drupal\entity\BundleEntityDuplicatorInterface $bundle_entity_duplicator
* The bundle entity duplicator.
*/
public function __construct(BundleEntityDuplicatorInterface $bundle_entity_duplicator) {
$this->bundleEntityDuplicator = $bundle_entity_duplicator;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [
EntityEvents::ENTITY_DUPLICATE => ['onEntityDuplicate'],
];
return $events;
}
/**
* Duplicates bundle fields and displays.
*
* @param \Drupal\entity\Event\EntityDuplicateEvent $event
* The entity duplicate event.
*/
public function onEntityDuplicate(EntityDuplicateEvent $event) {
$entity = $event->getEntity();
if ($entity->getEntityType()->getBundleOf()) {
/** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $source_entity */
$source_entity = $event->getSourceEntity();
$this->bundleEntityDuplicator->duplicateFields($source_entity, $entity->id());
$this->bundleEntityDuplicator->duplicateDisplays($source_entity, $entity->id());
}
}
}
@@ -0,0 +1,14 @@
<?php
namespace Drupal\entity\Form;
use Drupal\Core\Entity\Form\DeleteMultipleForm as CoreDeleteMultipleForm;
@trigger_error('\Drupal\entity\Form\DeleteMultipleForm has been deprecated in favor of \Drupal\Core\Entity\Form\DeleteMultipleForm. Use that instead.');
/**
* Provides an entities deletion confirmation form.
*
* @deprecated Use \Drupal\Core\Entity\Form\DeleteMultipleForm instead.
*/
class DeleteMultipleForm extends CoreDeleteMultipleForm {}
@@ -0,0 +1,33 @@
<?php
namespace Drupal\entity\Form;
use Drupal\Core\Entity\EntityFormInterface;
use Drupal\Core\Entity\EntityInterface;
/**
* Defines an interface for entity duplicate forms.
*/
interface EntityDuplicateFormInterface extends EntityFormInterface {
/**
* Gets the source entity.
*
* This is the entity that was duplicated to populate the form entity.
*
* @return \Drupal\Core\Entity\EntityInterface
* The source entity.
*/
public function getSourceEntity();
/**
* Sets the source entity.
*
* @param \Drupal\Core\Entity\EntityInterface $source_entity
* The source entity.
*
* @return $this
*/
public function setSourceEntity(EntityInterface $source_entity);
}
@@ -0,0 +1,58 @@
<?php
namespace Drupal\entity\Form;
use Drupal\Core\Entity\EntityInterface;
use Drupal\entity\Event\EntityDuplicateEvent;
use Drupal\entity\Event\EntityEvents;
/**
* Allows forms to implement EntityDuplicateFormInterface.
*
* Forms are expected to call $this->postSave() after the entity is saved.
* This works around core issue #3040556.
*/
trait EntityDuplicateFormTrait {
/**
* The source entity.
*
* @var \Drupal\Core\Entity\EntityInterface
*/
protected $sourceEntity;
/**
* {@inheritdoc}
*/
public function getSourceEntity() {
return $this->sourceEntity;
}
/**
* {@inheritdoc}
*/
public function setSourceEntity(EntityInterface $source_entity) {
$this->sourceEntity = $source_entity;
return $this;
}
/**
* Invokes entity duplicate hooks after the entity has been duplicated.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The saved entity.
* @param string $operation
* The form operation.
*/
protected function postSave(EntityInterface $entity, $operation) {
if ($operation == 'duplicate') {
// An event is used instead of a hook to prevent a conflict with core
// once hook_entity_duplicate() is introduced there.
$event = new EntityDuplicateEvent($entity, $this->sourceEntity);
/** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher */
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch($event, EntityEvents::ENTITY_DUPLICATE);
}
}
}
@@ -0,0 +1,174 @@
<?php
namespace Drupal\entity\Form;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\RevisionableInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
class RevisionRevertForm extends ConfirmFormBase {
/**
* The entity revision.
*
* @var \Drupal\Core\Entity\EntityInterface|\Drupal\Core\Entity\RevisionableInterface|\Drupal\Core\Entity\RevisionLogInterface
*/
protected $revision;
/**
* The date formatter.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* The entity bundle information.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInformation;
/**
* Creates a new RevisionRevertForm instance.
*
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_information
* The bundle information.
*/
public function __construct(DateFormatterInterface $date_formatter, EntityTypeBundleInfoInterface $bundle_information) {
$this->dateFormatter = $date_formatter;
$this->bundleInformation = $bundle_information;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('date.formatter'),
$container->get('entity_type.bundle.info')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'entity_revision_revert_confirm';
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
if ($this->revision instanceof RevisionLogInterface) {
return $this->t('Are you sure you want to revert to the revision from %revision-date?', ['%revision-date' => $this->dateFormatter->format($this->revision->getRevisionCreationTime())]);
}
return $this->t('Are you sure you want to revert the revision?');
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
if ($this->revision->getEntityType()->hasLinkTemplate('version-history')) {
return $this->revision->toUrl('version-history');
}
return $this->revision->toUrl();
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Revert');
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return '';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $_entity_revision = NULL, Request $request = NULL) {
$this->revision = $_entity_revision;
$form = parent::buildForm($form, $form_state);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// The revision timestamp will be updated when the revision is saved. Keep
// the original one for the confirmation message.
$this->revision = $this->prepareRevision($this->revision);
if ($this->revision instanceof RevisionLogInterface) {
$original_revision_timestamp = $this->revision->getRevisionCreationTime();
$this->revision->setRevisionLogMessage($this->t('Copy of the revision from %date.', ['%date' => $this->dateFormatter->format($original_revision_timestamp)]));
$this->messenger()->addStatus($this->t('@type %title has been reverted to the revision from %revision-date.', [
'@type' => $this->getBundleLabel($this->revision),
'%title' => $this->revision->label(),
'%revision-date' => $this->dateFormatter->format($original_revision_timestamp),
]));
}
else {
$this->messenger()->addStatus($this->t('@type %title has been reverted', [
'@type' => $this->getBundleLabel($this->revision),
'%title' => $this->revision->label(),
]));
}
$this->revision->save();
$this->logger('content')->notice('@type: reverted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]);
$form_state->setRedirect(
"entity.{$this->revision->getEntityTypeId()}.version_history",
[$this->revision->getEntityTypeId() => $this->revision->id()]
);
}
/**
* Prepares a revision to be reverted.
*
* @param \Drupal\Core\Entity\RevisionableInterface $revision
* The revision to be reverted.
*
* @return \Drupal\Core\Entity\RevisionableInterface
* The prepared revision ready to be stored.
*/
protected function prepareRevision(RevisionableInterface $revision) {
$revision->setNewRevision();
$revision->isDefaultRevision(TRUE);
return $revision;
}
/**
* Returns a bundle label.
*
* @param \Drupal\Core\Entity\RevisionableInterface $revision
* The entity revision.
*
* @return string
*/
protected function getBundleLabel(RevisionableInterface $revision) {
/** @var \Drupal\Core\Entity\EntityInterface|\Drupal\Core\Entity\RevisionableInterface $revision */
$bundle_info = $this->bundleInformation->getBundleInfo($revision->getEntityTypeId());
return $bundle_info[$revision->bundle()]['label'];
}
}
@@ -0,0 +1,165 @@
<?php
namespace Drupal\entity\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\RevisionableEntityBundleInterface;
use Drupal\Core\Form\FormStateInterface;
@trigger_error('\Drupal\entity\Form\RevisionableContentEntityForm has been deprecated in favor of \Drupal\Core\Entity\ContentEntityForm. Use that instead.');
/**
* Extends the base entity form with revision support in the UI.
*
* @deprecated Use \Drupal\Core\Entity\ContentEntityForm instead.
*/
class RevisionableContentEntityForm extends ContentEntityForm {
/**
* The entity being used by this form.
*
* @var \Drupal\Core\Entity\ContentEntityInterface|\Drupal\Core\Entity\RevisionLogInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected function prepareEntity() {
parent::prepareEntity();
$bundle_entity = $this->getBundleEntity();
// Set up default values, if required.
if (!$this->entity->isNew()) {
$this->entity->setRevisionLogMessage(NULL);
}
if ($bundle_entity instanceof RevisionableEntityBundleInterface) {
// Always use the default revision setting.
$this->entity->setNewRevision($bundle_entity && $bundle_entity->shouldCreateNewRevision());
}
}
/**
* Gets the bundle entity of the current entity.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* The bundle entity, or NULL if there is none.
*/
protected function getBundleEntity() {
if ($this->entity->getEntityType()->getBundleEntityType()) {
$bundle_key = $this->entity->getEntityType()->getKey('bundle');
return $this->entity->{$bundle_key}->referencedEntities()[0];
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$entity_type = $this->entity->getEntityType();
$bundle_entity = $this->getBundleEntity();
$account = $this->currentUser();
if ($this->operation == 'edit') {
$form['#title'] = $this->t('Edit %bundle_label @label', [
'%bundle_label' => $bundle_entity ? $bundle_entity->label() : '',
'@label' => $this->entity->label(),
]);
}
$form['advanced'] = [
'#type' => 'vertical_tabs',
'#weight' => 99,
];
// Add a log field if the "Create new revision" option is checked, or if the
// current user has the ability to check that option.
// @todo Could we autogenerate this form by using some widget on the
// revision info field.
$form['revision_information'] = [
'#type' => 'details',
'#title' => $this->t('Revision information'),
// Open by default when "Create new revision" is checked.
'#open' => $this->entity->isNewRevision(),
'#group' => 'advanced',
'#weight' => 20,
'#access' => $this->entity->isNewRevision() || $account->hasPermission($entity_type->get('admin_permission')),
];
$form['revision_information']['revision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Create new revision'),
'#default_value' => $this->entity->isNewRevision(),
'#access' => $account->hasPermission($entity_type->get('admin_permission')),
];
// Check the revision log checkbox when the log textarea is filled in.
// This must not happen if "Create new revision" is enabled by default,
// since the state would auto-disable the checkbox otherwise.
if (!$this->entity->isNewRevision()) {
$form['revision_information']['revision']['#states'] = [
'checked' => [
'textarea[name="revision_log"]' => ['empty' => FALSE],
],
];
}
$form['revision_information']['revision_log'] = [
'#type' => 'textarea',
'#title' => $this->t('Revision log message'),
'#rows' => 4,
'#default_value' => $this->entity->getRevisionLogMessage(),
'#description' => $this->t('Briefly describe the changes you have made.'),
];
return parent::form($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
// Save as a new revision if requested to do so.
if (!$form_state->isValueEmpty('revision')) {
$this->entity->setNewRevision();
}
$insert = $this->entity->isNew();
$this->entity->save();
$context = ['@type' => $this->entity->bundle(), '%info' => $this->entity->label()];
$logger = $this->logger('content');
$bundle_entity = $this->getBundleEntity();
$t_args = ['@type' => $bundle_entity ? $bundle_entity->label() : 'None', '%info' => $this->entity->label()];
if ($insert) {
$logger->notice('@type: added %info.', $context);
drupal_set_message($this->t('@type %info has been created.', $t_args));
}
else {
$logger->notice('@type: updated %info.', $context);
drupal_set_message($this->t('@type %info has been updated.', $t_args));
}
if ($this->entity->id()) {
$form_state->setValue('id', $this->entity->id());
$form_state->set('id', $this->entity->id());
if ($this->entity->getEntityType()->hasLinkTemplate('collection')) {
$form_state->setRedirectUrl($this->entity->toUrl('collection'));
}
else {
$form_state->setRedirectUrl($this->entity->toUrl('canonical'));
}
}
else {
// In the unlikely case something went wrong on save, the entity will be
// rebuilt and entity form redisplayed.
drupal_set_message($this->t('The entity could not be saved.'), 'error');
$form_state->setRebuild();
}
}
}
@@ -0,0 +1,81 @@
<?php
namespace Drupal\entity\Menu;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a set of tasks to view, edit and duplicate an entity.
*/
class DefaultEntityLocalTaskProvider implements EntityLocalTaskProviderInterface, EntityHandlerInterface {
use StringTranslationTrait;
/**
* Constructs a DefaultEntityLocalTaskProvider object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
*/
public function __construct(EntityTypeInterface $entity_type, TranslationInterface $string_translation) {
$this->setStringTranslation($string_translation);
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($entity_type, $container->get('string_translation'));
}
/**
* {@inheritdoc}
*/
public function buildLocalTasks(EntityTypeInterface $entity_type) {
// Note: delete-form was intentionally omitted, to match core. See #1834002.
$link_templates = [];
foreach (['canonical', 'edit-form', 'duplicate-form'] as $rel) {
if ($entity_type->hasLinkTemplate($rel)) {
$link_templates[] = str_replace('-', '_', $rel);
}
}
if (version_compare(\Drupal::VERSION, 10.1, '<') && $entity_type->hasLinkTemplate('version-history')) {
$link_templates[] = 'version_history';
}
$tasks = [];
if (count($link_templates) > 1) {
$entity_type_id = $entity_type->id();
$base = reset($link_templates);
$titles = [
'canonical' => $this->t('View'),
'edit_form' => $this->t('Edit'),
'duplicate_form' => $this->t('Duplicate'),
'version_history' => $this->t('Revisions'),
];
$weight = 0;
foreach ($link_templates as $rel) {
$route_name = "entity.$entity_type_id.$rel";
$tasks[$route_name] = [
'title' => $titles[$rel],
'route_name' => $route_name,
'base_route' => "entity.$entity_type_id.$base",
'weight' => $weight,
];
$weight += 10;
}
}
return $tasks;
}
}
@@ -0,0 +1,71 @@
<?php
namespace Drupal\entity\Menu;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a action link to the add page or add form on the collection.
*/
class EntityCollectionLocalActionProvider implements EntityLocalActionProviderInterface, EntityHandlerInterface {
use StringTranslationTrait;
/**
* Constructs a new EntityCollectionLocalActionProvider object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
*/
public function __construct(EntityTypeInterface $entity_type, TranslationInterface $string_translation) {
$this->setStringTranslation($string_translation);
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($entity_type, $container->get('string_translation'));
}
/**
* {@inheritdoc}
*/
public function buildLocalActions(EntityTypeInterface $entity_type) {
$actions = [];
if ($entity_type->hasLinkTemplate('collection')) {
$entity_type_id = $entity_type->id();
if ($entity_type->hasLinkTemplate('add-page')) {
$route_name = "entity.$entity_type_id.add_page";
}
elseif ($entity_type->hasLinkTemplate('add-form')) {
$route_name = "entity.$entity_type_id.add_form";
}
if (isset($route_name)) {
$actions[$route_name] = [
'title' => $this->t('Add @entity', [
'@entity' => $entity_type->getSingularLabel(),
]),
'route_name' => $route_name,
'options' => [
// Redirect back to the collection after form submission.
'query' => [
'destination' => $entity_type->getLinkTemplate('collection'),
],
],
'appears_on' => ["entity.$entity_type_id.collection"],
];
}
}
return $actions;
}
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\entity\Menu;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Provides an interface for entity local action providers.
*/
interface EntityLocalActionProviderInterface {
/**
* Builds local actions for the given entity type.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array[]
* An array of local action definitions.
*/
public function buildLocalActions(EntityTypeInterface $entity_type);
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\entity\Menu;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Provides an interface for entity local task providers.
*/
interface EntityLocalTaskProviderInterface {
/**
* Builds local tasks for the given entity type.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array[]
* An array of local task definitions.
*/
public function buildLocalTasks(EntityTypeInterface $entity_type);
}
@@ -0,0 +1,20 @@
<?php
namespace Drupal\entity\Plugin\Action;
use Drupal\Core\Action\Plugin\Action\DeleteAction as CoreDeleteAction;
@trigger_error('\Drupal\entity\Plugin\Action\DeleteAction has been deprecated in favor of \Drupal\Core\Action\Plugin\Action\DeleteAction. Use that instead.');
/**
* Redirects to an entity deletion form.
*
* @deprecated Use "entity:delete_action" instead.
*
* @Action(
* id = "entity_delete_action",
* label = @Translation("Delete entity"),
* deriver = "Drupal\entity\Plugin\Action\Derivative\DeleteActionDeriver",
* )
*/
class DeleteAction extends CoreDeleteAction {}
@@ -0,0 +1,85 @@
<?php
namespace Drupal\entity\Plugin\Action\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Provides a delete action for each content entity type.
*
* @deprecated
*/
class DeleteActionDeriver extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new DeleteActionDeriver object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static($container->get('entity_type.manager'));
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
if (empty($this->derivatives)) {
$definitions = [];
foreach ($this->getParticipatingEntityTypes() as $entity_type_id => $entity_type) {
$definition = $base_plugin_definition;
$definition['label'] = $this->t('Delete @entity_type (Deprecated)', ['@entity_type' => $entity_type->getSingularLabel()]);
$definition['type'] = $entity_type_id;
$definition['confirm_form_route_name'] = 'entity.' . $entity_type_id . '.delete_multiple_form';
$definitions[$entity_type_id] = $definition;
}
$this->derivatives = $definitions;
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
/**
* Gets a list of participating entity types.
*
* The list consists of all content entity types with a delete-multiple-form
* link template.
*
* @return \Drupal\Core\Entity\EntityTypeInterface[]
* The participating entity types, keyed by entity type id.
*/
protected function getParticipatingEntityTypes() {
$entity_types = $this->entityTypeManager->getDefinitions();
$entity_types = array_filter($entity_types, function (EntityTypeInterface $entity_type) {
// Core requires a "delete-multiple-confirm" form to be declared as well,
// if it's missing, it's safe to assume that the entity type is still
// relying on previous Entity API contrib behavior.
return $entity_type->hasLinkTemplate('delete-multiple-form') && !$entity_type->hasHandlerClass('form', 'delete-multiple-confirm');
});
return $entity_types;
}
}
@@ -0,0 +1,58 @@
<?php
namespace Drupal\entity\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Derives local actions for entity types.
*/
class EntityActionsDeriver extends DeriverBase implements ContainerDeriverInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs an entity local actions deriver.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static($container->get('entity_type.manager'));
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
if (!$this->derivatives) {
foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
$handlers = $entity_type->getHandlerClasses();
if (isset($handlers['local_action_provider'])) {
foreach ($handlers['local_action_provider'] as $class) {
/** @var \Drupal\entity\Menu\EntityLocalActionProviderInterface $handler */
$handler = $this->entityTypeManager->createHandlerInstance($class, $entity_type);
$this->derivatives += $handler->buildLocalActions($entity_type);
}
}
}
}
return $this->derivatives;
}
}
@@ -0,0 +1,58 @@
<?php
namespace Drupal\entity\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Derives local tasks for entity types.
*/
class EntityTasksDeriver extends DeriverBase implements ContainerDeriverInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs an entity local tasks deriver.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static($container->get('entity_type.manager'));
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
if (!$this->derivatives) {
foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
$handlers = $entity_type->getHandlerClasses();
if (isset($handlers['local_task_provider'])) {
foreach ($handlers['local_task_provider'] as $class) {
/** @var \Drupal\entity\Menu\EntityLocalTaskProviderInterface $handler */
$handler = $this->entityTypeManager->createHandlerInstance($class, $entity_type);
$this->derivatives += $handler->buildLocalTasks($entity_type);
}
}
}
}
return $this->derivatives;
}
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\entity\Plugin\views\field;
use Drupal\views\Plugin\views\field\EntityLink;
/**
* Field handler to present a link to an entity revision.
*
* @ingroup views_field_handlers
*
* @ViewsField("entity_link_revision")
*/
class EntityLinkRevision extends EntityLink {
/**
* {@inheritdoc}
*/
protected function getEntityLinkTemplate() {
return 'revision';
}
}
@@ -0,0 +1,39 @@
<?php
namespace Drupal\entity\Plugin\views\field;
use Drupal\views\Plugin\views\field\EntityLink;
use Drupal\views\ResultRow;
/**
* Field handler to present a link to revert an entity to a revision.
*
* @ingroup views_field_handlers
*
* @ViewsField("entity_link_revision_revert")
*/
class EntityLinkRevisionRevert extends EntityLink {
/**
* {@inheritdoc}
*/
protected function getEntityLinkTemplate() {
return 'revision-revert-form';
}
/**
* {@inheritdoc}
*/
protected function renderLink(ResultRow $row) {
$this->options['alter']['query'] = $this->getDestinationArray();
return parent::renderLink($row);
}
/**
* {@inheritdoc}
*/
protected function getDefaultLabel() {
return $this->t('revert');
}
}
@@ -0,0 +1,113 @@
<?php
namespace Drupal\entity\QueryAccess;
/**
* Represents a single query access condition.
*/
final class Condition {
/**
* The supported operators.
*
* @var string[]
*/
protected static $supportedOperators = [
'=', '<>', '<', '<=', '>', '>=', 'BETWEEN', 'NOT BETWEEN',
'IN', 'NOT IN', 'IS NULL', 'IS NOT NULL',
];
/**
* The field.
*
* @var string
*/
protected $field;
/**
* The value.
*
* @var mixed
*/
protected $value;
/**
* The operator.
*
* @var string
*/
protected $operator;
/**
* Constructs a new Condition object.
*
* @param string $field
* The field, with an optional column name. E.g: 'uid', 'address.locality'.
* @param mixed $value
* The value.
* @param string $operator
* The operator.
* Possible values: =, <>, <, <=, >, >=, BETWEEN, NOT BETWEEN,
* IN, NOT IN, IS NULL, IS NOT NULL.
*/
public function __construct($field, $value, $operator = NULL) {
// Provide a default based on the data type of the value.
if (!isset($operator)) {
$operator = is_array($value) ? 'IN' : '=';
}
// Validate the selected operator.
if (!in_array($operator, self::$supportedOperators)) {
throw new \InvalidArgumentException(sprintf('Unrecognized operator "%s".', $operator));
}
$this->field = $field;
$this->value = $value;
$this->operator = $operator;
}
/**
* {@inheritdoc}
*/
public function getField() {
return $this->field;
}
/**
* {@inheritdoc}
*/
public function getValue() {
return $this->value;
}
/**
* {@inheritdoc}
*/
public function getOperator() {
return $this->operator;
}
/**
* Gets the string representation of the condition.
*
* Used for debugging purposes.
*
* @return string
* The string representation of the condition.
*/
public function __toString() {
if (in_array($this->operator, ['IS NULL', 'IS NOT NULL'])) {
return "{$this->field} {$this->operator}";
}
else {
if (is_array($this->value)) {
$value = "['" . implode("', '", $this->value) . "']";
}
else {
$value = "'" . $this->value . "'";
}
return "{$this->field} {$this->operator} $value";
}
}
}
@@ -0,0 +1,227 @@
<?php
namespace Drupal\entity\QueryAccess;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\Core\Cache\RefinableCacheableDependencyTrait;
/**
* Represents a group of query access conditions.
*
* Used by query access handlers for filtering lists of entities based on
* granted permissions.
*
* Examples:
* @code
* // Filter by node type and uid.
* $condition_group = new ConditionGroup();
* $condition_group->addCondition('type', ['article', 'page']);
* $condition_group->addCondition('uid', '1');
*
* // Filter by node type or status.
* $condition_group = new ConditionGroup('OR');
* $condition_group->addCondition('type', ['article', 'page']);
* $condition_group->addCondition('status', '1', '<>');
*
* // Nested condition groups: node type AND (uid OR status).
* $condition_group = new ConditionGroup();
* $condition_group->addCondition('type', ['article', 'page']);
* $condition_group->addCondition((new ConditionGroup('OR'))
* ->addCondition('uid', 1)
* ->addCondition('status', '1')
* );
* @endcode
*/
final class ConditionGroup implements \Countable, RefinableCacheableDependencyInterface {
use RefinableCacheableDependencyTrait;
/**
* The conjunction.
*
* @var string
*/
protected $conjunction;
/**
* The conditions.
*
* @var \Drupal\entity\QueryAccess\Condition[]|\Drupal\entity\QueryAccess\ConditionGroup[]
*/
protected $conditions = [];
/**
* Whether the condition group is always FALSE.
*
* @var bool
*/
protected $alwaysFalse = FALSE;
/**
* Constructs a new ConditionGroup object.
*
* @param string $conjunction
* The conjunction.
*/
public function __construct($conjunction = 'AND') {
$this->conjunction = $conjunction;
}
/**
* Gets the conjunction.
*
* @return string
* The conjunction. Possible values: AND, OR.
*/
public function getConjunction() {
return $this->conjunction;
}
/**
* Gets all conditions and nested condition groups.
*
* @return \Drupal\entity\QueryAccess\Condition[]|\Drupal\entity\QueryAccess\ConditionGroup[]
* The conditions, where each one is either a Condition or a nested
* ConditionGroup. Returned by reference, to allow callers to replace
* or remove conditions.
*/
public function &getConditions() {
return $this->conditions;
}
/**
* Adds a condition.
*
* @param string|\Drupal\entity\QueryAccess\ConditionGroup $field
* Either a condition group (for nested AND/OR conditions), or a
* field name with an optional column name. E.g: 'uid', 'address.locality'.
* @param mixed $value
* The value.
* @param string $operator
* The operator.
* Possible values: =, <>, <, <=, >, >=, BETWEEN, NOT BETWEEN,
* IN, NOT IN, IS NULL, IS NOT NULL.
*
* @return $this
*/
public function addCondition($field, $value = NULL, $operator = NULL) {
if ($field instanceof ConditionGroup) {
if ($field->count() === 1) {
// The condition group only has a single condition, merge it.
$this->conditions[] = reset($field->getConditions());
$this->addCacheTags($field->getCacheTags());
$this->addCacheContexts($field->getCacheContexts());
$this->mergeCacheMaxAge($field->getCacheMaxAge());
}
elseif ($field->count() > 1) {
$this->conditions[] = $field;
}
}
else {
$this->conditions[] = new Condition($field, $value, $operator);
}
return $this;
}
/**
* Gets whether the condition group is always FALSE.
*
* Used when the user doesn't have access to any entities, to ensure that a
* query returns no results.
*
* @return bool
* Whether the condition group is always FALSE.
*/
public function isAlwaysFalse() {
return $this->alwaysFalse;
}
/**
* Sets whether the condition group should always be FALSE.
*
* @param bool $always_false
* Whether the condition group should always be FALSE.
*
* @return $this
*/
public function alwaysFalse($always_false = TRUE) {
$this->alwaysFalse = $always_false;
return $this;
}
/**
* Clones the contained conditions when the condition group is cloned.
*/
public function __clone() {
foreach ($this->conditions as $i => $condition) {
$this->conditions[$i] = clone $condition;
}
}
/**
* Gets the string representation of the condition group.
*
* @return string
* The string representation of the condition group.
*/
public function __toString() {
// Special case for a single, nested condition group:
if (count($this->conditions) == 1) {
return (string) reset($this->conditions);
}
$lines = [];
foreach ($this->conditions as $condition) {
$lines[] = str_replace("\n", "\n ", (string) $condition);
}
return $lines ? "(\n " . implode("\n {$this->conjunction}\n ", $lines) . "\n)" : '';
}
/**
* {@inheritdoc}
*/
public function count(): int {
return count($this->conditions);
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
$tags = $this->cacheTags;
foreach ($this->conditions as $condition) {
if ($condition instanceof ConditionGroup) {
$tags = array_merge($tags, $condition->getCacheTags());
}
}
return Cache::mergeTags($tags, []);
}
/**
* {@inheritdoc}
*/
public function getCacheContexts() {
$cache_contexts = $this->cacheContexts;
foreach ($this->conditions as $condition) {
if ($condition instanceof ConditionGroup) {
$cache_contexts = array_merge($cache_contexts, $condition->getCacheContexts());
}
}
return Cache::mergeContexts($cache_contexts);
}
/**
* {@inheritdoc}
*/
public function getCacheMaxAge() {
$max_age = $this->cacheMaxAge;
foreach ($this->conditions as $condition) {
if ($condition instanceof ConditionGroup) {
$max_age = Cache::mergeMaxAges($max_age, $condition->getCacheMaxAge());
}
}
return $max_age;
}
}
@@ -0,0 +1,199 @@
<?php
namespace Drupal\entity\QueryAccess;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\Query\Sql\Tables;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
use Drupal\Core\Render\RendererInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Defines a class for altering entity queries.
*
* EntityQuery doesn't have an alter hook, forcing this class to operate
* on the underlying SQL query, duplicating the EntityQuery condition logic.
*
* @internal
*/
class EntityQueryAlter implements ContainerInjectionInterface {
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* Constructs a new EntityQueryAlter object.
*
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
* The request stack.
*/
public function __construct(EntityFieldManagerInterface $entity_field_manager, EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer, RequestStack $request_stack) {
$this->entityFieldManager = $entity_field_manager;
$this->entityTypeManager = $entity_type_manager;
$this->renderer = $renderer;
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_field.manager'),
$container->get('entity_type.manager'),
$container->get('renderer'),
$container->get('request_stack')
);
}
/**
* Alters the select query for the given entity type.
*
* @param \Drupal\Core\Database\Query\SelectInterface $query
* The select query.
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*/
public function alter(SelectInterface $query, EntityTypeInterface $entity_type) {
if (!$entity_type->hasHandlerClass('query_access')) {
return;
}
$entity_type_id = $entity_type->id();
$storage = $this->entityTypeManager->getStorage($entity_type_id);
if (!$storage instanceof SqlContentEntityStorage) {
return;
}
/** @var \Drupal\entity\QueryAccess\QueryAccessHandlerInterface $query_access */
$query_access = $this->entityTypeManager->getHandler($entity_type_id, 'query_access');
$conditions = $query_access->getConditions($query->getMetaData('op') ?: 'view');
if ($conditions->isAlwaysFalse()) {
$query->where('1 = 0');
}
elseif (count($conditions)) {
$sql_conditions = $this->mapConditions($conditions, $query);
$query->condition($sql_conditions);
}
$this->applyCacheability(CacheableMetadata::createFromObject($conditions));
}
/**
* Maps an entity type's access conditions to SQL conditions.
*
* @param \Drupal\entity\QueryAccess\ConditionGroup $conditions
* The access conditions.
* @param \Drupal\Core\Database\Query\SelectInterface $query
* The SQL query.
* @param bool $nested_inside_or
* Whether the access conditions are nested inside an OR condition.
*
* @return \Drupal\Core\Database\Query\ConditionInterface
* The SQL conditions.
*/
protected function mapConditions(ConditionGroup $conditions, SelectInterface $query, $nested_inside_or = FALSE) {
$sql_condition = $query->conditionGroupFactory($conditions->getConjunction());
$tables = new Tables($query);
$nested_inside_or = $nested_inside_or || $conditions->getConjunction() == 'OR';
foreach ($conditions->getConditions() as $condition) {
if ($condition instanceof ConditionGroup) {
$nested_sql_conditions = $this->mapConditions($condition, $query, $nested_inside_or);
$sql_condition->condition($nested_sql_conditions);
}
else {
// Access conditions don't specify a langcode.
$langcode = NULL;
$type = $nested_inside_or || $condition->getOperator() === 'IS NULL' ? 'LEFT' : 'INNER';
$sql_field = $tables->addField($condition->getField(), $type, $langcode);
$value = $condition->getValue();
$operator = $condition->getOperator();
// Using LIKE/NOT LIKE ensures a case insensitive comparison.
// @see \Drupal\Core\Entity\Query\Sql\Condition::translateCondition().
$case_sensitive = $tables->isFieldCaseSensitive($condition->getField());
$operator_map = [
'=' => 'LIKE',
'<>' => 'NOT LIKE',
];
if ($case_sensitive === FALSE && isset($operator_map[$operator])) {
$operator = $operator_map[$operator];
$value = $query->escapeLike($value);
}
$sql_condition->condition($sql_field, $value, $operator);
}
}
return $sql_condition;
}
/**
* Applies the cacheability metadata to the current request.
*
* @param \Drupal\Core\Cache\CacheableMetadata $cacheable_metadata
* The cacheability metadata.
*/
protected function applyCacheability(CacheableMetadata $cacheable_metadata) {
$request = $this->requestStack->getCurrentRequest();
if ($request->isMethodCacheable() && $this->renderer->hasRenderContext() && $this->hasCacheableMetadata($cacheable_metadata)) {
$build = [];
$cacheable_metadata->applyTo($build);
$this->renderer->render($build);
}
}
/**
* Check if the cacheable metadata is not empty.
*
* An empty cacheable metadata object has no context, tags, and is permanent.
*
* @param \Drupal\Core\Cache\CacheableMetadata $cacheable_metadata
* The cacheable metadata.
*
* @return bool
* TRUE if there is cacheability metadata, otherwise FALSE.
*/
protected function hasCacheableMetadata(CacheableMetadata $cacheable_metadata) {
return $cacheable_metadata->getCacheMaxAge() !== Cache::PERMANENT
|| count($cacheable_metadata->getCacheContexts()) > 0
|| count($cacheable_metadata->getCacheTags()) > 0;
}
}
@@ -0,0 +1,84 @@
<?php
namespace Drupal\entity\QueryAccess;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Generic query access handler for entity types that do not have one.
*
* This query access handler only fires the alter event so that modules can
* subscribe to the query access alter event to alter any entity query or views
* query without having to duplicate the related code from Entity API.
*/
final class EventOnlyQueryAccessHandler implements EntityHandlerInterface, QueryAccessHandlerInterface {
/**
* The entity type.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* The event dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Constructs a new EventOnlyQueryAccessHandler object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
* The event dispatcher.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(EntityTypeInterface $entity_type, EventDispatcherInterface $event_dispatcher, AccountInterface $current_user) {
$this->entityType = $entity_type;
$this->eventDispatcher = $event_dispatcher;
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('event_dispatcher'),
$container->get('current_user')
);
}
/**
* {@inheritdoc}
*/
public function getConditions($operation, AccountInterface $account = NULL) {
$account = $account ?: $this->currentUser;
$entity_type_id = $this->entityType->id();
$conditions = new ConditionGroup('OR');
// Allow other modules to modify the conditions before they are used.
$event = new QueryAccessEvent($conditions, $operation, $account, $entity_type_id);
$this->eventDispatcher->dispatch($event, 'entity.query_access');
$this->eventDispatcher->dispatch($event, "entity.query_access.{$entity_type_id}");
return $conditions;
}
}
@@ -0,0 +1,119 @@
<?php
namespace Drupal\entity\QueryAccess;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\EventDispatcher\Event;
/**
* Defines the query access event.
*
* Allows modules to modify access conditions before they're applied to a query.
*
* The event ID is both generic and dynamic:
* - entity.query_access
* - entity.query_access.$entity_type_id
*/
class QueryAccessEvent extends Event {
/**
* The conditions.
*
* @var \Drupal\entity\QueryAccess\ConditionGroup
*/
protected $conditions;
/**
* The operation.
*
* @var string
*/
protected $operation;
/**
* The user for which to restrict access.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $account;
/**
* The ID of entity type the query is for.
*
* @var string
*/
protected $entityTypeId;
/**
* Constructs a new QueryAccessEvent.
*
* @param \Drupal\entity\QueryAccess\ConditionGroup $conditions
* The conditions.
* @param string $operation
* The operation. Usually one of "view", "update", "duplicate", or "delete".
* @param \Drupal\Core\Session\AccountInterface $account
* The user for which to restrict access.
* @param string $entity_type_id
* The ID of entity type the query is for.
*/
public function __construct(ConditionGroup $conditions, $operation, AccountInterface $account, $entity_type_id = NULL) {
$this->conditions = $conditions;
$this->operation = $operation;
$this->account = $account;
if (!isset($entity_type_id)) {
@trigger_error('The $entity_type_id argument must be passed to QueryAccessEvent::__construct(), it is required before entity:2.0.0. See https://www.drupal.org/node/3134363.', E_USER_DEPRECATED);
}
else {
$this->entityTypeId = $entity_type_id;
}
}
/**
* Gets the conditions.
*
* If $conditions->isAlwaysFalse() is TRUE, the user doesn't have access to
* any entities, and the query is expected to return no results.
* This can be reversed by calling $conditions->alwaysFalse(FALSE).
*
* If $conditions->isAlwaysFalse() is FALSE, and the condition group is
* empty (count is 0), the user has full access, and the query doesn't
* need to be restricted.
*
* @return \Drupal\entity\QueryAccess\ConditionGroup
* The conditions.
*/
public function getConditions() {
return $this->conditions;
}
/**
* Gets the operation.
*
* @return string
* The operation. Usually one of "view", "update" or "delete".
*/
public function getOperation() {
return $this->operation;
}
/**
* Gets the user for which to restrict access.
*
* @return \Drupal\Core\Session\AccountInterface
* The user.
*/
public function getAccount() {
return $this->account;
}
/**
* Gets the the entity type ID.
*
* @return string
* The entity type ID.
*/
public function getEntityTypeId() {
return $this->entityTypeId;
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\entity\QueryAccess;
use Drupal\Core\Session\AccountInterface;
/**
* Controls query access based on the generic entity permissions.
*
* @see \Drupal\entity\EntityAccessControlHandler
* @see \Drupal\entity\EntityPermissionProvider
*/
class QueryAccessHandler extends QueryAccessHandlerBase {
/**
* {@inheritdoc}
*/
protected function buildEntityOwnerConditions($operation, AccountInterface $account) {
if ($operation == 'view') {
// EntityPermissionProvider doesn't provide own/any view permissions.
return $this->buildEntityConditions($operation, $account);
}
return parent::buildEntityOwnerConditions($operation, $account);
}
}
@@ -0,0 +1,281 @@
<?php
namespace Drupal\entity\QueryAccess;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\EntityOwnerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Provides common logic for query access handlers.
*
* @see \Drupal\entity\QueryAccess\QueryAccessHandler
* @see \Drupal\entity\QueryAccess\UncacheableQueryAccessHandler
*/
abstract class QueryAccessHandlerBase implements EntityHandlerInterface, QueryAccessHandlerInterface {
/**
* The entity type.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* The entity type bundle info.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* The event dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Constructs a new QueryAccessHandlerBase object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* The entity type bundle info.
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
* The event dispatcher.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(EntityTypeInterface $entity_type, EntityTypeBundleInfoInterface $bundle_info, EventDispatcherInterface $event_dispatcher, AccountInterface $current_user) {
$this->entityType = $entity_type;
$this->bundleInfo = $bundle_info;
$this->eventDispatcher = $event_dispatcher;
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('entity_type.bundle.info'),
$container->get('event_dispatcher'),
$container->get('current_user')
);
}
/**
* {@inheritdoc}
*/
public function getConditions($operation, AccountInterface $account = NULL) {
$account = $account ?: $this->currentUser;
$entity_type_id = $this->entityType->id();
$conditions = $this->buildConditions($operation, $account);
// Allow other modules to modify the conditions before they are used.
$event = new QueryAccessEvent($conditions, $operation, $account, $entity_type_id);
$this->eventDispatcher->dispatch($event, 'entity.query_access');
$this->eventDispatcher->dispatch($event, "entity.query_access.{$entity_type_id}");
return $conditions;
}
/**
* Builds the conditions for the given operation and user.
*
* @param string $operation
* The access operation. Usually one of "view", "update", "duplicate",
* or "delete".
* @param \Drupal\Core\Session\AccountInterface $account
* The user for which to restrict access.
*
* @return \Drupal\entity\QueryAccess\ConditionGroup
* The conditions.
*/
public function buildConditions($operation, AccountInterface $account) {
$entity_type_id = $this->entityType->id();
$has_owner = $this->entityType->entityClassImplements(EntityOwnerInterface::class);
$has_published = $this->entityType->entityClassImplements(EntityPublishedInterface::class);
// Guard against broken/incomplete entity type definitions.
if ($has_owner && !$this->entityType->hasKey('owner') && !$this->entityType->hasKey('uid')) {
throw new \RuntimeException(sprintf('The "%s" entity type did not define an "owner" or "uid" key.', $entity_type_id));
}
if ($has_published && !$this->entityType->hasKey('published')) {
throw new \RuntimeException(sprintf('The "%s" entity type did not define a "published" key', $entity_type_id));
}
$admin_permission = $this->entityType->getAdminPermission() ?: "administer {$entity_type_id}";
if ($account->hasPermission($admin_permission)) {
// The user has full access to all operations, no conditions needed.
$conditions = new ConditionGroup('OR');
$conditions->addCacheContexts(['user.permissions']);
return $conditions;
}
if ($has_owner) {
$entity_conditions = $this->buildEntityOwnerConditions($operation, $account);
}
else {
$entity_conditions = $this->buildEntityConditions($operation, $account);
}
$conditions = NULL;
if ($operation == 'view' && $has_published) {
$owner_key = $this->entityType->hasKey('owner') ? $this->entityType->getKey('owner') : $this->entityType->getKey('uid');
$published_key = $this->entityType->getKey('published');
$published_conditions = NULL;
$unpublished_conditions = NULL;
if ($entity_conditions) {
// Restrict the existing conditions to published entities only.
$published_conditions = new ConditionGroup('AND');
$published_conditions->addCacheContexts(['user.permissions']);
$published_conditions->addCondition($entity_conditions);
$published_conditions->addCondition($published_key, '1');
}
if ($has_owner && $account->hasPermission("view own unpublished $entity_type_id")) {
$unpublished_conditions = new ConditionGroup('AND');
$unpublished_conditions->addCacheContexts(['user']);
$unpublished_conditions->addCondition($owner_key, $account->id());
$unpublished_conditions->addCondition($published_key, '0');
}
if ($published_conditions && $unpublished_conditions) {
$conditions = new ConditionGroup('OR');
$conditions->addCondition($published_conditions);
$conditions->addCondition($unpublished_conditions);
}
elseif ($published_conditions) {
$conditions = $published_conditions;
}
elseif ($unpublished_conditions) {
$conditions = $unpublished_conditions;
}
}
else {
$conditions = $entity_conditions;
}
if (!$conditions) {
// The user doesn't have access to any entities.
// Falsify the query to ensure no results are returned.
$conditions = new ConditionGroup('OR');
$conditions->addCacheContexts(['user.permissions']);
$conditions->alwaysFalse();
}
return $conditions;
}
/**
* Builds the conditions for entities that have an owner.
*
* @param string $operation
* The access operation. Usually one of "view", "update", "duplicate",
* or "delete".
* @param \Drupal\Core\Session\AccountInterface $account
* The user for which to restrict access.
*
* @return \Drupal\entity\QueryAccess\ConditionGroup|null
* The conditions, or NULL if the user doesn't have access to any entity.
*/
protected function buildEntityOwnerConditions($operation, AccountInterface $account) {
$entity_type_id = $this->entityType->id();
$owner_key = $this->entityType->hasKey('owner') ? $this->entityType->getKey('owner') : $this->entityType->getKey('uid');
$bundle_key = $this->entityType->getKey('bundle');
$conditions = new ConditionGroup('OR');
$conditions->addCacheContexts(['user.permissions']);
// Any $entity_type permission.
if ($account->hasPermission("$operation any $entity_type_id")) {
// The user has full access, no conditions needed.
return $conditions;
}
// Own $entity_type permission.
if ($account->hasPermission("$operation own $entity_type_id")) {
$conditions->addCacheContexts(['user']);
$conditions->addCondition($owner_key, $account->id());
}
$bundles = array_keys($this->bundleInfo->getBundleInfo($entity_type_id));
$bundles_with_any_permission = [];
$bundles_with_own_permission = [];
foreach ($bundles as $bundle) {
if ($account->hasPermission("$operation any $bundle $entity_type_id")) {
$bundles_with_any_permission[] = $bundle;
}
if ($account->hasPermission("$operation own $bundle $entity_type_id")) {
$bundles_with_own_permission[] = $bundle;
}
}
// Any $bundle permission.
if ($bundles_with_any_permission) {
$conditions->addCondition($bundle_key, $bundles_with_any_permission);
}
// Own $bundle permission.
if ($bundles_with_own_permission) {
$conditions->addCacheContexts(['user']);
$conditions->addCondition((new ConditionGroup('AND'))
->addCondition($owner_key, $account->id())
->addCondition($bundle_key, $bundles_with_own_permission)
);
}
return $conditions->count() ? $conditions : NULL;
}
/**
* Builds the conditions for entities that do not have an owner.
*
* @param string $operation
* The access operation. Usually one of "view", "update", "duplicate",
* or "delete".
* @param \Drupal\Core\Session\AccountInterface $account
* The user for which to restrict access.
*
* @return \Drupal\entity\QueryAccess\ConditionGroup|null
* The conditions, or NULL if the user doesn't have access to any entity.
*/
protected function buildEntityConditions($operation, AccountInterface $account) {
$entity_type_id = $this->entityType->id();
$bundle_key = $this->entityType->getKey('bundle');
$conditions = new ConditionGroup('OR');
$conditions->addCacheContexts(['user.permissions']);
// The $entity_type permission.
if ($account->hasPermission("$operation $entity_type_id")) {
// The user has full access, no conditions needed.
return $conditions;
}
$bundles = array_keys($this->bundleInfo->getBundleInfo($entity_type_id));
$bundles_with_any_permission = [];
foreach ($bundles as $bundle) {
if ($account->hasPermission("$operation $bundle $entity_type_id")) {
$bundles_with_any_permission[] = $bundle;
}
}
// The $bundle permission.
if ($bundles_with_any_permission) {
$conditions->addCondition($bundle_key, $bundles_with_any_permission);
}
return $conditions->count() ? $conditions : NULL;
}
}
@@ -0,0 +1,42 @@
<?php
namespace Drupal\entity\QueryAccess;
use Drupal\Core\Session\AccountInterface;
/**
* Query access handlers control access to entities in queries.
*
* An entity defines a query access handler in its annotation:
* @code
* query_access = "\Drupal\entity\QueryAccess\QueryAccessHandler"
* @endcode
* The handler builds a set of conditions which are then applied to a query
* to filter it. For example, if the user #22 only has access to view
* their own entities, a uid = '22' condition will be built and applied.
*
* The following query types are supported:
* - Entity queries with the $entity_type_id . '_access' tag.
* - Views queries.
*/
interface QueryAccessHandlerInterface {
/**
* Gets the conditions for the given operation and user.
*
* The "entity.query_access.$entity_type_id" event is fired to allow
* modules to alter the conditions.
*
* @param string $operation
* The access operation. Usually one of "view", "update", "duplicate",
* or "delete".
* @param \Drupal\Core\Session\AccountInterface $account
* The user for which to restrict access, or NULL
* to assume the current user. Defaults to NULL.
*
* @return \Drupal\entity\QueryAccess\ConditionGroup
* The conditions.
*/
public function getConditions($operation, AccountInterface $account = NULL);
}
@@ -0,0 +1,11 @@
<?php
namespace Drupal\entity\QueryAccess;
/**
* Controls query access based on the uncacheable entity permissions.
*
* @see \Drupal\entity\UncacheableEntityAccessControlHandler
* @see \Drupal\entity\UncacheableEntityPermissionProvider
*/
class UncacheableQueryAccessHandler extends QueryAccessHandlerBase {}
@@ -0,0 +1,250 @@
<?php
namespace Drupal\entity\QueryAccess;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Database\Connection;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\Sql\DefaultTableMapping;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
use Drupal\Core\Render\RendererInterface;
use Drupal\views\Plugin\views\query\Sql;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Defines a class for altering views queries.
*
* @internal
*/
class ViewsQueryAlter implements ContainerInjectionInterface {
/**
* The database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* Constructs a new ViewsQueryAlter object.
*
* @param \Drupal\Core\Database\Connection $connection
* The database connection.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
* The request stack.
*/
public function __construct(Connection $connection, EntityFieldManagerInterface $entity_field_manager, EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer, RequestStack $request_stack) {
$this->connection = $connection;
$this->entityFieldManager = $entity_field_manager;
$this->entityTypeManager = $entity_type_manager;
$this->renderer = $renderer;
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('database'),
$container->get('entity_field.manager'),
$container->get('entity_type.manager'),
$container->get('renderer'),
$container->get('request_stack')
);
}
/**
* Alters the given views query.
*
* @param \Drupal\views\Plugin\views\query\Sql $query
* The views query.
* @param \Drupal\views\ViewExecutable $view
* The view.
*/
public function alter(Sql $query, ViewExecutable $view) {
$table_info = $query->getEntityTableInfo();
$base_table = reset($table_info);
if (empty($base_table['entity_type']) || $base_table['relationship_id'] != 'none') {
return;
}
$entity_type_id = $base_table['entity_type'];
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
if (!$entity_type->hasHandlerClass('query_access')) {
return;
}
$storage = $this->entityTypeManager->getStorage($entity_type_id);
if (!$storage instanceof SqlContentEntityStorage) {
return;
}
/** @var \Drupal\entity\QueryAccess\QueryAccessHandlerInterface $query_access */
$query_access = $this->entityTypeManager->getHandler($entity_type_id, 'query_access');
$conditions = $query_access->getConditions('view');
if ($conditions->isAlwaysFalse()) {
$query->addWhereExpression(0, '1 = 0');
}
elseif (count($conditions)) {
// Store the data table, in case mapConditions() needs to join it in.
$base_table['data_table'] = $entity_type->getDataTable();
$field_storage_definitions = $this->entityFieldManager->getFieldStorageDefinitions($entity_type_id);
/** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
$table_mapping = $storage->getTableMapping();
$sql_conditions = $this->mapConditions($conditions, $query, $base_table, $field_storage_definitions, $table_mapping);
$query->addWhere(0, $sql_conditions);
}
$this->applyCacheability(CacheableMetadata::createFromObject($conditions));
}
/**
* Maps an entity type's access conditions to views SQL conditions.
*
* @param \Drupal\entity\QueryAccess\ConditionGroup $conditions
* The access conditions.
* @param \Drupal\views\Plugin\views\query\Sql $query
* The views query.
* @param array $base_table
* The base table information.
* @param \Drupal\Core\Field\FieldStorageDefinitionInterface[] $field_storage_definitions
* The field storage definitions.
* @param \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping
* The table mapping.
*
* @return \Drupal\Core\Database\Query\ConditionInterface
* The SQL conditions.
*/
protected function mapConditions(ConditionGroup $conditions, Sql $query, array $base_table, array $field_storage_definitions, DefaultTableMapping $table_mapping) {
$sql_condition = $this->connection->condition($conditions->getConjunction());
foreach ($conditions->getConditions() as $condition) {
if ($condition instanceof ConditionGroup) {
$nested_sql_conditions = $this->mapConditions($condition, $query, $base_table, $field_storage_definitions, $table_mapping);
$sql_condition->condition($nested_sql_conditions);
}
else {
$field = $condition->getField();
$property_name = NULL;
if (strpos($field, '.') !== FALSE) {
list($field, $property_name) = explode('.', $field);
}
// Skip unknown fields.
if (!isset($field_storage_definitions[$field])) {
continue;
}
$field_storage_definition = $field_storage_definitions[$field];
if (!$property_name) {
$property_name = $field_storage_definition->getMainPropertyName();
}
$column = $table_mapping->getFieldColumnName($field_storage_definition, $property_name);
if ($table_mapping->requiresDedicatedTableStorage($field_storage_definitions[$field])) {
if ($base_table['revision']) {
$dedicated_table = $table_mapping->getDedicatedRevisionTableName($field_storage_definition);
}
else {
$dedicated_table = $table_mapping->getDedicatedDataTableName($field_storage_definition);
}
// Views defaults to LEFT JOIN. For simplicity, we don't try to
// use an INNER JOIN when it's safe to do so (AND conjunctions).
$alias = $query->ensureTable($dedicated_table);
}
elseif ($base_table['revision'] && !$field_storage_definition->isRevisionable()) {
// Workaround for #2652652, which causes $query->ensureTable()
// to not work in this case, due to a missing relationship.
if ($data_table = $query->getTableInfo($base_table['data_table'])) {
$alias = $data_table['alias'];
}
else {
$configuration = [
'type' => 'INNER',
'table' => $base_table['data_table'],
'field' => 'id',
'left_table' => $base_table['alias'],
'left_field' => 'id',
];
/** @var \Drupal\Views\Plugin\views\join\JoinPluginBase $join */
$join = Views::pluginManager('join')->createInstance('standard', $configuration);
$alias = $query->addRelationship($base_table['data_table'], $join, $data_table);
}
}
else {
$alias = $base_table['alias'];
}
$value = $condition->getValue();
$operator = $condition->getOperator();
// Using LIKE/NOT LIKE ensures a case insensitive comparison.
// @see \Drupal\Core\Entity\Query\Sql\Condition::translateCondition().
$property_definitions = $field_storage_definition->getPropertyDefinitions();
$case_sensitive = $property_definitions[$property_name]->getSetting('case_sensitive');
$operator_map = [
'=' => 'LIKE',
'<>' => 'NOT LIKE',
];
if ($case_sensitive === FALSE && isset($operator_map[$operator])) {
$operator = $operator_map[$operator];
$value = $this->connection->escapeLike($value);
}
$sql_condition->condition("$alias.$column", $value, $operator);
}
}
return $sql_condition;
}
/**
* Applies the cacheability metadata to the current request.
*
* @param \Drupal\Core\Cache\CacheableMetadata $cacheable_metadata
* The cacheability metadata.
*/
protected function applyCacheability(CacheableMetadata $cacheable_metadata) {
$request = $this->requestStack->getCurrentRequest();
if ($request->isMethodCacheable() && $this->renderer->hasRenderContext()) {
$build = [];
$cacheable_metadata->applyTo($build);
$this->renderer->render($build);
}
}
}
@@ -0,0 +1,25 @@
<?php
namespace Drupal\entity\Revision;
use Drupal\Core\Entity\RevisionableContentEntityBase as BaseRevisionableContentEntityBase;
/**
* Improves the url route handling of core's revisionable content entity base.
*/
abstract class RevisionableContentEntityBase extends BaseRevisionableContentEntityBase {
/**
* {@inheritdoc}
*/
protected function urlRouteParameters($rel) {
$uri_route_parameters = parent::urlRouteParameters($rel);
if (strpos($this->getEntityType()->getLinkTemplate($rel), $this->getEntityTypeId() . '_revision') !== FALSE) {
$uri_route_parameters[$this->getEntityTypeId() . '_revision'] = $this->getRevisionId();
}
return $uri_route_parameters;
}
}
@@ -0,0 +1,39 @@
<?php
namespace Drupal\entity\Routing;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Provides HTML routes for entities with administrative add/edit/delete pages.
*
* Use this class if the add/edit/delete form routes should use the
* administrative theme.
*/
class AdminHtmlRouteProvider extends DefaultHtmlRouteProvider {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = parent::getRoutes($entity_type);
$entity_type_id = $entity_type->id();
$admin_route_names = [
"entity.{$entity_type_id}.add_page",
"entity.{$entity_type_id}.add_form",
"entity.{$entity_type_id}.edit_form",
"entity.{$entity_type_id}.delete_form",
"entity.{$entity_type_id}.delete_multiple_form",
"entity.{$entity_type_id}.duplicate_form",
];
foreach ($admin_route_names as $admin_route_name) {
if ($route = $collection->get($admin_route_name)) {
$route->setOption('_admin_route', TRUE);
}
}
return $collection;
}
}
@@ -0,0 +1,75 @@
<?php
namespace Drupal\entity\Routing;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider as CoreDefaultHtmlRouteProvider;
use Drupal\entity\Controller\EntityDuplicateController;
use Symfony\Component\Routing\Route;
/**
* Provides HTML routes for entities.
*/
class DefaultHtmlRouteProvider extends CoreDefaultHtmlRouteProvider {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = parent::getRoutes($entity_type);
$entity_type_id = $entity_type->id();
if ($duplicate_route = $this->getDuplicateFormRoute($entity_type)) {
$collection->add("entity.{$entity_type_id}.duplicate_form", $duplicate_route);
}
return $collection;
}
/**
* {@inheritdoc}
*/
protected function getCollectionRoute(EntityTypeInterface $entity_type) {
$route = parent::getCollectionRoute($entity_type);
if ($route && $entity_type->hasHandlerClass('permission_provider')) {
$admin_permission = $entity_type->getAdminPermission();
$overview_permission = "access {$entity_type->id()} overview";
$route->setRequirement('_permission', "$admin_permission+$overview_permission");
}
return $route;
}
/**
* Gets the duplicate-form route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getDuplicateFormRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('duplicate-form')) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('duplicate-form'));
$route
->setDefaults([
'_controller' => EntityDuplicateController::class . '::form',
'_title_callback' => EntityDuplicateController::class . '::title',
'entity_type_id' => $entity_type_id,
])
->setRequirement('_entity_access', "{$entity_type_id}.duplicate")
->setOption('parameters', [
$entity_type_id => ['type' => 'entity:' . $entity_type_id],
]);
// Entity types with serial IDs can specify this in their route
// requirements, improving the matching process.
if ($this->getEntityTypeIdKeyType($entity_type) === 'integer') {
$route->setRequirement($entity_type_id, '\d+');
}
return $route;
}
}
}
@@ -0,0 +1,54 @@
<?php
namespace Drupal\entity\Routing;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\EntityRouteProviderInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Provides the HTML route for deleting multiple entities.
*
* @deprecated Since Drupal 8.6.x the core DefaultHtmlRouteProvider provides
* the route for any entity type with a "delete-multiple-form" link template
* and a "delete-multiple-confirm" form.
*/
class DeleteMultipleRouteProvider implements EntityRouteProviderInterface {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$routes = new RouteCollection();
if ($route = $this->deleteMultipleFormRoute($entity_type)) {
$routes->add('entity.' . $entity_type->id() . '.delete_multiple_form', $route);
}
return $routes;
}
/**
* Returns the delete multiple form route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function deleteMultipleFormRoute(EntityTypeInterface $entity_type) {
// Core requires a "delete-multiple-confirm" form to be declared as well,
// if it's missing, it's safe to assume that the entity type is still
// relying on previous Entity API contrib behavior.
if ($entity_type->hasLinkTemplate('delete-multiple-form') && !$entity_type->hasHandlerClass('form', 'delete-multiple-confirm')) {
$route = new Route($entity_type->getLinkTemplate('delete-multiple-form'));
$route->setDefault('_form', '\Drupal\entity\Form\DeleteMultipleForm');
$route->setDefault('entity_type_id', $entity_type->id());
$route->setRequirement('_entity_delete_multiple_access', $entity_type->id());
return $route;
}
}
}
@@ -0,0 +1,127 @@
<?php
namespace Drupal\entity\Routing;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\EntityRouteProviderInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Provides revision routes.
*/
class RevisionRouteProvider implements EntityRouteProviderInterface {
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = new RouteCollection();
$entity_type_id = $entity_type->id();
if ($view_route = $this->getRevisionViewRoute($entity_type)) {
$collection->add("entity.$entity_type_id.revision", $view_route);
}
if ($view_route = $this->getRevisionRevertRoute($entity_type)) {
$collection->add("entity.$entity_type_id.revision_revert_form", $view_route);
}
if ($view_route = $this->getRevisionHistoryRoute($entity_type)) {
$collection->add("entity.$entity_type_id.version_history", $view_route);
}
return $collection;
}
/**
* Gets the entity revision view route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getRevisionViewRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('revision')) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('revision'));
$route->addDefaults([
'_controller' => '\Drupal\Core\Entity\Controller\EntityRevisionViewController',
'_title_callback' => '\Drupal\Core\Entity\Controller\EntityRevisionViewController::title',
]);
$route->addRequirements([
'_entity_access_revision' => "$entity_type_id.view",
]);
$route->setOption('parameters', [
$entity_type->id() => [
'type' => 'entity:' . $entity_type->id(),
],
$entity_type->id() . '_revision' => [
'type' => 'entity_revision:' . $entity_type->id(),
],
]);
return $route;
}
}
/**
* Gets the entity revision revert route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getRevisionRevertRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('revision-revert-form')) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('revision-revert-form'));
$route->addDefaults([
'_form' => '\Drupal\entity\Form\RevisionRevertForm',
'title' => 'Revert to earlier revision',
]);
$route->addRequirements([
'_entity_access_revision' => "$entity_type_id.update",
]);
$route->setOption('parameters', [
$entity_type->id() => [
'type' => 'entity:' . $entity_type->id(),
],
$entity_type->id() . '_revision' => [
'type' => 'entity_revision:' . $entity_type->id(),
],
]);
return $route;
}
}
/**
* Gets the entity revision version history route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getRevisionHistoryRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('version-history')) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('version-history'));
$route->addDefaults([
'_controller' => '\Drupal\entity\Controller\RevisionOverviewController::revisionOverviewController',
'_title' => 'Revisions',
]);
$route->setRequirement('_entity_access_revision', "$entity_type_id.list");
$route->setOption('entity_type_id', $entity_type->id());
$route->setOption('parameters', [
$entity_type->id() => [
'type' => 'entity:' . $entity_type->id(),
],
]);
return $route;
}
}
}
@@ -0,0 +1,54 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Controls access based on the uncacheable entity permissions.
*
* @see \Drupal\entity\UncacheableEntityPermissionProvider
*
* Note: this access control handler will cause pages to be cached per user.
*/
class UncacheableEntityAccessControlHandler extends EntityAccessControlHandlerBase {
/**
* {@inheritdoc}
*/
public function __construct(EntityTypeInterface $entity_type) {
parent::__construct($entity_type);
if (!$entity_type->hasHandlerClass('permission_provider') || !is_a($entity_type->getHandlerClass('permission_provider'), UncacheableEntityPermissionProvider::class, TRUE)) {
throw new \Exception('\Drupal\entity\UncacheableEntityAccessControlHandler requires the \Drupal\entity\UncacheableEntityPermissionProvider permission provider.');
}
}
/**
* {@inheritdoc}
*/
protected function checkEntityOwnerPermissions(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\user\EntityOwnerInterface $entity */
if ($operation === 'view' && $entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
if ($account->id() != $entity->getOwnerId()) {
// There's no permission for viewing other user's unpublished entity.
return AccessResult::neutral()->cachePerUser();
}
$permissions = [
"view own unpublished {$entity->getEntityTypeId()}",
];
$result = AccessResult::allowedIfHasPermissions($account, $permissions)->cachePerUser();
}
else {
$result = parent::checkEntityOwnerPermissions($entity, $operation, $account);
}
return $result;
}
}
@@ -0,0 +1,148 @@
<?php
namespace Drupal\entity;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides generic entity permissions which are cached per user.
*
* Intended for content entity types, since config entity types usually rely
* on a single "administer" permission.
*
* Provided permissions:
* - The declared "admin_permission" of the entity type (or
* "administer $entity_type" if the entity type does not declare an
* administrative permission)
* - access $entity_type overview
* - view own unpublished $entity_type
* - view (own|any) ($bundle) $entity_type
* - update (own|any) ($bundle) $entity_type
* - duplicate (own|any) ($bundle) $entity_type
* - delete (own|any) ($bundle) $entity_type
* - create $bundle $entity_type
*
* Important:
* Provides "view own ($bundle) $entity_type" permissions, which require
* caching pages per user. This can significantly increase the size of caches,
* impacting site performance. Use \Drupal\entity\EntityPermissionProvider
* if those permissions are not necessary.
*
* Example annotation:
* @code
* handlers = {
* "access" = "Drupal\entity\UncacheableEntityAccessControlHandler",
* "permission_provider" = "Drupal\entity\UncacheableEntityPermissionProvider",
* }
* @endcode
*
* @see \Drupal\entity\EntityAccessControlHandler
* @see \Drupal\entity\EntityPermissions
*/
class UncacheableEntityPermissionProvider extends EntityPermissionProviderBase {
/**
* Builds permissions for the entity_type granularity.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array
* The permissions.
*/
protected function buildEntityTypePermissions(EntityTypeInterface $entity_type) {
$permissions = parent::buildEntityTypePermissions($entity_type);
$entity_type_id = $entity_type->id();
$has_owner = $entity_type->entityClassImplements(EntityOwnerInterface::class);
$plural_label = $entity_type->getPluralLabel();
if ($has_owner) {
$permissions["view any {$entity_type_id}"] = [
'title' => $this->t('View any @type', [
'@type' => $plural_label,
]),
];
$permissions["view own {$entity_type_id}"] = [
'title' => $this->t('View own @type', [
'@type' => $plural_label,
]),
];
}
else {
$permissions["view {$entity_type_id}"] = [
'title' => $this->t('View @type', [
'@type' => $plural_label,
]),
];
}
return $permissions;
}
/**
* Builds permissions for the bundle granularity.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return array
* The permissions.
*/
protected function buildBundlePermissions(EntityTypeInterface $entity_type) {
$permissions = parent::buildBundlePermissions($entity_type);
$entity_type_id = $entity_type->id();
$bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
$has_owner = $entity_type->entityClassImplements(EntityOwnerInterface::class);
$plural_label = $entity_type->getPluralLabel();
if ($has_owner) {
$permissions["view any {$entity_type_id}"] = [
'title' => $this->t('View any @type', [
'@type' => $plural_label,
]),
];
$permissions["view own {$entity_type_id}"] = [
'title' => $this->t('View own @type', [
'@type' => $plural_label,
]),
];
}
else {
$permissions["view {$entity_type_id}"] = [
'title' => $this->t('View @type', [
'@type' => $plural_label,
]),
];
}
foreach ($bundles as $bundle_name => $bundle_info) {
if ($has_owner) {
$permissions["view any {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: View any @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
$permissions["view own {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: View own @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
}
else {
$permissions["view {$bundle_name} {$entity_type_id}"] = [
'title' => $this->t('@bundle: View @type', [
'@bundle' => $bundle_info['label'],
'@type' => $plural_label,
]),
];
}
}
return $permissions;
}
}
@@ -0,0 +1,11 @@
name: 'Entity bundle plugin examples test'
type: module
description: 'Module for testing bundle plugins.'
package: Testing
dependencies:
- entity:entity
# Information added by Drupal.org packaging script on 2024-08-11
version: '8.x-1.5'
project: 'entity'
datestamp: 1723380065
@@ -0,0 +1,31 @@
<?php
namespace Drupal\entity_module_bundle_plugin_examples_test\Plugin\BundlePluginTest;
use Drupal\entity\BundleFieldDefinition;
use Drupal\Core\Plugin\PluginBase;
use Drupal\entity_module_bundle_plugin_test\Plugin\BundlePluginTest\BundlePluginTestInterface;
/**
* Provides the second bundle plugin.
*
* @BundlePluginTest(
* id = "second",
* label = @Translation("Second"),
* )
*/
class Second extends PluginBase implements BundlePluginTestInterface {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = [];
$fields['second_mail'] = BundleFieldDefinition::create('email')
->setLabel($this->t('Email'))
->setRequired(TRUE);
return $fields;
}
}
@@ -0,0 +1,11 @@
name: 'Entity bundle plugin test'
type: module
description: 'Module for testing bundle plugins.'
package: Testing
dependencies:
- entity:entity
# Information added by Drupal.org packaging script on 2024-08-11
version: '8.x-1.5'
project: 'entity'
datestamp: 1723380065
@@ -0,0 +1,4 @@
services:
plugin.manager.bundle_plugin_test:
class: Drupal\entity_module_bundle_plugin_test\BundlePluginTestManager
parent: default_plugin_manager
@@ -0,0 +1,34 @@
<?php
namespace Drupal\entity_module_bundle_plugin_test\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines the BundlePluginTest annotation object.
*
* Plugin namespace: Plugin\BundlePluginTest.
*
* @see plugin_api
*
* @Annotation
*/
class BundlePluginTest extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The plugin label.
*
* @ingroup plugin_translatable
*
* @var \Drupal\Core\Annotation\Translation
*/
public $label;
}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\entity_module_bundle_plugin_test;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
/**
* Manages discovery and instantiation of BundlePluginTest plugins.
*
* @see \Drupal\entity_module_bundle_plugin_test\Annotation\BundlePluginTest
* @see plugin_api
*/
class BundlePluginTestManager extends DefaultPluginManager {
/**
* Constructs a new BundlePluginTestManager object.
*
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* The cache backend.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
parent::__construct('Plugin/BundlePluginTest', $namespaces, $module_handler, 'Drupal\entity_module_bundle_plugin_test\Plugin\BundlePluginTest\BundlePluginTestInterface', 'Drupal\entity_module_bundle_plugin_test\Annotation\BundlePluginTest');
$this->alterInfo('bundle_plugin_test_info');
$this->setCacheBackend($cache_backend, 'bundle_plugin_test_plugins');
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\entity_module_bundle_plugin_test\Entity;
use Drupal\Core\Entity\ContentEntityBase;
/**
* Defines the 'entity_test_bundle_plugin' entity class.
*
* @ContentEntityType(
* id = "entity_test_bundle_plugin",
* label = @Translation("Entity test bundle plugin"),
* bundle_label = @Translation("Bundle Plugin Test"),
* bundle_plugin_type = "bundle_plugin_test",
* base_table = "entity_test_bundle_plugin",
* admin_permission = "administer content",
* fieldable = TRUE,
* entity_keys = {
* "id" = "method_id",
* "uuid" = "uuid",
* "bundle" = "type"
* },
* )
*/
class EntityTestBundlePlugin extends ContentEntityBase {
}
@@ -0,0 +1,12 @@
<?php
namespace Drupal\entity_module_bundle_plugin_test\Plugin\BundlePluginTest;
use Drupal\entity\BundlePlugin\BundlePluginInterface;
/**
* Defines the interface for BundlePluginTest plugins.
*/
interface BundlePluginTestInterface extends BundlePluginInterface {
}
@@ -0,0 +1,31 @@
<?php
namespace Drupal\entity_module_bundle_plugin_test\Plugin\BundlePluginTest;
use Drupal\entity\BundleFieldDefinition;
use Drupal\Core\Plugin\PluginBase;
/**
* Provides the first bundle plugin.
*
* @BundlePluginTest(
* id = "first",
* label = @Translation("First"),
* description = @Translation("Some description"),
* )
*/
class First extends PluginBase implements BundlePluginTestInterface {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = [];
$fields['first_mail'] = BundleFieldDefinition::create('email')
->setLabel($this->t('Email'))
->setRequired(TRUE);
return $fields;
}
}
@@ -0,0 +1,17 @@
langcode: en
status: true
dependencies:
config:
- field.storage.entity_test_enhanced.assigned
id: entity_test_enhanced.first.assigned
field_name: assigned
entity_type: entity_test_enhanced
bundle: first
label: Assigned
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string
@@ -0,0 +1,17 @@
langcode: en
status: true
dependencies:
config:
- field.storage.entity_test_enhanced.assigned
id: entity_test_enhanced.second.assigned
field_name: assigned
entity_type: entity_test_enhanced
bundle: second
label: Assigned
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string
@@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
module:
- entity_module_test
id: entity_test_enhanced.assigned
field_name: assigned
entity_type: entity_test_enhanced
type: string
settings:
max_length: 255
is_ascii: false
case_sensitive: true
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
module:
- entity_module_test
id: entity_test_enhanced_with_owner_delete_action
label: 'Delete enhanced entities with owner'
type: entity_test_enhanced_with_owner
plugin: entity:delete_action:entity_test_enhanced_with_owner
configuration: { }
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
module:
- entity_module_test
id: entity_test_enhanced_with_owner_publish_action
label: 'Publish enhanced entities with owner'
type: entity_test_enhanced_with_owner
plugin: entity:publish_action:entity_test_enhanced_with_owner
configuration: { }
@@ -0,0 +1,10 @@
langcode: en
status: true
dependencies:
module:
- entity_module_test
id: entity_test_enhanced_with_owner_unpublish_action
label: 'Unpublish enhanced entities with owner'
type: entity_test_enhanced_with_owner
plugin: entity:unpublish_action:entity_test_enhanced_with_owner
configuration: { }
@@ -0,0 +1,170 @@
langcode: en
status: true
dependencies:
module:
- entity_module_test
id: entity_test_enhanced
label: 'Enhanced entities'
module: views
description: ''
tag: ''
base_table: entity_test_enhanced_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: default
options:
grouping: { }
row_class: ''
default_row_class: true
uses_fields: false
row:
type: fields
options:
inline: { }
separator: ''
hide_empty: false
default_field_elements: true
fields:
name:
table: entity_test_enhanced_field_data
field: name
id: name
entity_type: null
entity_field: name
plugin_id: field
relationship: none
group_type: group
admin_label: ''
label: ''
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
filters: { }
sorts:
id:
id: id
table: entity_test_enhanced_field_data
field: id
relationship: none
group_type: group
admin_label: ''
order: ASC
exposed: false
expose:
label: ''
entity_type: entity_test_enhanced
entity_field: id
plugin_id: standard
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
tags: { }
@@ -0,0 +1,170 @@
langcode: en
status: true
dependencies:
module:
- entity_module_test
id: entity_test_enhanced_revisions
label: 'Enhanced entities (Revisions)'
module: views
description: ''
tag: ''
base_table: entity_test_enhanced_field_revision
base_field: nid
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: default
options:
grouping: { }
row_class: ''
default_row_class: true
uses_fields: false
row:
type: fields
options:
inline: { }
separator: ''
hide_empty: false
default_field_elements: true
fields:
name:
table: entity_test_enhanced_field_revision
field: name
id: name
entity_type: null
entity_field: name
plugin_id: field
relationship: none
group_type: group
admin_label: ''
label: ''
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
filters: { }
sorts:
vid:
id: vid
table: entity_test_enhanced_field_revision
field: vid
relationship: none
group_type: group
admin_label: ''
order: ASC
exposed: false
expose:
label: ''
entity_type: entity_test_enhanced
entity_field: vid
plugin_id: standard
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
tags: { }
@@ -0,0 +1,170 @@
langcode: en
status: true
dependencies:
module:
- entity_module_test
id: entity_test_enhanced_with_owner
label: 'Enhanced entities with an owner'
module: views
description: ''
tag: ''
base_table: entity_test_enhanced_with_owner_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: default
options:
grouping: { }
row_class: ''
default_row_class: true
uses_fields: false
row:
type: fields
options:
inline: { }
separator: ''
hide_empty: false
default_field_elements: true
fields:
name:
table: entity_test_enhanced_with_owner_field_data
field: name
id: name
entity_type: null
entity_field: name
plugin_id: field
relationship: none
group_type: group
admin_label: ''
label: ''
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
filters: { }
sorts:
id:
id: id
table: entity_test_enhanced_with_owner_field_data
field: id
relationship: none
group_type: group
admin_label: ''
order: ASC
exposed: false
expose:
label: ''
entity_type: entity_test_enhanced_with_owner
entity_field: id
plugin_id: standard
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
tags: { }
@@ -0,0 +1,170 @@
langcode: en
status: true
dependencies:
module:
- entity_module_test
id: entity_test_enhanced_with_owner_revisions
label: 'Enhanced entities with an owner (Revisions)'
module: views
description: ''
tag: ''
base_table: entity_test_enhanced_with_owner_field_revision
base_field: nid
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: default
options:
grouping: { }
row_class: ''
default_row_class: true
uses_fields: false
row:
type: fields
options:
inline: { }
separator: ''
hide_empty: false
default_field_elements: true
fields:
name:
table: entity_test_enhanced_with_owner_field_revision
field: name
id: name
entity_type: null
entity_field: name
plugin_id: field
relationship: none
group_type: group
admin_label: ''
label: ''
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
filters: { }
sorts:
vid:
id: vid
table: entity_test_enhanced_with_owner_field_revision
field: vid
relationship: none
group_type: group
admin_label: ''
order: ASC
exposed: false
expose:
label: ''
entity_type: entity_test_enhanced_with_owner
entity_field: vid
plugin_id: standard
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
tags: { }
@@ -0,0 +1,10 @@
name: Entity test
type: module
package: Testing
dependencies:
- drupal:field
# Information added by Drupal.org packaging script on 2024-08-11
version: '8.x-1.5'
project: 'entity'
datestamp: 1723380065
@@ -0,0 +1,15 @@
<?php
/**
* Implements hook_entity_bundle_info().
*/
function entity_module_test_entity_bundle_info() {
$bundles['entity_test_enhanced']['default']['label'] = t('Default');
$bundles['entity_test_enhanced']['first']['label'] = t('First');
$bundles['entity_test_enhanced']['second']['label'] = t('Second');
$bundles['entity_test_enhanced_with_owner']['default']['label'] = t('Default');
$bundles['entity_test_enhanced_with_owner']['first']['label'] = t('First');
$bundles['entity_test_enhanced_with_owner']['second']['label'] = t('Second');
return $bundles;
}
@@ -0,0 +1,6 @@
'view all entity_test_enhanced revisions':
title: 'View all entity_test_enhanced revisions'
'restrict access': TRUE
'revert all entity_test_enhanced revisions':
title: 'Revert all entity_test_enhanced revisions'
'restrict access': TRUE
@@ -0,0 +1,5 @@
services:
entity_module_test.query_access_subscriber:
class: Drupal\entity_module_test\EventSubscriber\QueryAccessSubscriber
tags:
- { name: event_subscriber }
@@ -0,0 +1,120 @@
<?php
namespace Drupal\entity_module_test\Entity;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\entity\Revision\RevisionableContentEntityBase;
/**
* Provides a test entity which uses all the capabilities of entity module.
*
* @ContentEntityType(
* id = "entity_test_enhanced",
* label = @Translation("Enhanced entity"),
* label_collection = @Translation("Enhanced entities"),
* label_singular = @Translation("enhanced entity"),
* label_plural = @Translation("enhanced entities"),
* label_count = @PluralTranslation(
* singular = "@count enhanced entity",
* plural = "@count enhanced entities",
* ),
* handlers = {
* "storage" = "\Drupal\Core\Entity\Sql\SqlContentEntityStorage",
* "access" = "\Drupal\entity\EntityAccessControlHandler",
* "query_access" = "\Drupal\entity\QueryAccess\QueryAccessHandler",
* "permission_provider" = "\Drupal\entity\EntityPermissionProvider",
* "form" = {
* "add" = "\Drupal\entity_module_test\Form\EnhancedEntityForm",
* "edit" = "\Drupal\entity_module_test\Form\EnhancedEntityForm",
* "duplicate" = "\Drupal\entity_module_test\Form\EnhancedEntityForm",
* "delete" = "\Drupal\Core\Entity\EntityDeleteForm",
* },
* "route_provider" = {
* "html" = "\Drupal\entity\Routing\DefaultHtmlRouteProvider",
* "revision" = "\Drupal\entity\Routing\RevisionRouteProvider",
* "delete-multiple" = "\Drupal\entity\Routing\DeleteMultipleRouteProvider",
* },
* "local_action_provider" = {
* "collection" = "\Drupal\entity\Menu\EntityCollectionLocalActionProvider",
* },
* "local_task_provider" = {
* "default" = "\Drupal\entity\Menu\DefaultEntityLocalTaskProvider",
* },
* "list_builder" = "\Drupal\Core\Entity\EntityListBuilder",
* "views_data" = "\Drupal\entity\EntityViewsData",
* },
* base_table = "entity_test_enhanced",
* data_table = "entity_test_enhanced_field_data",
* revision_table = "entity_test_enhanced_revision",
* revision_data_table = "entity_test_enhanced_field_revision",
* translatable = TRUE,
* revisionable = TRUE,
* admin_permission = "administer entity_test_enhanced",
* permission_granularity = "bundle",
* entity_keys = {
* "id" = "id",
* "bundle" = "type",
* "revision" = "vid",
* "langcode" = "langcode",
* "label" = "name",
* "published" = "status",
* },
* revision_metadata_keys = {
* "revision_user" = "revision_user",
* "revision_created" = "revision_created",
* "revision_log_message" = "revision_log_message"
* },
* links = {
* "add-page" = "/entity_test_enhanced/add",
* "add-form" = "/entity_test_enhanced/add/{type}",
* "edit-form" = "/entity_test_enhanced/{entity_test_enhanced}/edit",
* "duplicate-form" = "/entity_test_enhanced/{entity_test_enhanced}/duplicate",
* "canonical" = "/entity_test_enhanced/{entity_test_enhanced}",
* "collection" = "/entity_test_enhanced",
* "delete-form" = "/entity_test_enhanced/{entity_test_enhanced}/delete",
* "delete-multiple-form" = "/entity_test_enhanced/delete",
* "revision" = "/entity_test_enhanced/{entity_test_enhanced}/revisions/{entity_test_enhanced_revision}/view",
* "revision-revert-form" = "/entity_test_enhanced/{entity_test_enhanced}/revisions/{entity_test_enhanced_revision}/revert",
* "version-history" = "/entity_test_enhanced/{entity_test_enhanced}/revisions",
* },
* )
*/
class EnhancedEntity extends RevisionableContentEntityBase implements EntityPublishedInterface {
use EntityPublishedTrait;
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields += static::publishedBaseFieldDefinitions($entity_type);
$fields['name'] = BaseFieldDefinition::create('string')
->setLabel('Name')
->setRevisionable(TRUE)
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => 0,
])
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => -5,
]);
// Add a computed entity reference field for testing.
$fields['computed_entity_ref'] = BaseFieldDefinition::create('entity_reference')
->setLabel('Test entity reference')
->setSetting('target_type', 'entity_test_enhanced')
->setCardinality(1)
->setComputed(TRUE)
->setClass('Drupal\entity_module_test\Field\ComputedEntityRefItemList');
return $fields;
}
}
@@ -0,0 +1,118 @@
<?php
namespace Drupal\entity_module_test\Entity;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\entity\Revision\RevisionableContentEntityBase;
use Drupal\user\EntityOwnerInterface;
use Drupal\user\EntityOwnerTrait;
/**
* Provides a test entity which uses all the capabilities of entity module.
*
* @ContentEntityType(
* id = "entity_test_enhanced_with_owner",
* label = @Translation("Enhanced entity with owner"),
* label_collection = @Translation("Enhanced entities with owner"),
* label_singular = @Translation("enhanced entity with owner"),
* label_plural = @Translation("enhanced entities with owner"),
* label_count = @PluralTranslation(
* singular = "@count enhanced entity with owner",
* plural = "@count enhanced entities with owner",
* ),
* handlers = {
* "storage" = "\Drupal\Core\Entity\Sql\SqlContentEntityStorage",
* "access" = "\Drupal\entity\UncacheableEntityAccessControlHandler",
* "query_access" = "\Drupal\entity\QueryAccess\UncacheableQueryAccessHandler",
* "permission_provider" = "\Drupal\entity\UncacheableEntityPermissionProvider",
* "form" = {
* "add" = "\Drupal\Core\Entity\ContentEntityForm",
* "edit" = "\Drupal\Core\Entity\ContentEntityForm",
* "delete" = "\Drupal\Core\Entity\EntityDeleteForm",
* },
* "route_provider" = {
* "html" = "\Drupal\entity\Routing\DefaultHtmlRouteProvider",
* "revision" = "\Drupal\entity\Routing\RevisionRouteProvider",
* "delete-multiple" = "\Drupal\entity\Routing\DeleteMultipleRouteProvider",
* },
* "local_action_provider" = {
* "collection" = "\Drupal\entity\Menu\EntityCollectionLocalActionProvider",
* },
* "list_builder" = "\Drupal\entity\BulkFormEntityListBuilder",
* "views_data" = "\Drupal\entity\EntityViewsData",
* },
* base_table = "entity_test_enhanced_with_owner",
* data_table = "entity_test_enhanced_with_owner_field_data",
* revision_table = "entity_test_enhanced_with_owner_revision",
* revision_data_table = "entity_test_enhanced_with_owner_field_revision",
* translatable = TRUE,
* revisionable = TRUE,
* admin_permission = "administer entity_test_enhanced_with_owner",
* permission_granularity = "bundle",
* entity_keys = {
* "id" = "id",
* "bundle" = "type",
* "revision" = "vid",
* "langcode" = "langcode",
* "label" = "name",
* "owner" = "user_id",
* "published" = "status",
* },
* revision_metadata_keys = {
* "revision_user" = "revision_user",
* "revision_created" = "revision_created",
* "revision_log_message" = "revision_log_message"
* },
* links = {
* "add-page" = "/entity_test_enhanced_with_owner/add",
* "add-form" = "/entity_test_enhanced_with_owner/add/{type}",
* "edit-form" = "/entity_test_enhanced_with_owner/{entity_test_enhanced_with_owner}/edit",
* "duplicate-form" = "/entity_test_enhanced/{entity_test_enhanced}/duplicate",
* "canonical" = "/entity_test_enhanced_with_owner/{entity_test_enhanced_with_owner}",
* "collection" = "/entity_test_enhanced_with_owner",
* "delete-multiple-form" = "/entity_test_enhanced_with_owner/delete",
* },
* )
*/
class EnhancedEntityWithOwner extends RevisionableContentEntityBase implements EntityOwnerInterface, EntityPublishedInterface {
use EntityOwnerTrait, EntityPublishedTrait;
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields += static::ownerBaseFieldDefinitions($entity_type);
$fields += static::publishedBaseFieldDefinitions($entity_type);
$fields['name'] = BaseFieldDefinition::create('string')
->setLabel('Name')
->setRevisionable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => -5,
]);
$fields['user_id']
// Default EntityTest entities to have the root user as the owner, to
// simplify testing.
->setDefaultValue([0 => ['target_id' => 1]])
->setDisplayOptions('form', [
'type' => 'entity_reference_autocomplete',
'weight' => -1,
'settings' => [
'match_operator' => 'CONTAINS',
'size' => '60',
'placeholder' => '',
],
]);
return $fields;
}
}
@@ -0,0 +1,108 @@
<?php
namespace Drupal\entity_module_test\EventSubscriber;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\entity\QueryAccess\ConditionGroup;
use Drupal\entity\QueryAccess\QueryAccessEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class QueryAccessSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
'entity.query_access' => 'onGenericQueryAccess',
'entity.query_access.entity_test_enhanced' => 'onQueryAccess',
'entity.query_access.node' => 'onEventOnlyQueryAccess',
];
}
/**
* Modifies the access conditions based on the entity type.
*
* This is just a convenient example for testing the catch-all event. A real
* subscriber would probably extend the conditions based on the third party
* settings it set on the entity type(s).
*
* @param \Drupal\entity\QueryAccess\QueryAccessEvent $event
* The event.
*/
public function onGenericQueryAccess(QueryAccessEvent $event) {
$conditions = $event->getConditions();
$email = $event->getAccount()->getEmail();
if ($event->getEntityTypeId() == 'entity_test_enhanced_with_owner') {
// Disallow access to entity_test_enhanced_with_owner for the user with
// email address [email protected]. Anyone else has access.
if ($email == '[email protected]') {
$conditions->alwaysFalse();
}
elseif ($email == '[email protected]') {
$conditions->alwaysFalse(FALSE);
}
}
}
/**
* Modifies the access conditions based on the current user.
*
* This is just a convenient example for testing. A real subscriber would
* ignore the account and extend the conditions to cover additional factors,
* such as a custom entity field.
*
* @param \Drupal\entity\QueryAccess\QueryAccessEvent $event
* The event.
*/
public function onQueryAccess(QueryAccessEvent $event) {
$conditions = $event->getConditions();
$email = $event->getAccount()->getEmail();
if ($email == '[email protected]') {
// This user should not have access to any entities.
$conditions->alwaysFalse();
}
elseif ($email == '[email protected]') {
// This user should have access to entities with the IDs 1, 2, and 3.
// The query access handler might have already set ->alwaysFalse()
// due to the user not having any other access, so we make sure
// to undo it with $conditions->alwaysFalse(TRUE).
$conditions->alwaysFalse(FALSE);
$conditions->addCondition('id', ['1', '2', '3']);
}
elseif ($email == '[email protected]') {
// This user should only have access to entities assigned to "marketing",
// or unassigned entities.
$conditions->alwaysFalse(FALSE);
$conditions->addCondition((new ConditionGroup('OR'))
->addCondition('assigned', NULL, 'IS NULL')
// Confirm that explicitly specifying the property name works.
->addCondition('assigned.value', 'marketing')
);
}
}
/**
* Modifies the access conditions based on the node type.
*
* This is just a convenient example for testing whether the event-only query
* access subscriber is added to entity types that do not specify a query
* access handler; in this case: node.
*
* @param \Drupal\entity\QueryAccess\QueryAccessEvent $event
* The event.
*/
public function onEventOnlyQueryAccess(QueryAccessEvent $event) {
if (\Drupal::state()->get('test_event_only_query_access')) {
$conditions = $event->getConditions();
$conditions->addCondition('type', 'foo');
$cacheability = \Drupal::state()->get('event_only_query_access_cacheability');
if ($cacheability instanceof CacheableDependencyInterface) {
$conditions->addCacheableDependency($cacheability);
}
}
}
}
@@ -0,0 +1,22 @@
<?php
namespace Drupal\entity_module_test\Field;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
/**
* Item list for the computed_entity_ref computed entity reference field.
*/
class ComputedEntityRefItemList extends FieldItemList {
use ComputedItemListTrait;
/**
* {@inheritdoc}
*/
protected function computeValue() {
// Always make the field value empty.
$this->list = [];
}
}
Loaded 100 of 31193 files, more files were not shown because too many files have changed in this diff. Show more