clean install

This commit is contained in:
2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 changed files with 3555714 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
barbaz
barnot
Bálint
cfrm
codebymikey
Csuthy
Hodgdon
jhodgdon
Pasqualle

View File

@@ -0,0 +1,31 @@
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:
SKIP_ESLINT: 1
# Speed up test execution to run test concurrently.
_PHPUNIT_CONCURRENT: 1
# Broaden test coverage.
OPT_IN_TEST_PREVIOUS_MAJOR: 1
OPT_IN_TEST_PREVIOUS_MINOR: 1
OPT_IN_TEST_NEXT_MINOR: 1
OPT_IN_TEST_NEXT_MAJOR: 1
# Check for deprecation.
RUN_JOB_UPGRADE_STATUS: 1

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.

View File

@@ -0,0 +1,34 @@
# Configuration Update Manager
* Introduction
* Installation
* Maintainers
## Introduction
The Configuration Update Manager project consists of two modules:
Configuration Update Base: A base module providing functionality related to
updating and computing differences between configuration versions. No
user interface; used by other modules such as Features.
Configuration Update Reports (in the config_update_ui sub-directory of this
project): Adds an updates report and revert functionality to configuration
management. Depends on Configuration Update Base. For more information, see
the README file in the subdirectory.
## Installation
Install as you would normally install a contributed Drupal module. Visit:
https://www.drupal.org/documentation/install/modules-themes/modules-8
for further information.
## Maintainers
* Bálint Csuthy (Pasqualle) - https://www.drupal.org/u/pasqualle
* codebymikey - https://www.drupal.org/u/codebymikey
Created by:
* Jennifer Hodgdon (jhodgdon) - https://www.drupal.org/u/jhodgdon

View File

@@ -0,0 +1,12 @@
name: 'Configuration Update Base'
type: module
description: 'Provides basic revert and update functionality for other modules.'
core_version_requirement: ^9.4 || ^10 || ^11
php: 8.1
dependencies:
- drupal:config
# Information added by Drupal.org packaging script on 2024-08-25
version: '2.0.0-alpha4'
project: 'config_update'
datestamp: 1724596933

View File

@@ -0,0 +1,21 @@
<?php
/**
* @file
* Configuration Update Base module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function config_update_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.config_update':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Configuration Update Base module provides functionality that other modules can use, related to updating and computing differences between configuration versions. This module does not provide any end-user functionality itself.') . '</p>';
return $output;
}
}

View File

@@ -0,0 +1,20 @@
services:
config_update.config_diff:
class: Drupal\config_update\ConfigDiffer
arguments: ['@string_translation']
config_update.config_list:
class: Drupal\config_update\ConfigListerWithProviders
arguments: ['@entity_type.manager', '@config.storage', '@config_update.extension_storage', '@config_update.extension_optional_storage', '@module_handler', '@theme_handler']
config_update.config_update:
class: Drupal\config_update\ConfigReverter
arguments: ['@entity_type.manager', '@config.storage', '@config_update.extension_storage', '@config_update.extension_optional_storage', '@config.factory', '@event_dispatcher']
config_update.extension_storage:
class: Drupal\Core\Config\ExtensionInstallStorage
arguments: ['@config.storage', 'config/install', '', true, '%install_profile%']
config_update.extension_optional_storage:
class: Drupal\Core\Config\ExtensionInstallStorage
arguments: ['@config.storage', 'config/optional', '', true, '%install_profile%']

View File

@@ -0,0 +1,171 @@
# Configuration Update Reports
* Introduction
* Installation
* Generating reports in the user interface
* Generating reports using Drush commands
* Important notes *** Be sure to read this section ***
## Introduction
This module provides a report that allows you to see the differences between the
default configuration items provided by the current versions of your installed
modules, themes, and install profile, and the active configuration of your
site. From this report, you can also import new configuration provided by
updates, and revert your site configuration to the provided values.
The main use case is: You update a module, and it has either changed default
configuration that it provides, or added new default configuration items that
you didn't get when you first installed the module. You want to be able to
import the new items, view the differences between the active site configuration
and the changed configuration, and possibly "revert" (or it may be an update) to
the newly-provided default configuration.
## Installation
Install the module in the normal way for Drupal modules. The only dependencies
are the Configuration Manager module (Drupal core), and the Configuration Update
Base module (part of this same project download).
## Generating reports in the user interface
You can generate configuration reports at Administration >> Configuration >>
Development >> Configuration management >> Update report (path:
admin/config/development/configuration/report ).
You can generate a report for a particular type of configuration object, such as
Actions, Tours, Views, etc. Or, you can generate a report for an installed
module, theme, or install profile. Finally, you can generate a report that
contains all configuration in one report.
The report has three sections, depending on what type you choose:
1. Missing configuration items: Configuration items that are provided as
defaults by your currently-installed modules, themes, and install profile
that are missing from your active site configuration.
Any items listed here can be imported into your site.
2. Added configuration items: Configuration items that you added to the site
(not provided by a currently-installed module, theme, or install
profile). This section is only shown when you are running the report based on
a configuration type.
Items listed here can be exported, which is useful for developers or if you
want to keep your site configuration in a version control system.
3. Changed configuration items: Configuration items that are in your active site
configuration that differ from the same item currently being provided by an
installed module, theme, or install profile.
You can export these items, see the differences between what is on your site
and what the module/theme/profile is currently providing, or "revert" to the
version currently being provided by the module/theme/profile in its default
configuration.
Note that the differences may be a bit hard to read, but hopefully they'll
give you the general idea of what has changed.
## Generating reports using Drush commands
The reports detailed in the previous section can also be generated, in pieces,
using Drush commands (https://drupal.org/project/drush):
drush config-list-types (clt)
Lists all the config types on your system. Reports can be run for
'system.simple' (simple configuration), and 'system.all' (all types), in
addition to the types listed by this command.
drush config-added-report (cra)
drush config-missing-report (crm)
drush config-different-report (crd)
drush config-inactive-report (cri)
Run config reports (see below).
drush config-diff (cfd)
Show config differences for one item between active and imported (see below).
The report commands run reports that tell what config has been added, is
missing, is inactive, or is different between your active site configuration and
the imported default configuration from config/install directories of your
installed profile, modules, and themes.
For each report except "added", the first argument is one of:
- type: Runs the report for a configuration type; use drush config-list-types to
list them.
- module: Runs the report for an installed module.
- theme: Runs the report for an installed theme.
- profile: Runs the report for the install profile.
The second argument for reports is the machine name of the configuration type,
module, theme, or install profile you want to run the report for. For the
"added" report, this is the only argument, as the added report is always by
configuration type.
These are the same as the reports you get in the UI, which is described above;
the difference is that in Drush the report is separated into pieces, and the
UI report sections have more columns giving information about each config item.
Once you have found a configuration item with differences, you can view the
differences using the config-diff command. This is a normalized/formatted diff
like in the UI of this module, so see above for details.
Drush examples:
drush clt
drush crm module node
drush cra block
drush crd theme olivero
drush crd type system.all
drush crd type system.simple
drush crd profile standard
drush cfd block.block.olivero_search
Once you have figured out which configuration items are added, missing, or
different, you can:
- Export them - see drush config-export.
- Import missing configuration or revert to provided default values. There are
Drush commands to do this:
drush config-revert (cfr)
Revert a config item found in a "different" report to the current version in
the module, theme, or install profile that provides it.
drush config-revert-multiple (cfrm)
Revert all config items of one type or from one module, theme, or install
profile to the provided versions.
drush config-import-missing (cfi)
Import a config item found in a "missing" or "inactive" report from the
current version in the module, theme, or install profile that provides it.
You can also to use the drush config-import command to import/update multiple
configuration items. But this requires that you locate the files containing the
configuration you want to import, and copy them to your configuration staging
directory.
## Important notes
Here are some notes about how this module functions:
* This module is always looking at the base configuration items, without
overrides (from settings.php, for example) or translations.
* It is possible for an install profile on a site to provide configuration that
overrides configuration from a module or theme. The install profile version
always takes precedence. As an example, consider the case where module Foo
provides a configuration item called foo.settings, and install profile Bar
overrides this with its own file. Any reports that include foo.settings will
be based on the differences between your site's active configuration and the
version in the install profile. This is not usually a problem, but it can be
confusing if you're looking at the Foo module report. The foo.settings item
will be present, but the differences reported will be between the install
profile's version and your site's active configuration, not the differences
between the Foo module version and your site's active configuration.

View File

@@ -0,0 +1,9 @@
config_update_ui.settings:
type: config_entity
label: 'Configuration Update Reports settings'
mapping:
ignore:
type: sequence
label: 'Ignored configuration items'
sequence:
type: string

View File

@@ -0,0 +1,14 @@
name: 'Configuration Update Reports'
type: module
description: 'Adds an updates report and revert functionality to configuration management.'
core_version_requirement: ^9.4 || ^10 || ^11
php: 8.1
configure: config_update_ui.report
dependencies:
- config_update:config_update
- drupal:config
# Information added by Drupal.org packaging script on 2024-08-25
version: '2.0.0-alpha4'
project: 'config_update'
datestamp: 1724596933

View File

@@ -0,0 +1,5 @@
report_css:
version: 1.x
css:
theme:
css/config_update_ui.report.css: {}

View File

@@ -0,0 +1,5 @@
config_update_ui.report:
route_name: config_update_ui.report
title: 'Updates report'
base_route: config.sync
weight: 1000

View File

@@ -0,0 +1,54 @@
<?php
/**
* @file
* Configuration Update Reports module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
/**
* Implements hook_help().
*/
function config_update_ui_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.config_update_ui':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Configuration Update Reports module provides a report that allows you to see the differences between the default configuration provided by the current versions of your installed modules, themes, and install profile, and the active configuration of your site. From this report, you can also import new configuration provided by updates, and revert your active configuration to the provided default values.') . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Checking for configuration differences') . '</dd>';
$output .= '<dd>' . t('The <a href=":report">Updates report</a> shows you configuration that differs between your site\'s active configuration and the installed modules, themes, and install profile. Choose a particular configuration type (or All), or run the report for a particular module, theme, or your install profile.', [':report' => Url::fromRoute('config_update_ui.report')->toString()]) . '</dd>';
$output .= '</dl>';
return $output;
case 'config_update_ui.report':
$output = '';
$output .= '<p>' . t('This report shows which default configuration items provided by the current versions of your installed modules, themes, and install profile differ from the active configuration of your site. You can generate the report for all configuration of a certain type; for a particular installed module, theme, or your install profile (only modules, themes, and install profiles that actually provide configuration are listed); or for all configuration.') . '</p>';
$output .= '<p>' . t('Some configuration provided by modules has dependencies, and is only added to your system when all the dependencies are satisfied. This is known as <em>optional</em> configuration.') . '</p>';
$output .= '<p>' . t('Differences, including missing and added configuration, can be due to either an updated module or theme providing different configuration from when you installed it, or to changes made by site administrators. This report does not differentiate between these two sources for differences, and note that an install profile can also silently override module/theme configuration. Overrides (such as those in your settings.php file) and translations are not considered when looking at differences.') . '</p>';
return $output;
case 'config_update_ui.diff':
return '<p>' . t('Most configuration is organized into a hierarchy of settings; at a minimum, it is a one-level hierarchy where each setting has a name and a value, and the hierarchy comes in when some of the settings have multiple components.') . '</p><p>' . t('Configuration items are normalized and formatted before computing differences. The normalization step alphabetizes the components at each level of the hierarchy, and removes a few components whose differences should be ignored, such as the UUID. The formatting step shows the full hierarchy of each configuration value with :: separators for the hierarchy levels, and a : separator between the lowest-level setting name and the value, so that in a line-by-line diff you can always see which values are actually different. Green lines with + signs have been added, and yellow lines with - signs have been removed.') . '</p><p>' . t('Note that differences are considering the base configuration, without overrides from your settings.php file, or translations.') . '</p>';
}
}
/**
* Implements hook_menu_links_discovered_alter().
*/
function config_update_ui_menu_links_discovered_alter(&$links) {
if (\Drupal::moduleHandler()->moduleExists('admin_toolbar_tools')) {
// Add the Updates report link to the Tools menu, but only if the
// Admin Toolbar Extra Tools module is present.
$links['admin_toolbar_tools.config.update'] = [
'title' => t('Updates report'),
'route_name' => 'config_update_ui.report',
'menu_name' => 'admin',
'parent' => 'config.sync',
'weight' => 3,
];
}
}

View File

@@ -0,0 +1,8 @@
view config updates report:
title: 'View configuration updates report'
revert configuration:
title: 'Revert any configuration'
restrict access: true
delete configuration:
title: 'Delete any configuration'
restrict access: true

View File

@@ -0,0 +1,43 @@
config_update_ui.report:
path: '/admin/config/development/configuration/report/{report_type}/{name}'
defaults:
_controller: '\Drupal\config_update_ui\Controller\ConfigUpdateController::report'
_title: 'Updates report'
report_type: NULL
name: NULL
requirements:
_permission: 'view config updates report'
config_update_ui.import:
path: '/admin/config/development/configuration/report/import/{config_type}/{config_name}'
defaults:
_title: 'Import'
_form: '\Drupal\config_update_ui\Form\ConfigImportConfirmForm'
requirements:
_permission: 'import configuration'
config_update_ui.diff:
path: '/admin/config/development/configuration/report/diff/{config_type}/{config_name}'
defaults:
_title: 'Differences'
_controller: '\Drupal\config_update_ui\Controller\ConfigUpdateController::diff'
config_type: NULL
config_name: NULL
requirements:
_permission: 'view config updates report'
config_update_ui.revert:
path: '/admin/config/development/configuration/report/revert/{config_type}/{config_name}'
defaults:
_title: 'Revert'
_form: '\Drupal\config_update_ui\Form\ConfigRevertConfirmForm'
requirements:
_permission: 'revert configuration'
config_update_ui.delete:
path: '/admin/config/development/configuration/report/delete/{config_type}/{config_name}'
defaults:
_title: 'Delete'
_form: '\Drupal\config_update_ui\Form\ConfigDeleteConfirmForm'
requirements:
_permission: 'delete configuration'

View File

@@ -0,0 +1,13 @@
/**
* @file
* Styling for the Config Updates report.
*/
table.config-update-report {
margin-top: 2em;
}
table.config-update-report caption {
font-size: 1.1em;
font-weight: bold;
}

View File

@@ -0,0 +1,6 @@
services:
config_update_ui.commands:
class: \Drupal\config_update_ui\Commands\ConfigUpdateUiCommands
arguments: ['@entity_type.manager', '@config_update.config_diff', '@config_update.config_list', '@config_update.config_update']
tags:
- { name: drush.command }

View File

@@ -0,0 +1,407 @@
<?php
namespace Drupal\config_update_ui\Commands;
use Drupal\Component\Diff\DiffFormatter;
use Drupal\config_update\ConfigDiffer;
use Drupal\config_update\ConfigListerWithProviders;
use Drupal\config_update\ConfigReverter;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drush\Commands\DrushCommands;
use Drush\Drush;
/**
* A set of Drush commands for Config Update Manager.
*/
class ConfigUpdateUiCommands extends DrushCommands {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected EntityTypeManagerInterface $entityManager;
/**
* The config differ.
*
* @var \Drupal\config_update\ConfigDiffer
*/
protected ConfigDiffer $configDiff;
/**
* The config lister.
*
* @var \Drupal\config_update\ConfigListerWithProviders
*/
protected ConfigListerWithProviders $configList;
/**
* The config reverter.
*
* @var \Drupal\config_update\ConfigReverter
*/
protected ConfigReverter $configUpdate;
/**
* Constructs a ConfigUpdateUiCommands object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityManager
* The entity type manager.
* @param \Drupal\config_update\ConfigDiffer $configDiff
* The config differ.
* @param \Drupal\config_update\ConfigListerWithProviders $configList
* The config lister.
* @param \Drupal\config_update\ConfigReverter $configUpdate
* The config reverter.
*/
public function __construct(EntityTypeManagerInterface $entityManager, ConfigDiffer $configDiff, ConfigListerWithProviders $configList, ConfigReverter $configUpdate) {
parent::__construct();
$this->entityManager = $entityManager;
$this->configDiff = $configDiff;
$this->configList = $configList;
$this->configUpdate = $configUpdate;
$this->logger = Drush::logger();
}
/**
* Lists config types.
*
* @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
* A structured data object of rows of configuration types.
*
* @command config:list-types
* @aliases clt,config-list-types
*/
public function listTypes() {
$definitions = $this->configList->listTypes();
return array_keys($definitions);
}
/**
* Displays added config items.
*
* Displays a list of config items that did not come from your installed
* modules, themes, or install profile.
*
* @param string $name
* The type of config to report on. See config-list-types to list them.
* You can also use system.all for all types, or system.simple for simple
* config.
*
* @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
* A structured data object of rows of added configuration items.
*
* @usage drush config-added-report action
* Displays the added config report for action config.
*
* @command config:added-report
* @aliases cra,config-added-report
*/
public function addedReport(string $name) {
[$activeList, $installList, $optionalList] = $this->configList->listConfig('type', $name);
$addedItems = array_diff($activeList, $installList, $optionalList);
if (!count($addedItems)) {
$this->logger->success(dt('No added config.'));
}
sort($addedItems);
return $addedItems;
}
/**
* Displays missing config items.
*
* Displays a list of config items from your installed modules, themes, or
* install profile that are not currently in your active config.
*
* @param string $type
* Run the report for: module, theme, profile, or "type" for config entity
* type.
* @param string $name
* The machine name of the module, theme, etc. to report on. See
* config-list-types to list types for config entities; you can also use
* system.all for all types, or system.simple for simple config.
*
* @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
* A structured data object of rows of missing configuration items.
*
* @usage drush config-missing-report type action
* Displays the missing config report for action config.
*
* @command config:missing-report
* @aliases crm,config-missing-report
*/
public function missingReport(string $type, string $name) {
[$activeList, $installList] = $this->configList->listConfig($type, $name);
$missingItems = array_diff($installList, $activeList);
if (!count($missingItems)) {
$this->logger->success(dt('No missing config.'));
}
sort($missingItems);
return $missingItems;
}
/**
* Displays optional config items.
*
* Displays a list of optional config items from your installed modules,
* themes, or install profile that are not currently in your active config.
*
* @param string $type
* Run the report for: module, theme, profile, or "type" for config entity
* type.
* @param string $name
* The machine name of the module, theme, etc. to report on. See
* config-list-types to list types for config entities; you can also use
* system.all for all types, or system.simple for simple config.
*
* @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
* A structured data object of rows of inactive configuration items.
*
* @usage drush config-inactive-report type action
* Displays the inactive config report for action config.
*
* @command config:inactive-report
* @aliases cri,config-inactive-report
*/
public function inactiveReport(string $type, string $name) {
[$activeList, $optionalList] = $this->configList->listConfig($type, $name);
$inactiveItems = array_diff($optionalList, $activeList);
if (!count($inactiveItems)) {
$this->logger->success(dt('No inactive config.'));
}
sort($inactiveItems);
return $inactiveItems;
}
/**
* Displays differing config items.
*
* Displays a list of config items that differ from the versions provided by
* your installed modules, themes, or install profile. See config-diff to
* show what the differences are.
*
* @param string $type
* Run the report for: module, theme, profile, or "type" for config entity
* type.
* @param string $name
* The machine name of the module, theme, etc. to report on. See
* config-list-types to list types for config entities; you can also use
* system.all for all types, or system.simple for simple config.
*
* @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields
* A structured data object of rows of differing configuration items.
*
* @usage drush config-different-report type action
* Displays the differing config report for action config.
*
* @command config:different-report
* @aliases crd,config-different-report
*/
public function differentReport(string $type, string $name) {
$differentItems = $this->getDifferentItems($type, $name);
if (!count($differentItems)) {
$this->logger->success(dt('No different config'));
}
return $differentItems;
}
/**
* Displays a diff of a config item.
*
* Displays line-by-line differences for one config item between your active
* config and the version currently being provided by an installed module,
* theme, or install profile.
*
* @param string $name
* The config item to diff. See config-different-report to list config
* items that are different.
*
* @return string
* The formatted diff output.
*
* @usage drush config-diff block.block.olivero_search
* Displays the config differences for the search block
* in the Olivero theme.
*
* @command config:diff
* @aliases cfd,config-diff
*/
public function diff(string $name): string {
$extension = $this->configUpdate->getFromExtension('', $name);
$active = $this->configUpdate->getFromActive('', $name);
if ($extension && $active) {
$diff = $this->configDiff->diff($extension, $active);
// Drupal\Component\Diff\DiffFormatter does not expose a service so we
// instantiate it manually here.
$diffFormatter = new DiffFormatter();
return $diffFormatter->format($diff);
}
$this->logger->error(dt('Config is missing, cannot diff.'));
return '';
}
/**
* Reverts a config item.
*
* Reverts one config item in active storage to the version provided by an
* installed module, theme, or install profile.
*
* @param string $name
* The config item to revert. See config-different-report to list config
* items that are different.
*
* @usage drush config-revert block.block.olivero_search
* Revert the config for the search block in the Olivero theme to the
* version provided by the install profile.
*
* @command config:revert
* @aliases cfr,config-revert
*/
public function revert(string $name) {
$type = $this->configList->getTypeNameByConfigName($name);
// The lister gives NULL if simple configuration, but the reverter expects
// 'system.simple' so we convert it.
if ($type === NULL) {
$type = 'system.simple';
}
$shortname = $this->getConfigShortname($type, $name);
if ($this->configUpdate->revert($type, $shortname)) {
$this->logger->success(dt('The configuration item @name was reverted to its source.', ['@name' => $name]));
}
else {
$this->logger->error(dt('There was an error and the configuration item @name was not reverted.', ['@name' => $name]));
}
}
/**
* Imports missing config item.
*
* Imports a missing or inactive config item provided by an installed module,
* theme, or install profile. Be sure that requirements are met.
*
* @param string $name
* The name of the config item to import (usually the ID you would see in
* the user interface). See config-missing-report to list config items that
* are missing, and config-inactive-report to list config items that are
* inactive.
*
* @usage drush config-import-missing block.block.olivero_search
* Import the config for the search block in the Olivero theme from the
* version provided by the install profile.
*
* @command config:import-missing
* @aliases cfi,config-import-missing
*/
public function importMissing(string $name) {
$type = $this->configList->getTypeNameByConfigName($name);
// The lister gives NULL if simple configuration, but the reverter expects
// 'system.simple' so we convert it.
if ($type === NULL) {
$type = 'system.simple';
}
$shortname = $this->getConfigShortname($type, $name);
if ($this->configUpdate->import($type, $shortname)) {
$this->logger->success(dt('The configuration item @name was imported from its source.', ['@name' => $name]));
}
else {
$this->logger->error(dt('There was an error and the configuration item @name was not imported.', ['@name' => $name]));
}
}
/**
* Reverts multiple config items to extension provided version.
*
* Reverts a set of config items to the versions provided by installed
* modules, themes, or install profiles. A set is all differing items from
* one extension, or one type of configuration.
*
* @param string $type
* Type of set to revert: "module" for all items from a module, "theme" for
* all items from a theme, "profile" for all items from the install profile,
* or "type" for all items of one config entity type. See
* config-different-report to list config items that are different.
* @param string $name
* The machine name of the module, theme, etc. to revert items of. All
* items in the corresponding config-different-report will be reverted.
*
* @usage drush config-revert-multiple type action
* Revert all differing config items of type action.
*
* @command config:revert-multiple
* @aliases cfrm,config-revert-multiple
*/
public function revertMultiple(string $type, string $name) {
$different = $this->getDifferentItems($type, $name);
foreach ($different as $name) {
$this->revert($name);
}
}
/**
* Lists differing config items.
*
* Lists config items that differ from the versions provided by your
* installed modules, themes, or install profile. See config-diff to show
* what the differences are.
*
* @param string $type
* Run the report for: module, theme, profile, or "type" for config entity
* type.
* @param string $name
* The machine name of the module, theme, etc. to report on. See
* config-list-types to list types for config entities; you can also use
* system.all for all types, or system.simple for simple config.
*
* @return array
* An array of differing configuration items.
*/
protected function getDifferentItems(string $type, string $name): array {
[$activeList, $installList, $optionalList] = $this->configList->listConfig($type, $name);
$addedItems = array_diff($activeList, $installList, $optionalList);
$activeAndAddedItems = array_diff($activeList, $addedItems);
$differentItems = [];
foreach ($activeAndAddedItems as $name) {
$active = $this->configUpdate->getFromActive('', $name);
$extension = $this->configUpdate->getFromExtension('', $name);
if (!$this->configDiff->same($active, $extension)) {
$differentItems[] = $name;
}
}
sort($differentItems);
return $differentItems;
}
/**
* Gets the config item shortname given the type and name.
*
* @param string $type
* The type of the config item.
* @param string $name
* The name of the config item.
*
* @return string
* The shortname for the configuration item.
*/
protected function getConfigShortname(string $type, string $name): string {
$shortname = $name;
if ($type != 'system.simple') {
$definition = $this->entityManager->getDefinition($type);
$prefix = $definition->getConfigPrefix() . '.';
if (str_starts_with($name, $prefix)) {
$shortname = substr($name, strlen($prefix));
}
}
return $shortname;
}
}

View File

@@ -0,0 +1,718 @@
<?php
namespace Drupal\config_update_ui\Controller;
use Drupal\config_update\ConfigDiffInterface;
use Drupal\config_update\ConfigListByProviderInterface;
use Drupal\config_update\ConfigRevertInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Diff\DiffFormatter;
use Drupal\Core\Extension\ModuleExtensionList;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\Url;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Returns responses for Configuration Revert module operations.
*/
class ConfigUpdateController extends ControllerBase {
/**
* The config differ.
*
* @var \Drupal\config_update\ConfigDiffInterface
*/
protected $configDiff;
/**
* The config lister.
*
* @var \Drupal\config_update\ConfigListByProviderInterface
*/
protected $configList;
/**
* The config reverter.
*
* @var \Drupal\config_update\ConfigRevertInterface
*/
protected $configRevert;
/**
* The diff formatter.
*
* @var \Drupal\Core\Diff\DiffFormatter
*/
protected $diffFormatter;
/**
* The module extension list.
*
* @var \Drupal\Core\Extension\ModuleExtensionList
*/
protected $moduleExtensionList;
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* The config factory.
*
* @var \Drupal\Core\config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Logger interface.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* Constructs a ConfigUpdateController object.
*
* @param \Drupal\config_update\ConfigDiffInterface $config_diff
* The config differ.
* @param \Drupal\config_update\ConfigListByProviderInterface $config_list
* The config lister.
* @param \Drupal\config_update\ConfigRevertInterface $config_update
* The config reverter.
* @param \Drupal\Core\Diff\DiffFormatter $diff_formatter
* The diff formatter to use.
* @param \Drupal\Core\Extension\ModuleExtensionList $module_extension_list
* The module extension list.
* @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
* The theme handler.
* @param \drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Psr\Log\LoggerInterface $logger
* The logger instance.
*/
public function __construct(ConfigDiffInterface $config_diff, ConfigListByProviderInterface $config_list, ConfigRevertInterface $config_update, DiffFormatter $diff_formatter, ModuleExtensionList $module_extension_list, ThemeHandlerInterface $theme_handler, ConfigFactoryInterface $config_factory, LoggerInterface $logger) {
$this->configDiff = $config_diff;
$this->configList = $config_list;
$this->configRevert = $config_update;
$this->diffFormatter = $diff_formatter;
$this->diffFormatter->show_header = FALSE;
$this->moduleExtensionList = $module_extension_list;
$this->themeHandler = $theme_handler;
$this->configFactory = $config_factory;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config_update.config_diff'),
$container->get('config_update.config_list'),
$container->get('config_update.config_update'),
$container->get('diff.formatter'),
$container->get('extension.list.module'),
$container->get('theme_handler'),
$container->get('config.factory'),
$container->get('logger.factory')->get('config_update_ui')
);
}
/**
* Shows the diff between active and provided configuration.
*
* @param string $config_type
* The type of configuration.
* @param string $config_name
* The name of the config item, without the prefix.
*
* @return array
* Render array for page showing differences between them.
*/
public function diff($config_type, $config_name) {
$diff = $this->configDiff->diff(
$this->configRevert->getFromExtension($config_type, $config_name),
$this->configRevert->getFromActive($config_type, $config_name)
);
$build = [];
$definition = $this->configList->getType($config_type);
$config_type_label = ($definition) ? $definition->getLabel() : $this->t('Simple configuration');
$build['#title'] = $this->t('Config difference for @type @name',
[
'@type' => $config_type_label,
'@name' => $config_name,
]
);
$build['#attached']['library'][] = 'system/diff';
$rows = $this->diffFormatter->format($diff);
$build['diff'] = [
'#type' => 'table',
'#header' => [
['data' => $this->t('Source config'), 'colspan' => '2'],
['data' => $this->t('Site config'), 'colspan' => '2'],
],
'#rows' => $rows,
'#empty' => $this->t('There are no changes.'),
'#attributes' => ['class' => ['diff']],
];
$url = new Url('config_update_ui.report');
$build['wrapper'] = [
'#type' => 'container',
'#attributes' => [
'class' => ['form-actions'],
],
];
$links = [];
if (!empty($rows)) {
$links['revert'] = [
'url' => Url::fromRoute('config_update_ui.revert',
[
'config_type' => $config_type,
'config_name' => $config_name,
]
),
'title' => $this->t('Revert to source'),
];
}
$links['export'] = [
'url' => Url::fromRoute('config.export_single', ['config_type' => $config_type, 'config_name' => $config_name]),
'title' => $this->t('Export'),
];
$links['delete'] = [
'url' => Url::fromRoute('config_update_ui.delete', ['config_type' => $config_type, 'config_name' => $config_name]),
'title' => $this->t('Delete'),
];
$build['wrapper']['operations'] = [
'#type' => 'dropbutton',
'#links' => $links,
];
$build['wrapper']['back'] = [
'#type' => 'link',
'#attributes' => [
'class' => [
'button',
],
],
'#title' => $this->t("Back to 'Updates report' page"),
'#url' => $url,
];
return $build;
}
/**
* Generates the config updates report.
*
* @param string $report_type
* (optional) Type of report to run:
* - type: Configuration entity type.
* - module: Module.
* - theme: Theme.
* - profile: Install profile.
* @param string $name
* (optional) Name of specific item to run report for (config entity type
* ID, module machine name, etc.). Ignored for profile.
*
* @return array
* Render array for report, with section at the top for selecting another
* report to run. If either $report_type or $name is missing, the report
* itself is not generated.
*/
public function report($report_type = NULL, $name = NULL) {
$links = $this->generateReportLinks();
$report = $this->generateReport($report_type, $name);
if (!$report) {
return $links;
}
// If there is a report, extract the title, put table of links in a
// details element, and add report to build.
$build = [];
$build['#title'] = $report['#title'];
unset($report['#title']);
$build['links_wrapper'] = [
'#type' => 'details',
'#title' => $this->t('Generate new report'),
'#children' => $links,
];
$build['report'] = $report;
$build['#attached']['library'][] = 'config_update/report_css';
return $build;
}
/**
* Generates the operations links for running individual reports.
*
* @return array
* Render array for the operations links for running reports.
*/
protected function generateReportLinks() {
// These links are put into an 'operations' render array element. They do
// not look good outside of tables. Also note that the array index in
// operations links is used as a class on the LI element. Some classes are
// special in the Seven CSS, such as "contextual", so avoid hitting these
// accidentally by prefixing.
$build = [];
$build['links'] = [
'#type' => 'table',
'#header' => [
$this->t('Report type'),
$this->t('Report on'),
],
'#rows' => [],
];
// Full report of all configuration.
$links['report_full'] = [
'title' => $this->t('Everything'),
'url' => Url::fromRoute('config_update_ui.report', ['report_type' => 'type', 'name' => 'system.all']),
];
$build['links']['#rows'][] = [
$this->t('Full report'),
[
'data' => [
'#type' => 'operations',
'#links' => $links,
],
],
];
// Reports by configuration type.
$definitions = $this->configList->listTypes();
$links = [];
foreach ($definitions as $entity_type => $definition) {
$links['report_type_' . $entity_type] = [
'title' => $definition->getLabel(),
'url' => Url::fromRoute('config_update_ui.report', ['report_type' => 'type', 'name' => $entity_type]),
];
}
uasort($links, [$this, 'sortLinks']);
$links = [
'report_type_system.simple' => [
'title' => $this->t('Simple configuration'),
'url' => Url::fromRoute('config_update_ui.report', ['report_type' => 'type', 'name' => 'system.simple']),
],
] + $links;
$build['links']['#rows'][] = [
$this->t('Single configuration type'),
[
'data' => [
'#type' => 'operations',
'#links' => $links,
],
],
];
// Make a list of installed modules.
$profile = $this->getProfileName();
$modules = $this->moduleExtensionList->getList();
$links = [];
foreach ($modules as $machine_name => $module) {
if ($machine_name != $profile && $this->configList->providerHasConfig('module', $machine_name)) {
$links['report_module_' . $machine_name] = [
'title' => $this->moduleExtensionList->getName($machine_name),
'url' => Url::fromRoute('config_update_ui.report', ['report_type' => 'module', 'name' => $machine_name]),
];
}
}
uasort($links, [$this, 'sortLinks']);
$build['links']['#rows'][] = [
$this->t('Single module'),
[
'data' => [
'#type' => 'operations',
'#links' => $links,
],
],
];
// Make a list of installed themes.
$themes = $this->themeHandler->listInfo();
$links = [];
foreach ($themes as $machine_name => $theme) {
if ($this->configList->providerHasConfig('theme', $machine_name)) {
$links['report_theme_' . $machine_name] = [
'title' => $this->themeHandler->getName($machine_name),
'url' => Url::fromRoute('config_update_ui.report', ['report_type' => 'theme', 'name' => $machine_name]),
];
}
}
uasort($links, [$this, 'sortLinks']);
$build['links']['#rows'][] = [
$this->t('Single theme'),
[
'data' => [
'#type' => 'operations',
'#links' => $links,
],
],
];
$links = [];
// Profile is just one option.
if ($this->configList->providerHasConfig('profile', $profile)) {
$links['report_profile_' . $profile] = [
'title' => $this->moduleExtensionList->getName($profile),
'url' => Url::fromRoute('config_update_ui.report', ['report_type' => 'profile']),
];
$build['links']['#rows'][] = [
$this->t('Installation profile'),
[
'data' => [
'#type' => 'operations',
'#links' => $links,
],
],
];
}
return $build;
}
/**
* Generates a report about config updates.
*
* @param string $report_type
* Type of report to generate: 'type', 'module', 'theme', or 'profile'.
* @param string $value
* Machine name of a configuration type, module, or theme to generate the
* report for. Ignored for profile, since that uses the active profile.
*
* @return array
* Render array for the updates report. Empty if invalid or missing
* report type or value.
*/
protected function generateReport($report_type, $value) {
// Figure out what to name the report, and incidentally, validate that
// $value exists for this type of report.
switch ($report_type) {
case 'type':
if ($value == 'system.all') {
$label = $this->t('All configuration');
}
elseif ($value == 'system.simple') {
$label = $this->t('Simple configuration');
}
else {
$definition = $this->configList->getType($value);
if (!$definition) {
return NULL;
}
$label = $this->t('@name configuration', ['@name' => $definition->getLabel()]);
}
break;
case 'module':
$list = $this->moduleExtensionList->getList();
if (!isset($list[$value])) {
return NULL;
}
$label = $this->t('@name module', ['@name' => $this->moduleExtensionList->getName($value)]);
break;
case 'theme':
$list = $this->themeHandler->listInfo();
if (!isset($list[$value])) {
return NULL;
}
$label = $this->t('@name theme', ['@name' => $this->themeHandler->getName($value)]);
break;
case 'profile':
$profile = $this->getProfileName();
$label = $this->t('@name profile', ['@name' => $this->moduleExtensionList->getName($profile)]);
break;
default:
return NULL;
}
// List the active and extension-provided config.
[$active_list, $install_list, $optional_list] = $this->configList->listConfig($report_type, $value);
// Build the report.
$build = [];
$build['#title'] = $this->t('Configuration updates report for @label', ['@label' => $label]);
$build['report_header'] = ['#markup' => '<h3>' . $this->t('Updates report') . '</h3>'];
// List items missing from site.
$removed = array_diff($install_list, $active_list);
$build['removed'] = [
'#caption' => $this->t('Missing configuration items'),
'#empty' => $this->t('None: all provided configuration items are in your active configuration.'),
] + $this->makeReportTable($removed, 'extension', ['import']);
// List optional items that are not installed.
$inactive = array_diff($optional_list, $active_list);
$build['inactive'] = [
'#caption' => $this->t('Inactive optional items'),
'#empty' => $this->t('None: all optional configuration items are in your active configuration.'),
] + $this->makeReportTable($inactive, 'extension', ['import']);
// List items added to site, which only makes sense in the report for a
// config type.
$added = array_diff($active_list, $install_list, $optional_list);
if ($report_type == 'type') {
$build['added'] = [
'#caption' => $this->t('Added configuration items'),
'#empty' => $this->t('None: all active configuration items of this type were provided by modules, themes, or install profile.'),
] + $this->makeReportTable($added, 'active', ['export', 'delete']);
}
// For differences, we need to go through the array of config in both
// and see if each config item is the same or not.
$both = array_diff($active_list, $added);
$different = [];
foreach ($both as $name) {
if (!$this->configDiff->same(
$this->configRevert->getFromExtension('', $name),
$this->configRevert->getFromActive('', $name)
)) {
$different[] = $name;
}
}
$build['different'] = [
'#caption' => $this->t('Changed configuration items'),
'#empty' => $this->t('None: no active configuration items differ from their current provided versions.'),
] + $this->makeReportTable($different, 'active',
['diff', 'export', 'revert', 'delete']);
return $build;
}
/**
* Builds a table for the report.
*
* @param string[] $names
* List of machine names of config items for the table.
* @param string $storage
* Config storage the items can be loaded from, either 'active' or
* 'extension'.
* @param string[] $actions
* Action links to include, one or more of:
* - diff
* - revert
* - export
* - import
* - delete.
*
* @return array
* Render array for the table, not including the #empty and #prefix
* properties.
*/
protected function makeReportTable(array $names, $storage, array $actions) {
$build = [];
$ignored_items = $this->configFactory->get('config_update_ui.settings')->get('ignore');
if (is_array($ignored_items)) {
$names = array_diff($names, $ignored_items);
}
$build['#type'] = 'table';
$build['#attributes'] = ['class' => ['config-update-report']];
$build['#header'] = [
'name' => [
'data' => $this->t('Machine name'),
],
'label' => [
'data' => $this->t('Label (if any)'),
'class' => [RESPONSIVE_PRIORITY_LOW],
],
'type' => [
'data' => $this->t('Type'),
'class' => [RESPONSIVE_PRIORITY_MEDIUM],
],
'provider' => [
'data' => $this->t('Provider'),
'class' => [RESPONSIVE_PRIORITY_LOW],
],
'operations' => [
'data' => $this->t('Operations'),
],
];
$build['#rows'] = [];
sort($names);
foreach ($names as $name) {
$row = [];
if ($storage == 'active') {
$config = $this->configRevert->getFromActive('', $name);
}
else {
$config = $this->configRevert->getFromExtension('', $name);
}
if (empty($config)) {
$this->logger->error('Malformed config file @config_name.', ['@config_name' => $name]);
continue;
}
// Figure out what type of config it is, and get the ID.
$entity_type = $this->configList->getTypeNameByConfigName($name);
if (!$entity_type) {
// This is simple config.
$id = $name;
$label = '';
$type_label = $this->t('Simple configuration');
$entity_type = 'system.simple';
}
else {
$definition = $this->configList->getType($entity_type);
$id_key = $definition->getKey('id');
$id = $config[$id_key];
// The label key is not required.
if ($label_key = $definition->getKey('label')) {
$label = $config[$label_key];
}
else {
$label = '';
}
$type_label = $definition->getLabel();
}
$row[] = $name;
$row[] = $label;
$row[] = $type_label;
$provider = $this->configList->getConfigProvider($name);
$provider_name = '';
if (!empty($provider)) {
switch ($provider[0]) {
case 'profile':
$provider_name = $this->moduleExtensionList->getName($provider[1]);
if ($provider_name) {
$provider_name = $this->t('@name profile', ['@name' => $provider_name]);
}
else {
$provider_name = '';
}
break;
case 'module':
$provider_name = $this->moduleExtensionList->getName($provider[1]);
if ($provider_name) {
$provider_name = $this->t('@name module', ['@name' => $provider_name]);
}
else {
$provider_name = '';
}
break;
case 'theme':
$provider_name = $this->themeHandler->getName($provider[1]);
if ($provider_name) {
$provider_name = $this->t('@name theme', ['@name' => $provider_name]);
}
else {
$provider_name = '';
}
break;
}
}
$row[] = $provider_name;
$links = [];
$routes = [
'export' => 'config.export_single',
'import' => 'config_update_ui.import',
'diff' => 'config_update_ui.diff',
'revert' => 'config_update_ui.revert',
'delete' => 'config_update_ui.delete',
];
$titles = [
'export' => $this->t('Export'),
'import' => $this->t('Import from source'),
'diff' => $this->t('Show differences'),
'revert' => $this->t('Revert to source'),
'delete' => $this->t('Delete'),
];
foreach ($actions as $action) {
$links[$action] = [
'url' => Url::fromRoute($routes[$action], ['config_type' => $entity_type, 'config_name' => $id]),
'title' => $titles[$action],
];
}
$row[] = [
'data' => [
'#type' => 'operations',
'#links' => $links,
],
];
$build['#rows'][] = $row;
}
return $build;
}
/**
* Compares links for uasort(), to sort by displayed link title.
*/
protected static function sortLinks($link1, $link2) {
$title1 = $link1['title'];
$title2 = $link2['title'];
if ($title1 == $title2) {
return 0;
}
return ($title1 < $title2) ? -1 : 1;
}
/**
* Returns the name of the install profile.
*
* For backwards compatibility with pre/post 8.3.x, tries to get it from
* either configuration or settings.
*
* @return string
* The name of the install profile.
*/
protected function getProfileName() {
// Code adapted from DrupalKernel::getInstalProfile() in Core.
// In Core 8.3.x or later, read from config.
$profile = $this->configFactory->get('core.extension')->get('profile');
if (!empty($profile)) {
return $profile;
}
else {
// If system_update_8300() has not yet run, use settings.
return Settings::get('install_profile');
}
}
}

View File

@@ -0,0 +1,149 @@
<?php
namespace Drupal\config_update_ui\Form;
use Drupal\config_update\ConfigListInterface;
use Drupal\config_update\ConfigRevertInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Defines a confirmation form for deleting configuration.
*/
class ConfigDeleteConfirmForm extends ConfirmFormBase {
/**
* The type of config being deleted.
*
* @var string
*/
protected $type;
/**
* The name of the config item being deleted, without the prefix.
*
* @var string
*/
protected $name;
/**
* The config lister.
*
* @var \Drupal\config_update\ConfigListInterface
*/
protected $configList;
/**
* The config reverter.
*
* @var \Drupal\config_update\ConfigRevertInterface
*/
protected $configRevert;
/**
* Constructs a ConfigDeleteConfirmForm object.
*
* @param \Drupal\config_update\ConfigListInterface $config_list
* The config lister.
* @param \Drupal\config_update\ConfigRevertInterface $config_update
* The config reverter.
*/
public function __construct(ConfigListInterface $config_list, ConfigRevertInterface $config_update) {
$this->configList = $config_list;
$this->configRevert = $config_update;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config_update.config_list'),
$container->get('config_update.config_update')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_delete_confirm';
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
if ($this->type == 'system.simple') {
$type_label = $this->t('Simple configuration');
}
else {
$definition = $this->configList->getType($this->type);
if (!$definition) {
// Make a 404 error if the type doesn't exist.
throw new NotFoundHttpException();
}
$type_label = $definition->get('label');
}
// To delete, the configuration item must exist in active storage. Check
// that and make a 404 error if not.
$active = $this->configRevert->getFromActive($this->type, $this->name);
if (!$active) {
throw new NotFoundHttpException();
}
return $this->t('Are you sure you want to delete the %type config %item?',
[
'%type' => $type_label,
'%item' => $this->name,
]
);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('config_update_ui.report');
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->t('This action cannot be undone. Manually deleting configuration from this page can cause problems on your site due to missing dependencies, and should only be done if there is no other way to delete a problematic piece of configuration.');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $config_type = NULL, $config_name = NULL) {
$this->type = $config_type;
$this->name = $config_name;
$form = parent::buildForm($form, $form_state);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->configRevert->delete($this->type, $this->name);
$this->messenger()->addMessage($this->t('The configuration %item has been deleted.', ['%item' => $this->name]));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

View File

@@ -0,0 +1,151 @@
<?php
namespace Drupal\config_update_ui\Form;
use Drupal\config_update\ConfigListInterface;
use Drupal\config_update\ConfigRevertInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Defines a confirmation form for importing configuration.
*/
class ConfigImportConfirmForm extends ConfirmFormBase {
/**
* The type of config being imported.
*
* @var string
*/
protected $type;
/**
* The name of the config item being imported, without the prefix.
*
* @var string
*/
protected $name;
/**
* The config lister.
*
* @var \Drupal\config_update\ConfigListInterface
*/
protected $configList;
/**
* The config reverter.
*
* @var \Drupal\config_update\ConfigRevertInterface
*/
protected $configRevert;
/**
* Constructs a ConfigImportConfirmForm object.
*
* @param \Drupal\config_update\ConfigListInterface $config_list
* The config lister.
* @param \Drupal\config_update\ConfigRevertInterface $config_update
* The config reverter.
*/
public function __construct(ConfigListInterface $config_list, ConfigRevertInterface $config_update) {
$this->configList = $config_list;
$this->configRevert = $config_update;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config_update.config_list'),
$container->get('config_update.config_update')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_import_confirm';
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
if ($this->type == 'system.simple') {
$type_label = $this->t('Simple configuration');
}
else {
$definition = $this->configList->getType($this->type);
if (!$definition) {
// Make a 404 error if the type doesn't exist.
throw new NotFoundHttpException();
}
$type_label = $definition->get('label');
}
// To import (as opposed to revert), the configuration item must exist in
// extension storage but not active storage, so check that, and make a 404
// error if not.
$extension = $this->configRevert->getFromExtension($this->type, $this->name);
$active = $this->configRevert->getFromActive($this->type, $this->name);
if (!$extension || $active) {
throw new NotFoundHttpException();
}
return $this->t('Are you sure you want to import the %type config %item from its source configuration?',
[
'%type' => $type_label,
'%item' => $this->name,
]
);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('config_update_ui.report');
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->t('Configuration will be added to your site. This action cannot be undone.');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Import');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $config_type = NULL, $config_name = NULL) {
$this->type = $config_type;
$this->name = $config_name;
$form = parent::buildForm($form, $form_state);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->configRevert->import($this->type, $this->name);
$this->messenger()->addMessage($this->t('The configuration %item has been imported from its source.', ['%item' => $this->name]));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

View File

@@ -0,0 +1,151 @@
<?php
namespace Drupal\config_update_ui\Form;
use Drupal\config_update\ConfigListInterface;
use Drupal\config_update\ConfigRevertInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Defines a confirmation form for reverting configuration.
*/
class ConfigRevertConfirmForm extends ConfirmFormBase {
/**
* The type of config being reverted.
*
* @var string
*/
protected $type;
/**
* The name of the config item being reverted, without the prefix.
*
* @var string
*/
protected $name;
/**
* The config lister.
*
* @var \Drupal\config_update\ConfigListInterface
*/
protected $configList;
/**
* The config reverter.
*
* @var \Drupal\config_update\ConfigRevertInterface
*/
protected $configRevert;
/**
* Constructs a ConfigRevertConfirmForm object.
*
* @param \Drupal\config_update\ConfigListInterface $config_list
* The config lister.
* @param \Drupal\config_update\ConfigRevertInterface $config_update
* The config reverter.
*/
public function __construct(ConfigListInterface $config_list, ConfigRevertInterface $config_update) {
$this->configList = $config_list;
$this->configRevert = $config_update;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config_update.config_list'),
$container->get('config_update.config_update')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_update_confirm';
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
if ($this->type == 'system.simple') {
$type_label = $this->t('Simple configuration');
}
else {
$definition = $this->configList->getType($this->type);
if (!$definition) {
// Make a 404 error if the type doesn't exist.
throw new NotFoundHttpException();
}
$type_label = $definition->get('label');
}
// To revert (as opposed to import), the configuration item must exist in
// both active storage and extension storage, so check that and make a 404
// error if not.
$extension = $this->configRevert->getFromExtension($this->type, $this->name);
$active = $this->configRevert->getFromActive($this->type, $this->name);
if (!$extension || !$active) {
throw new NotFoundHttpException();
}
return $this->t('Are you sure you want to revert the %type config %item to its source configuration?',
[
'%type' => $type_label,
'%item' => $this->name,
]
);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('config_update_ui.report');
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->t('Customizations will be lost. This action cannot be undone.');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Revert');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $config_type = NULL, $config_name = NULL) {
$this->type = $config_type;
$this->name = $config_name;
$form = parent::buildForm($form, $form_state);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->configRevert->revert($this->type, $this->name);
$this->messenger()->addMessage($this->t('The configuration %item has been reverted to its source.', ['%item' => $this->name]));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace Drupal\Tests\config_update_ui\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Verify config reports, reverts, and diffs with profile overrides.
*
* @group config_update
*/
class ConfigProfileOverridesTest extends BrowserTestBase {
/**
* Use the Standard profile, so that there are profile config overrides.
*
* @var string
*/
protected $profile = 'standard';
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'config',
'config_update',
'config_update_ui',
];
/**
* The admin user that will be created.
*
* @var object
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create user and log in.
$this->adminUser = $this->createUser([
'access administration pages',
'administer themes',
'view config updates report',
'synchronize configuration',
'export configuration',
'import configuration',
'revert configuration',
'delete configuration',
]);
$this->drupalLogin($this->adminUser);
}
/**
* Tests that config overrides work as expected.
*/
public function testConfigOverrides() {
// The Standard install profile contains a system.theme.yml file that
// sets up olivero/claro as the default/admin theme. The default config
// from the System module has no admin theme and stark as the default
// theme. So first, run the report on simple configuration and verify
// that system.theme is not shown (it should not be missing, or added,
// or overridden).
$this->drupalGet('admin/config/development/configuration/report/type/system.simple');
$session = $this->assertSession();
$session->responseNotContains('system.theme');
// Go to the Appearance page and change the theme to whatever is currently
// disabled. Return to the report and verify that system.theme is there,
// since it is now overridden.
$this->drupalGet('admin/appearance');
$this->clickLink('Install and set as default');
$this->drupalGet('admin/config/development/configuration/report/type/system.simple');
$session = $this->assertSession();
$session->pageTextContains('system.theme');
// Look at the differences for system.theme and verify it's against
// the standard profile version, not default version. The line for
// default should show olivero as the source; if it's against the system
// version, the word olivero would not be there.
$this->drupalGet('admin/config/development/configuration/report/diff/system.simple/system.theme');
$session = $this->assertSession();
$session->pageTextContains('olivero');
// Revert and verify that it reverted to the profile version, not the
// system module version.
$this->drupalGet('admin/config/development/configuration/report/revert/system.simple/system.theme');
$this->submitForm([], 'Revert');
$this->drupalGet('admin/config/development/configuration/single/export/system.simple/system.theme');
$session = $this->assertSession();
$session->pageTextContains('admin: claro');
$session->pageTextContains('default: olivero');
}
}

View File

@@ -0,0 +1,415 @@
<?php
namespace Drupal\Tests\config_update_ui\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Verify the config revert report and its links.
*
* @group config_update
*/
class ConfigUpdateTest extends BrowserTestBase {
/**
* Default theme.
*
* @var string
*/
protected $defaultTheme = 'stark';
/**
* Modules to enable.
*
* Use the Search module because it has two included config items in its
* config/install, assuming node and user are also enabled.
*
* @var array
*/
protected static $modules = [
'config',
'config_update',
'config_update_ui',
'search',
'node',
'user',
'block',
'text',
'field',
'filter',
];
/**
* The admin user that will be created.
*
* @var object
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create user and log in.
$this->adminUser = $this->createUser([
'access administration pages',
'administer search',
'view config updates report',
'synchronize configuration',
'export configuration',
'import configuration',
'revert configuration',
'delete configuration',
'administer filters',
]);
$this->drupalLogin($this->adminUser);
// Make sure local tasks and page title are showing.
$this->placeBlock('local_tasks_block');
$this->placeBlock('page_title_block');
}
/**
* Tests the config report and its linked pages.
*/
public function testConfigReport() {
// Test links to report page.
$this->drupalGet('admin/config/development/configuration');
$this->clickLink('Updates report');
$this->assertNoReport();
// Verify some empty reports.
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->assertReport('Search page', [], [], [], []);
// Module, theme, and profile reports have no 'added' section.
$this->drupalGet('admin/config/development/configuration/report/module/search');
$this->assertReport('Search module', [], [], [], [], ['added']);
$this->drupalGet('admin/config/development/configuration/report/theme/stark');
$this->assertReport('Stark theme', [], [], [], [], ['added']);
$inactive = ['locale.settings' => 'Simple configuration'];
$this->drupalGet('admin/config/development/configuration/report/profile');
$this->assertReport('Testing profile', [], [], [], $inactive, ['added']);
// The locale.settings line should show that the Testing profile is the
// provider.
$session = $this->assertSession();
$session->pageTextContains('Testing profile');
// Verify that the user search page cannot be imported (because it already
// exists).
$this->drupalGet('admin/config/development/configuration/report/import/search_page/user_search');
$session = $this->assertSession();
$session->statusCodeEquals(404);
// Delete the user search page from the search UI and verify report for
// both the search page config type and user module.
$this->drupalGet('admin/config/search/pages');
$this->clickLink('Delete');
$this->submitForm([], 'Delete');
$inactive = ['search.page.user_search' => 'Users'];
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->assertReport('Search page', [], [], [], $inactive);
// The search.page.user_search line should show that the User module is the
// provider.
$session = $this->assertSession();
$session->pageTextContains('User module');
$this->drupalGet('admin/config/development/configuration/report/module/user');
$this->assertReport('User module', [], [], [], $inactive, ['added', 'changed']);
// Verify that the user search page cannot be reverted (because it does
// not already exist).
$this->drupalGet('admin/config/development/configuration/report/revert/search_page/user_search');
$session = $this->assertSession();
$session->statusCodeEquals(404);
// Verify that the delete URL doesn't work either.
$this->drupalGet('admin/config/development/configuration/report/delete/search_page/user_search');
$session = $this->assertSession();
$session->statusCodeEquals(404);
// Use the import link to get it back. Do this from the search page
// report to make sure we are importing the right config.
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->clickLink('Import from source');
$this->submitForm([], 'Import');
$session = $this->assertSession();
$session->pageTextContains('has been imported');
$this->assertNoReport();
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->assertReport('Search page', [], [], [], []);
// Verify that after import, there is no config hash generated.
$this->drupalGet('admin/config/development/configuration/single/export/search_page/user_search');
$session = $this->assertSession();
$session->pageTextContains('id: user_search');
$session->pageTextNotContains('default_config_hash:');
// Edit the node search page from the search UI and verify report.
$this->drupalGet('admin/config/search/pages');
$this->clickLink('Edit');
$this->submitForm([
'label' => 'New label',
'path' => 'new_path',
], 'Save search page');
$changed = ['search.page.node_search' => 'New label'];
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->assertReport('Search page', [], [], $changed, []);
// Test the show differences link.
$this->clickLink('Show differences');
$session = $this->assertSession();
$session->pageTextContains('Content');
$session->pageTextContains('New label');
$session->pageTextContains('node');
$session->pageTextContains('new_path');
// Test the Back link.
$this->clickLink("Back to 'Updates report' page");
$this->assertNoReport();
// Test the export link.
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->clickLink('Export', 1);
$session = $this->assertSession();
$session->pageTextContains('Here is your configuration:');
$session->pageTextContains('id: node_search');
$session->pageTextContains('New label');
$session->pageTextContains('path: new_path');
$session->pageTextContains('search.page.node_search.yml');
// Grab the uuid and hash lines from the exported config for the next test.
$text = strip_tags($this->getSession()->getPage()->find('css', 'textarea')->getHtml());
$matches = [];
preg_match('|^.*uuid:.*$|m', $text, $matches);
$uuid_line = trim($matches[0]);
preg_match('|^.*default_config_hash:.*$|m', $text, $matches);
$hash_line = trim($matches[0]);
// Test reverting.
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->clickLink('Revert to source');
$session = $this->assertSession();
$session->pageTextContains('Are you sure you want to revert');
$session->pageTextContains('Search page');
$session->pageTextContains('node_search');
$session->pageTextContains('Customizations will be lost. This action cannot be undone');
$this->submitForm([], 'Revert');
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->assertReport('Search page', [], [], [], []);
// Verify that the uuid and hash keys were retained in the revert.
$this->drupalGet('admin/config/development/configuration/single/export/search_page/node_search');
$session = $this->assertSession();
$session->pageTextContains('id: node_search');
$session->pageTextContains($uuid_line);
$session->pageTextContains($hash_line);
// Add a new search page from the search UI and verify report.
$this->drupalGet('admin/config/search/pages');
$this->submitForm([
'search_type' => 'node_search',
], 'Add search page');
$this->submitForm([
'label' => 'test',
'id' => 'test',
'path' => 'test',
], 'Save');
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$added = ['search.page.test' => 'test'];
$this->assertReport('Search page', [], $added, [], []);
// Test the export link.
$this->clickLink('Export', 1);
$session = $this->assertSession();
$session->pageTextContains('Here is your configuration:');
$session->pageTextContains('id: test');
$session->pageTextContains('label: test');
$session->pageTextContains('path: test');
$session->pageTextContains('search.page.test.yml');
// Test the delete link.
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->clickLink('Delete');
$session = $this->assertSession();
$session->pageTextContains('Are you sure');
$session->pageTextContains('cannot be undone');
$this->submitForm([], 'Delete');
$session = $this->assertSession();
$session->pageTextContains('has been deleted');
// And verify the report again.
$this->drupalGet('admin/config/development/configuration/report/type/search_page');
$this->assertReport('Search page', [], [], [], []);
// Change the search module config and verify the actions work for
// simple config.
$this->drupalGet('admin/config/search/pages');
$this->submitForm([
'minimum_word_size' => 4,
], 'Save configuration');
$changed = ['search.settings' => 'search.settings'];
$this->drupalGet('admin/config/development/configuration/report/module/search');
$this->assertReport('Search module', [], [], $changed, [], ['added']);
$this->clickLink('Show differences');
$session = $this->assertSession();
$session->pageTextContains('Config difference for Simple configuration search.settings');
$session->pageTextContains('index::minimum_word_size');
$session->pageTextContains('4');
$this->drupalGet('admin/config/development/configuration/report/module/search');
$this->clickLink('Export', 1);
$session = $this->assertSession();
$session->pageTextContains('minimum_word_size: 4');
// Grab the hash line for the next test.
$text = strip_tags($this->getSession()->getPage()->find('css', 'textarea')->getHtml());
$matches = [];
preg_match('|^.*default_config_hash:.*$|m', $text, $matches);
$hash_line = trim($matches[0]);
$this->drupalGet('admin/config/development/configuration/report/module/search');
$this->clickLink('Revert to source');
$this->submitForm([], 'Revert');
// Verify that the hash was retained in the revert.
$this->drupalGet('admin/config/development/configuration/single/export/system.simple/search.settings');
$session = $this->assertSession();
$session->pageTextContains($hash_line);
$this->drupalGet('admin/config/development/configuration/report/module/search');
$this->assertReport('Search module', [], [], [], [], ['added']);
// Edit the plain_text filter from the filter UI and verify report.
// The filter_format config type uses a label key other than 'label'.
$this->drupalGet('admin/config/content/formats/manage/plain_text');
$this->submitForm([
'name' => 'New label',
], 'Save configuration');
$changed = ['filter.format.plain_text' => 'New label'];
$this->drupalGet('admin/config/development/configuration/report/type/filter_format');
$this->assertReport('Text format', [], [], $changed, []);
}
/**
* Asserts that the report page has the correct content.
*
* Assumes you are already on the report page.
*
* @param string $title
* Report title to check for.
* @param string[] $missing
* Array of items that should be listed as missing, name => label.
* @param string[] $added
* Array of items that should be listed as added, name => label.
* @param string[] $changed
* Array of items that should be listed as changed, name => label.
* @param string[] $inactive
* Array of items that should be listed as inactive, name => label.
* @param string[] $skip
* Array of report sections to skip checking.
*/
protected function assertReport($title, array $missing, array $added, array $changed, array $inactive, array $skip = []) {
$session = $this->assertSession();
$session->pageTextContains('Configuration updates report for ' . $title);
$session->pageTextContains('Generate new report');
if (!in_array('missing', $skip)) {
$session->pageTextContains('Missing configuration items');
if (count($missing)) {
foreach ($missing as $name => $label) {
$session->pageTextContains($name);
$session->pageTextContains($label);
}
$session->pageTextNotContains('None: all provided configuration items are in your active configuration.');
}
else {
$session->pageTextContains('None: all provided configuration items are in your active configuration.');
}
}
if (!in_array('inactive', $skip)) {
$session->pageTextContains('Inactive optional items');
if (count($inactive)) {
foreach ($inactive as $name => $label) {
$session->pageTextContains($name);
$session->pageTextContains($label);
}
$session->pageTextNotContains('None: all optional configuration items are in your active configuration.');
}
else {
$session->pageTextContains('None: all optional configuration items are in your active configuration.');
}
}
if (!in_array('added', $skip)) {
$session->pageTextContains('Added configuration items');
if (count($added)) {
foreach ($added as $name => $label) {
$session->pageTextContains($name);
$session->pageTextContains($label);
}
$session->pageTextNotContains('None: all active configuration items of this type were provided by modules, themes, or install profile.');
}
else {
$session->pageTextContains('None: all active configuration items of this type were provided by modules, themes, or install profile.');
}
}
if (!in_array('changed', $skip)) {
$session->pageTextContains('Changed configuration items');
if (count($changed)) {
foreach ($changed as $name => $label) {
$session->pageTextContains($name);
$session->pageTextContains($label);
}
$session->pageTextNotContains('None: no active configuration items differ from their current provided versions.');
}
else {
$session->pageTextContains('None: no active configuration items differ from their current provided versions.');
}
}
}
/**
* Asserts that the report is not shown.
*
* Assumes you are already on the report form page.
*/
protected function assertNoReport() {
$session = $this->assertSession();
$session->pageTextContains('Report type');
$session->pageTextContains('Full report');
$session->pageTextContains('Single configuration type');
$session->pageTextContains('Single module');
$session->pageTextContains('Single theme');
$session->pageTextContains('Installation profile');
$session->pageTextContains('Updates report');
$session->pageTextNotContains('Missing configuration items');
$session->pageTextNotContains('Added configuration items');
$session->pageTextNotContains('Changed configuration items');
$session->pageTextNotContains('Unchanged configuration items');
// Verify that certain report links are shown or not shown. For extensions,
// only extensions that have configuration should be shown.
// Modules.
$session->linkExists('Search');
$session->linkExists('Field');
$session->linkNotExists('Configuration Update Base');
// @todo this test fails since #2922511. Investigate.
// $session->linkNotExists('Configuration Update Reports');
// Themes.
$session->linkNotExists('Stark');
// Profiles.
$session->linkExists('Testing');
// Configuration types.
$session->linkExists('Everything');
$session->linkExists('Simple configuration');
$session->linkExists('Search page');
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Drupal\config_update;
/**
* Defines an interface for deleting config items.
*/
interface ConfigDeleteInterface {
/**
* Name of the event triggered before configuration delete.
*
* @see \Drupal\config_update\ConfigRevertEvent
* @see \Drupal\config_update\ConfigDeleteInterface::delete()
*/
const PRE_DELETE = 'config_update.pre_delete';
/**
* Name of the event triggered on configuration delete.
*
* @see \Drupal\config_update\ConfigRevertEvent
* @see \Drupal\config_update\ConfigDeleteInterface::delete()
*/
const DELETE = 'config_update.delete';
/**
* Deletes a configuration item.
*
* This action triggers the ConfigDeleteInterface::PRE_DELETE and
* ConfigDeleteInterface::DELETE events if the configuration could be deleted.
*
* @param string $type
* The type of configuration.
* @param string $name
* The name of the config item, without the prefix.
*
* @return bool
* TRUE if the operation succeeded; FALSE if the base configuration could
* not be found to delete. May also throw exceptions if there is a
* problem during deleting the configuration.
*
* @see \Drupal\config_update\ConfigDeleteInterface::PRE_DELETE
* @see \Drupal\config_update\ConfigDeleteInterface::DELETE
*/
public function delete($type, $name);
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Drupal\config_update;
/**
* Defines an interface for config differences.
*/
interface ConfigDiffInterface {
/**
* Decides if two configuration arrays are considered to be the same.
*
* The two arrays are considered to be the same if, after "normalizing", they
* have the same keys and values. It is up to the particular implementing
* class to decide what normalizing means.
*
* @param array|null $source
* Source config.
* @param array|null $target
* Target config.
*
* @return bool
* TRUE if the source and target are the same, and FALSE if they are
* different.
*/
public function same($source, $target);
/**
* Calculates differences between config.
*
* The two arrays are "normalized" and split into lines to compare
* differences. It is up to the particular implementing class to decide what
* normalizing means.
*
* @param array|null $source
* Source config.
* @param array|null $target
* Target config.
*
* @return \Drupal\Component\Diff\Diff
* Diff object for displaying line-by-line differences between source and
* target config.
*/
public function diff($source, $target);
}

View File

@@ -0,0 +1,195 @@
<?php
namespace Drupal\config_update;
use Drupal\Component\Diff\Diff;
use Drupal\Component\Serialization\Yaml;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
/**
* Provides methods related to config differences.
*/
class ConfigDiffer implements ConfigDiffInterface {
use StringTranslationTrait;
/**
* List of elements to ignore on top level when comparing config.
*
* @var string[]
*
* @see ConfigDiffer::format().
*/
protected $ignore;
/**
* Prefix to use to indicate config hierarchy.
*
* @var string
*
* @see ConfigDiffer::format().
*/
protected $hierarchyPrefix;
/**
* Prefix to use to indicate config values.
*
* @var string
*
* @see ConfigDiffer::format().
*/
protected $valuePrefix;
/**
* Constructs a ConfigDiffer.
*
* @param \Drupal\Core\StringTranslation\TranslationInterface $translation
* String translation service.
* @param string[] $ignore
* Config components to ignore at the top level.
* @param string $hierarchy_prefix
* Prefix to use in diffs for array hierarchy.
* @param string $value_prefix
* Prefix to use in diffs for array value.
*/
public function __construct(TranslationInterface $translation, array $ignore = ['uuid', '_core'], $hierarchy_prefix = '::', $value_prefix = ' : ') {
$this->stringTranslation = $translation;
$this->hierarchyPrefix = $hierarchy_prefix;
$this->valuePrefix = $value_prefix;
$this->ignore = $ignore;
}
/**
* Normalizes config for comparison.
*
* Removes elements in the ignore list from the top level of configuration,
* and at each level of the array, removes empty arrays and sorts by array
* key, so that config from different storage can be compared meaningfully.
*
* @param array|null $config
* Configuration array to normalize.
*
* @return array
* Normalized configuration array.
*
* @see ConfigDiffer::format()
* @see ConfigDiffer::$ignore
*/
protected function normalize($config) {
if (empty($config)) {
return [];
}
// Remove "ignore" elements, only at the top level.
foreach ($this->ignore as $element) {
unset($config[$element]);
}
// Recursively normalize and return.
return $this->normalizeArray($config);
}
/**
* Recursively sorts an array by key, and removes empty arrays.
*
* @param array $array
* An array to normalize.
*
* @return array
* An array that is sorted by key, at each level of the array, with empty
* arrays removed.
*/
protected function normalizeArray(array $array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$new = $this->normalizeArray($value);
if (count($new)) {
$array[$key] = $new;
}
else {
unset($array[$key]);
}
}
}
ksort($array);
return $array;
}
/**
* {@inheritdoc}
*/
public function same($source, $target) {
$source = $this->normalize($source);
$target = $this->normalize($target);
return $source === $target;
}
/**
* Formats config for showing differences.
*
* To compute differences, we need to separate the config into lines and use
* line-by-line differentiator. The obvious way to split into lines is:
* @code
* explode("\n", Yaml::encode($config))
* @endcode
* But this would highlight meaningless differences due to the often different
* order of config files, and also loses the indentation and context of the
* config hierarchy when differences are computed, making the difference
* difficult to interpret.
*
* So, what we do instead is to take the YAML hierarchy and format it so that
* the hierarchy is shown on each line. So, if you're in element
* $config['foo']['bar'] and the value is 'value', you will see
* 'foo::bar : value'.
*
* @param array $config
* Config array to format. Normalize it first if you want to do diffs.
* @param string $prefix
* (optional) When called recursively, the prefix to put on each line. Omit
* when initially calling this function.
*
* @return string[]
* Array of config lines formatted so that a line-by-line diff will show the
* context in each line, and meaningful differences will be computed.
*
* @see ConfigDiffer::normalize()
* @see ConfigDiffer::$hierarchyPrefix
* @see ConfigDiffer::$valuePrefix
*/
protected function format(array $config, $prefix = '') {
$lines = [];
foreach ($config as $key => $value) {
$section_prefix = ($prefix) ? $prefix . $this->hierarchyPrefix . $key : $key;
if (is_array($value)) {
$lines[] = $section_prefix;
$newlines = $this->format($value, $section_prefix);
foreach ($newlines as $line) {
$lines[] = $line;
}
}
else {
$lines[] = $section_prefix . $this->valuePrefix . Yaml::encode($value);
}
}
return $lines;
}
/**
* {@inheritdoc}
*/
public function diff($source, $target) {
$source = $this->normalize($source);
$target = $this->normalize($target);
$source_lines = $this->format($source);
$target_lines = $this->format($target);
return new Diff($source_lines, $target_lines);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Drupal\config_update;
/**
* Defines an extended interface for listing configuration.
*/
interface ConfigListByProviderInterface extends ConfigListInterface {
/**
* Returns the provider of a given config object.
*
* @param string $name
* Name of the config object.
*
* @return string[]
* Array containing the type of extension providing this config object as
* its first element (module, theme, profile), and the name of the provider
* as its second element. NULL if unknown.
*/
public function getConfigProvider($name);
/**
* Lists the providers of a given type that actually have configuration.
*
* @param string $type
* Type of extension (module, theme, profile).
* @param string $name
* Machine name of extension.
*
* @return bool
* TRUE if the extension has either install or optional config, and FALSE
* if it does not.
*/
public function providerHasConfig($type, $name);
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Drupal\config_update;
/**
* Defines an interface for config listings.
*/
interface ConfigListInterface {
/**
* Lists the types of configuration available on the system.
*
* @return \Drupal\Core\Entity\EntityTypeInterface[]
* Array of entity type definitions, keyed by machine name of the type.
*/
public function listTypes();
/**
* Returns the entity type object for a given config type name.
*
* @param string $name
* Config entity type machine name.
*
* @return \Drupal\Core\Entity\EntityTypeInterface
* Entity type object with machine name $name.
*/
public function getType($name);
/**
* Returns the entity type object for a given config prefix.
*
* @param string $prefix
* Config prefix.
*
* @return \Drupal\Core\Entity\EntityTypeInterface
* Entity type object corresponding to $prefix.
*/
public function getTypeByPrefix($prefix);
/**
* Returns the config type name for a given config object.
*
* @param string $name
* Name of the config object.
*
* @return string
* Name of the config type that this is an instance of, determined by
* prefix. NULL for simple configuration.
*/
public function getTypeNameByConfigName($name);
/**
* Lists the config objects in active and extension storage.
*
* @param string $list_type
* Type of list to make: 'type', 'module', 'theme', or 'profile'.
* @param string $name
* Machine name of a configuration type, module, or theme to generate the
* list for. Ignored for profile, since that uses the active profile. Use
* type 'system.simple' for simple config, and 'system.all' to list all
* config items.
*
* @return array
* Array whose first element is the list of config objects in active
* storage, second is the list of config objects in extension storage,
* and third is the list of optional config objects in extension storage
* (the ones with dependencies from config/optional directories).
* Note that for everything except 'type' lists, the active storage list
* includes all configuration items in the system, not limited to ones from
* this module, theme, or profile.
*/
public function listConfig($list_type, $name);
}

View File

@@ -0,0 +1,254 @@
<?php
namespace Drupal\config_update;
use Drupal\Core\Config\ExtensionInstallStorage;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\Extension;
use Drupal\Core\Site\Settings;
/**
* Provides methods related to config listing.
*/
class ConfigLister implements ConfigListInterface {
/**
* List of current config entity types, keyed by prefix.
*
* This is not set up until ConfigLister::listTypes() has been called.
*
* @var string[]
*/
protected $typesByPrefix = [];
/**
* List of current config entity type definitions, keyed by entity type.
*
* This is not set up until ConfigLister::listTypes() has been called.
*
* @var \Drupal\Core\Entity\EntityTypeInterface[]
*/
protected $definitions = [];
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityManager;
/**
* The active config storage.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $activeConfigStorage;
/**
* The extension config storage.
*
* @var \Drupal\Core\Config\ExtensionInstallStorage
*/
protected $extensionConfigStorage;
/**
* The extension config storage for optional config.
*
* @var \Drupal\Core\Config\ExtensionInstallStorage
*/
protected $extensionOptionalConfigStorage;
/**
* Constructs a ConfigLister.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Config\StorageInterface $active_config_storage
* The active config storage.
* @param \Drupal\Core\Config\ExtensionInstallStorage $extension_config_storage
* The extension config storage.
* @param \Drupal\Core\Config\ExtensionInstallStorage $extension_optional_config_storage
* The extension config storage for optional config items.
*/
public function __construct(EntityTypeManagerInterface $entity_manager, StorageInterface $active_config_storage, ExtensionInstallStorage $extension_config_storage, ExtensionInstallStorage $extension_optional_config_storage) {
$this->entityManager = $entity_manager;
$this->activeConfigStorage = $active_config_storage;
$this->extensionConfigStorage = $extension_config_storage;
$this->extensionOptionalConfigStorage = $extension_optional_config_storage;
}
/**
* Sets up and returns the entity definitions list.
*/
public function listTypes() {
// Return list if it has already been calculated.
if (count($this->definitions)) {
return $this->definitions;
}
// Calculate and return the list.
foreach ($this->entityManager->getDefinitions() as $entity_type => $definition) {
if ($definition->entityClassImplements('Drupal\Core\Config\Entity\ConfigEntityInterface')) {
$this->definitions[$entity_type] = $definition;
$prefix = $definition->getConfigPrefix();
$this->typesByPrefix[$prefix] = $entity_type;
}
}
ksort($this->definitions);
return $this->definitions;
}
/**
* {@inheritdoc}
*/
public function getType($name) {
$definitions = $this->listTypes();
return $definitions[$name] ?? NULL;
}
/**
* {@inheritdoc}
*/
public function getTypeByPrefix($prefix) {
$definitions = $this->listTypes();
return isset($this->typesByPrefix[$prefix]) ? $definitions[$this->typesByPrefix[$prefix]] : NULL;
}
/**
* {@inheritdoc}
*/
public function getTypeNameByConfigName($name) {
$definitions = $this->listTypes();
foreach ($this->typesByPrefix as $prefix => $entity_type) {
if (strpos($name, $prefix . '.') === 0) {
return $entity_type;
}
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function listConfig($list_type, $name) {
$active_list = [];
$install_list = [];
$optional_list = [];
$definitions = $this->listTypes();
switch ($list_type) {
case 'type':
if ($name == 'system.all') {
$active_list = $this->activeConfigStorage->listAll();
$install_list = $this->extensionConfigStorage->listAll();
$optional_list = $this->extensionOptionalConfigStorage->listAll();
}
elseif ($name == 'system.simple') {
// Listing is done by prefixes, and simple config doesn't have one.
// So list all and filter out all known prefixes.
$active_list = $this->omitKnownPrefixes($this->activeConfigStorage->listAll());
$install_list = $this->omitKnownPrefixes($this->extensionConfigStorage->listAll());
$optional_list = $this->omitKnownPrefixes($this->extensionOptionalConfigStorage->listAll());
}
elseif (isset($this->definitions[$name])) {
$definition = $this->definitions[$name];
$prefix = $definition->getConfigPrefix();
$active_list = $this->activeConfigStorage->listAll($prefix);
$install_list = $this->extensionConfigStorage->listAll($prefix);
$optional_list = $this->extensionOptionalConfigStorage->listAll($prefix);
}
break;
case 'profile':
$name = $this->getProfileName();
// Intentional fall-through here to the 'module' or 'theme' case.
case 'module':
case 'theme':
$active_list = $this->activeConfigStorage->listAll();
$install_list = $this->listProvidedItems($list_type, $name);
$optional_list = $this->listProvidedItems($list_type, $name, TRUE);
break;
}
// This only seems to be a problem in unit tests, where a mock object
// is returning NULL instead of an empty array for some reason.
if (!is_array($optional_list)) {
$optional_list = [];
}
return [$active_list, $install_list, $optional_list];
}
/**
* Returns a list of the install storage items for an extension.
*
* @param string $type
* Type of extension ('module', etc.).
* @param string $name
* Machine name of extension.
* @param bool $do_optional
* FALSE (default) to list config/install items, TRUE to list
* config/optional items.
*
* @return string[]
* List of config items provided by this extension.
*/
protected function listProvidedItems($type, $name, $do_optional = FALSE) {
// @todo Inject this dependency in the constructor.
// @phpstan-ignore-next-line as it's a dynamic service call.
$pathname = \Drupal::service("extension.list.$type")->getPathname($name);
// @phpstan-ignore-next-line as $this->root failing on previous major.
$component = new Extension(\Drupal::root(), $type, $pathname);
if ($do_optional) {
$names = $this->extensionOptionalConfigStorage->getComponentNames([$component]);
}
else {
$names = $this->extensionConfigStorage->getComponentNames([$component]);
}
return array_keys($names);
}
/**
* Omits config with known prefixes from a list of config names.
*/
protected function omitKnownPrefixes($list) {
$prefixes = array_keys($this->typesByPrefix);
$list = array_combine($list, $list);
foreach ($list as $name) {
foreach ($prefixes as $prefix) {
if (strpos($name, $prefix . '.') === 0) {
unset($list[$name]);
}
}
}
return array_values($list);
}
/**
* Returns the name of the install profile.
*
* For backwards compatibility with pre/post 8.3.x, tries to get it from
* either configuration or settings.
*
* @return string
* The name of the install profile.
*/
protected function getProfileName() {
// Code adapted from DrupalKernel::getInstalProfile() in Core.
// In Core 8.3.x or later, read from config.
$config = $this->activeConfigStorage->read('core.extension');
if (!empty($config['profile'])) {
return $config['profile'];
}
else {
// If system_update_8300() has not yet run, use settings.
return Settings::get('install_profile');
}
}
}

View File

@@ -0,0 +1,151 @@
<?php
namespace Drupal\config_update;
use Drupal\Core\Config\ExtensionInstallStorage;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
/**
* Provides methods related to config listing, including provider calculation.
*/
class ConfigListerWithProviders extends ConfigLister implements ConfigListByProviderInterface {
/**
* List of providers of config, keyed by config item name.
*
* The array elements are each arrays, with the type of extension providing
* the config object as the first element (module, theme, profile), and the
* name of the provider as the second element.
*
* This is not set up until ConfigListerWithProviders::listProviders() has
* been called.
*
* @var array
*/
protected $providers = [];
/**
* List of extensions that provide configuration, keyed by type.
*
* This is not set up until ConfigListerWithProviders::listProviders() has
* been called.
*
* @var array
*/
protected $extensionsWithConfig = [];
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* Constructs a ConfigListerWithProviders.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Config\StorageInterface $active_config_storage
* The active config storage.
* @param \Drupal\Core\Config\ExtensionInstallStorage $extension_config_storage
* The extension config storage.
* @param \Drupal\Core\Config\ExtensionInstallStorage $extension_optional_config_storage
* The extension config storage for optional config items.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
* The theme handler.
*/
public function __construct(EntityTypeManagerInterface $entity_manager, StorageInterface $active_config_storage, ExtensionInstallStorage $extension_config_storage, ExtensionInstallStorage $extension_optional_config_storage, ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler) {
$this->entityManager = $entity_manager;
$this->activeConfigStorage = $active_config_storage;
$this->extensionConfigStorage = $extension_config_storage;
$this->extensionOptionalConfigStorage = $extension_optional_config_storage;
$this->moduleHandler = $module_handler;
$this->themeHandler = $theme_handler;
}
/**
* Sets up and returns the config providers list.
*/
public function listProviders() {
// Return the list if it has already been set up.
if (count($this->providers)) {
return $this->providers;
}
// Calculate the list of who provides which config, if it hasn't been set
// up yet. List all of the profile, modules, and themes. Profile needs to
// come last, so it will override config in modules and themes in our list,
// matching what the config system does.
$extensionsToDo = [];
$profile = $this->getProfileName();
$modules = $this->moduleHandler->getModuleList();
foreach ($modules as $machine_name => $module) {
if ($machine_name != $profile) {
$extensionsToDo[] = ['module', $machine_name];
}
}
$themes = $this->themeHandler->listInfo();
foreach ($themes as $machine_name => $theme) {
$extensionsToDo[] = ['theme', $machine_name];
}
$extensionsToDo[] = ['profile', $profile];
// For each extension, figure out if it has config, and make an index of
// config item => provider.
$this->extensionsWithConfig = [
'profile' => [],
'module' => [],
'theme' => [],
];
foreach ($extensionsToDo as $item) {
$type = $item[0];
$name = $item[1];
$configs = array_merge($this->listProvidedItems($type, $name),
$this->listProvidedItems($type, $name, TRUE));
if (!empty($configs)) {
$this->extensionsWithConfig[$type][$name] = $name;
foreach ($configs as $config) {
$this->providers[$config] = [$type, $name];
}
}
}
return $this->providers;
}
/**
* {@inheritdoc}
*/
public function getConfigProvider($name) {
$providers = $this->listProviders();
return (isset($providers[$name])) ? $providers[$name] : NULL;
}
/**
* {@inheritdoc}
*/
public function providerHasConfig($type, $name) {
// Make sure the list of extensions with configuration has been generated.
$this->listProviders();
return isset($this->extensionsWithConfig[$type][$name]);
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace Drupal\config_update;
use Drupal\Component\EventDispatcher\Event;
/**
* Event context class for configuration pre-revert/pre-import events.
*
* This class is passed in as the event when the
* \Drupal\config_update\ConfigRevertInterface::PRE_IMPORT and
* \Drupal\config_update\ConfigRevertInterface::PRE_REVERT events are triggered.
*/
class ConfigPreRevertEvent extends Event {
/**
* The type of configuration that is being imported or reverted.
*
* @var string
*/
protected $type;
/**
* The name of the config item being imported or reverted, without prefix.
*
* @var string
*/
protected $name;
/**
* The current configuration to be applied.
*
* @var array
*/
protected $value;
/**
* The active configuration.
*
* Only available on \Drupal\config_update\ConfigRevertInterface::PRE_REVERT.
*
* @var array|null
*/
protected $active;
/**
* Constructs a new ConfigPreRevertEvent.
*
* @param string $type
* The type of configuration being imported or reverted.
* @param string $name
* The name of the config item being imported/reverted, without prefix.
* @param array $value
* The current configuration.
* @param array|null $active
* The active configuration.
*/
public function __construct($type, $name, array $value, $active) {
$this->type = $type;
$this->name = $name;
$this->active = $active;
$this->value = $value;
}
/**
* Returns the type of configuration being imported or reverted.
*
* @return string
* The type of configuration, either 'system.simple' or a config entity
* type machine name.
*/
public function getType() {
return $this->type;
}
/**
* Returns the name of the config item, without prefix.
*
* @return string
* The name of the config item being imported/reverted/deleted, with the
* prefix.
*/
public function getName() {
return $this->name;
}
/**
* Returns the current configuration value to be applied.
*
* @return array
* The configuration value.
*/
public function getValue() {
return $this->value;
}
/**
* Set the configuration value to import or revert to after the event.
*
* This new value will be imported in place of the configuration value
* originally read from the filesystem.
*
* @param array $value
* The configuration value.
*/
public function setValue(array $value) {
$this->value = $value;
}
/**
* Returns the active configuration.
*
* Only available on \Drupal\config_update\ConfigRevertInterface::PRE_REVERT.
*
* @return array|null
* The active configuration.
*/
public function getActive() {
return $this->active;
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Drupal\config_update;
use Drupal\Component\EventDispatcher\Event;
/**
* Event context class for configuration revert/import events.
*
* This class is passed in as the event when the
* \Drupal\config_update\ConfigRevertInterface::IMPORT,
* \Drupal\config_update\ConfigDeleteInterface::PRE_DELETE,
* \Drupal\config_update\ConfigDeleteInterface::DELETE, and
* \Drupal\config_update\ConfigRevertInterface::REVERT events are triggered.
*/
class ConfigRevertEvent extends Event {
/**
* The type of configuration that is being imported or reverted.
*
* @var string
*/
protected $type;
/**
* The name of the config item being imported or reverted, without prefix.
*
* @var string
*/
protected $name;
/**
* Constructs a new ConfigRevertEvent.
*
* @param string $type
* The type of configuration being imported or reverted.
* @param string $name
* The name of the config item being imported/reverted, without prefix.
*/
public function __construct($type, $name) {
$this->type = $type;
$this->name = $name;
}
/**
* Returns the type of configuration being imported or reverted.
*
* @return string
* The type of configuration, either 'system.simple' or a config entity
* type machine name.
*/
public function getType() {
return $this->type;
}
/**
* Returns the name of the config item, without prefix.
*
* @return string
* The name of the config item being imported/reverted/deleted, with the
* prefix.
*/
public function getName() {
return $this->name;
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace Drupal\config_update;
/**
* Defines an interface for config import and revert operations.
*/
interface ConfigRevertInterface {
/**
* Name of the event triggered before configuration import.
*
* @see \Drupal\config_update\ConfigPreRevertEvent
* @see \Drupal\config_update\ConfigRevertInterface::import()
*/
const PRE_IMPORT = 'config_update.pre_import';
/**
* Name of the event triggered on configuration import.
*
* @see \Drupal\config_update\ConfigRevertEvent
* @see \Drupal\config_update\ConfigRevertInterface::import()
*/
const IMPORT = 'config_update.import';
/**
* Name of the event triggered before configuration revert.
*
* @see \Drupal\config_update\ConfigPreRevertEvent
* @see \Drupal\config_update\ConfigRevertInterface::revert()
*/
const PRE_REVERT = 'config_update.pre_revert';
/**
* Name of the event triggered on configuration revert.
*
* @see \Drupal\config_update\ConfigRevertEvent
* @see \Drupal\config_update\ConfigRevertInterface::revert()
*/
const REVERT = 'config_update.revert';
/**
* Imports configuration from extension storage to active storage.
*
* This action triggers the ConfigRevertInterface::PRE_IMPORT and
* ConfigRevertInterface::IMPORT events if the configuration could be
* imported.
*
* @param string $type
* The type of configuration.
* @param string $name
* The name of the config item, without the prefix.
*
* @return bool
* TRUE if the operation succeeded; FALSE if the configuration could not
* be found to import. May also throw exceptions if there is a problem
* during saving the configuration.
*
* @see \Drupal\config_update\ConfigRevertInterface::PRE_IMPORT
* @see \Drupal\config_update\ConfigRevertInterface::IMPORT
*/
public function import($type, $name);
/**
* Reverts configuration to the value from extension storage.
*
* This action triggers the ConfigRevertInterface::PRE_REVERT and
* ConfigRevertInterface::REVERT events if the configuration could be
* reverted.
*
* @param string $type
* The type of configuration.
* @param string $name
* The name of the config item, without the prefix.
*
* @return bool
* TRUE if the operation succeeded; FALSE if the base configuration could
* not be found to revert to. May also throw exceptions if there is a
* problem during saving the configuration.
*
* @see \Drupal\config_update\ConfigRevertInterface::PRE_REVERT
* @see \Drupal\config_update\ConfigRevertInterface::REVERT
*/
public function revert($type, $name);
/**
* Gets the current active value of configuration.
*
* @param string $type
* The type of configuration. Or pass '' to indicate that $name is the full
* name.
* @param string $name
* The name of the config item, without the prefix.
*
* @return array
* The configuration value, or FALSE if it is not found.
*/
public function getFromActive($type, $name);
/**
* Gets the extension storage value of configuration.
*
* This is the value from a file in the config/install or config/optional
* directory of a module, theme, or install profile.
*
* @param string $type
* The type of configuration. Or pass '' to indicate that $name is the full
* name.
* @param string $name
* The name of the config item, without the prefix.
*
* @return array|false
* The configuration value, or FALSE if it could not be located.
*/
public function getFromExtension($type, $name);
}

View File

@@ -0,0 +1,278 @@
<?php
namespace Drupal\config_update;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* Provides methods related to config reverting, deleting, and importing.
*
* In this class, when any import or revert operation is requested, the
* configuration that is being reverted or imported is searched for in both the
* config/install repository and config/optional. This happens automatically.
*/
class ConfigReverter implements ConfigRevertInterface, ConfigDeleteInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityManager;
/**
* The active config storage.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $activeConfigStorage;
/**
* The extension config storage for config/install config items.
*
* @var \Drupal\Core\Config\StorageInterface
*/
protected $extensionConfigStorage;
/**
* The extension config storage for config/optional config items.
*
* @var \Drupal\Core\Config\ExtensionInstallStorage
*/
protected $extensionOptionalConfigStorage;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The event dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $dispatcher;
/**
* Constructs a ConfigReverter.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Config\StorageInterface $active_config_storage
* The active config storage.
* @param \Drupal\Core\Config\StorageInterface $extension_config_storage
* The extension config storage.
* @param \Drupal\Core\Config\StorageInterface $extension_optional_config_storage
* The extension config storage for optional config items.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
* The event dispatcher.
*/
public function __construct(EntityTypeManagerInterface $entity_manager, StorageInterface $active_config_storage, StorageInterface $extension_config_storage, StorageInterface $extension_optional_config_storage, ConfigFactoryInterface $config_factory, EventDispatcherInterface $dispatcher) {
$this->entityManager = $entity_manager;
$this->activeConfigStorage = $active_config_storage;
$this->extensionConfigStorage = $extension_config_storage;
$this->extensionOptionalConfigStorage = $extension_optional_config_storage;
$this->configFactory = $config_factory;
$this->dispatcher = $dispatcher;
}
/**
* {@inheritdoc}
*/
public function import($type, $name) {
// Read the config from the file. Note: Do not call getFromExtension() here
// because we need $full_name below.
$full_name = $this->getFullName($type, $name);
$value = FALSE;
if ($full_name) {
$value = $this->extensionConfigStorage->read($full_name);
if (!$value) {
$value = $this->extensionOptionalConfigStorage->read($full_name);
}
}
if (!$value) {
return FALSE;
}
// Trigger an event to modify the configuration value.
$event = new ConfigPreRevertEvent($type, $name, $value, NULL);
$this->dispatcher->dispatch($event, ConfigRevertInterface::PRE_IMPORT);
$value = $event->getValue();
// Save it as a new config entity or simple config.
if ($type === 'system.simple') {
$this->configFactory->getEditable($full_name)->setData($value)->save();
}
else {
$entity_storage = $this->entityManager->getStorage($type);
$entity = $entity_storage->createFromStorageRecord($value);
$entity->save();
}
// Trigger an event notifying of this change.
$event = new ConfigRevertEvent($type, $name);
$this->dispatcher->dispatch($event, ConfigRevertInterface::IMPORT);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function revert($type, $name) {
// Read the config from the file. Note: Do not call getFromExtension() here
// because we need $full_name below.
$value = FALSE;
$full_name = $this->getFullName($type, $name);
if ($full_name) {
$value = $this->extensionConfigStorage->read($full_name);
if (!$value) {
$value = $this->extensionOptionalConfigStorage->read($full_name);
}
}
if (!$value) {
return FALSE;
}
// Make sure the configuration exists currently in active storage.
$active_value = $this->activeConfigStorage->read($full_name);
if (!$active_value) {
return FALSE;
}
// Trigger an event to modify the active configuration value.
$event = new ConfigPreRevertEvent($type, $name, $value, $active_value);
$this->dispatcher->dispatch($event, ConfigRevertInterface::PRE_REVERT);
$value = $event->getValue();
// Load the current config and replace the value, retaining the config
// hash (which is part of the _core config key's value).
if ($type === 'system.simple') {
$config = $this->configFactory->getEditable($full_name);
$core = $config->get('_core');
$config
->setData($value)
->set('_core', $core)
->save();
}
else {
$definition = $this->entityManager->getDefinition($type);
$id_key = $definition->getKey('id');
$id = $value[$id_key];
$entity_storage = $this->entityManager->getStorage($type);
$entity = $entity_storage->load($id);
$core = $entity->get('_core');
$entity = $entity_storage->updateFromStorageRecord($entity, $value);
$entity->set('_core', $core);
$entity->save();
}
// Trigger an event notifying of this change.
$event = new ConfigRevertEvent($type, $name);
$this->dispatcher->dispatch($event, ConfigRevertInterface::REVERT);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function delete($type, $name) {
$config = FALSE;
$full_name = $this->getFullName($type, $name);
if ($full_name) {
// Make sure the configuration exists currently in active storage.
if (!$this->activeConfigStorage->read($full_name)) {
return FALSE;
}
$config = $this->configFactory->getEditable($full_name);
}
if (!$config) {
return FALSE;
}
// Trigger an event notifying of this change.
$event = new ConfigRevertEvent($type, $name);
$this->dispatcher->dispatch($event, ConfigDeleteInterface::PRE_DELETE);
if ($type === 'system.simple') {
$config->delete();
}
else {
// Delete a config entity instance, updating all its dependents.
$definition = $this->entityManager->getDefinition($type);
$id = $config->get($definition->getKey('id'));
$entity_storage = $this->entityManager->getStorage($type);
$entity = $entity_storage->load($id);
if (!$entity) {
return FALSE;
}
$entity->delete();
}
// Trigger an event notifying of this change.
$event = new ConfigRevertEvent($type, $name);
$this->dispatcher->dispatch($event, ConfigDeleteInterface::DELETE);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getFromActive($type, $name) {
$full_name = $this->getFullName($type, $name);
if ($full_name) {
return $this->activeConfigStorage->read($full_name);
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function getFromExtension($type, $name) {
$value = FALSE;
$full_name = $this->getFullName($type, $name);
if ($full_name) {
$value = $this->extensionConfigStorage->read($full_name);
if (!$value) {
$value = $this->extensionOptionalConfigStorage->read($full_name);
}
}
return $value;
}
/**
* Returns the full name of a config item.
*
* @param string $type
* The config type, or '' to indicate $name is already prefixed.
* @param string $name
* The config name, without prefix.
*
* @return string
* The config item's full name, or FALSE if there is an error.
*/
protected function getFullName($type, $name) {
if ($type === 'system.simple' || !$type) {
return $name;
}
$definition = $this->entityManager->getDefinition($type);
if ($definition) {
$prefix = $definition->getConfigPrefix() . '.';
return $prefix . $name;
}
else {
return FALSE;
}
}
}

View File

@@ -0,0 +1,363 @@
<?php
namespace Drupal\Tests\config_update\Unit;
use Drupal\config_update\ConfigDiffer;
/**
* Tests the \Drupal\config_update\ConfigDiffer class.
*
* @group config_update
*
* @coversDefaultClass \Drupal\config_update\ConfigDiffer
*/
class ConfigDifferTest extends ConfigUpdateUnitTestBase {
/**
* The config differ to test.
*
* @var \Drupal\config_update\ConfigDiffer
*/
protected $configDiffer;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->configDiffer = new ConfigDiffer($this->getTranslationMock());
}
/**
* @covers \Drupal\config_update\ConfigDiffer::same
* @dataProvider sameProvider
*/
public function testSame($a, $b, $expected) {
$this->assertEquals($expected, $this->configDiffer->same($a, $b));
}
/**
* Data provider for self:testSame().
*/
public function sameProvider() {
$base = [
'uuid' => 'bar',
'a' => 'a',
'b' => 0,
'c' => [
'd' => TRUE,
'e' => FALSE,
'empty' => [],
],
];
return [
[$base, $base, TRUE],
// Add _core, omit uuid at top level. Should match, as both are removed
// in normalization process.
[
$base,
[
'_core' => 'foo',
'a' => 'a',
'b' => 0,
'c' => [
'd' => TRUE,
'e' => FALSE,
'empty' => [],
],
],
TRUE,
],
// Change order in top and deep level. Should match.
[
$base,
[
'uuid' => 'bar',
'b' => 0,
'a' => 'a',
'c' => [
'e' => FALSE,
'empty' => [],
'd' => TRUE,
],
],
TRUE,
],
// Add _core in deeper level. Should not match, as this is removed
// only at the top level during normalization.
[
$base,
[
'uuid' => 'bar',
'a' => 'a',
'b' => 0,
'c' => [
'_core' => 'do-not-use-this-key',
'd' => TRUE,
'e' => FALSE,
'empty' => [],
],
],
FALSE,
],
// Add uuid in deeper level. Should not match, as this is removed
// only at the top level during normalization.
[
$base,
[
'uuid' => 'bar',
'a' => 'a',
'b' => 0,
'c' => [
'd' => TRUE,
'e' => FALSE,
'uuid' => 'important',
'empty' => [],
],
],
FALSE,
],
// Omit a component. Should not match.
[
$base,
[
'uuid' => 'bar',
'a' => 'a',
'c' => [
'd' => TRUE,
'e' => FALSE,
'empty' => [],
],
],
FALSE,
],
// Add a component. Should not match.
[
$base,
[
'uuid' => 'bar',
'a' => 'a',
'b' => 0,
'c' => [
'd' => TRUE,
'e' => FALSE,
'empty' => [],
],
'f' => 'f',
],
FALSE,
],
// 0 should not match a string.
[
$base,
[
'_core' => 'foo',
'uuid' => 'bar',
'a' => 'a',
'b' => 'b',
'c' => [
'd' => TRUE,
'e' => FALSE,
'empty' => [],
],
],
FALSE,
],
// 0 should not match NULL.
[
$base,
[
'_core' => 'foo',
'uuid' => 'bar',
'a' => 'a',
'b' => NULL,
'c' => [
'd' => TRUE,
'e' => FALSE,
'empty' => [],
],
],
FALSE,
],
// FALSE should not match a string.
[
$base,
[
'_core' => 'foo',
'uuid' => 'bar',
'a' => 'a',
'b' => 0,
'c' => [
'd' => TRUE,
'e' => 'e',
'empty' => [],
],
],
FALSE,
],
// TRUE should not match a string.
[
$base,
[
'_core' => 'foo',
'uuid' => 'bar',
'a' => 'a',
'b' => 0,
'c' => [
'd' => 'd',
'e' => FALSE,
'empty' => [],
],
],
FALSE,
],
// Add an empty array at top, and remove at lower level. Should still
// match.
[
$base,
[
'_core' => 'foo',
'uuid' => 'bar',
'a' => 'a',
'b' => 0,
'c' => [
'd' => TRUE,
'e' => FALSE,
],
'empty_two' => [],
],
TRUE,
],
];
}
/**
* @covers \Drupal\config_update\ConfigDiffer::diff
*/
public function testDiff() {
$configOne = [
'uuid' => '1234-5678-90',
'id' => 'test.config.id',
'id_to_remove' => 'test.remove.id',
'type' => 'old_type',
'true_value' => TRUE,
'null_value' => NULL,
'nested_array' => [
'flat_array' => [
'value2',
'value1',
'value3',
],
'custom_key' => 'value',
],
];
$configTwo = [
'uuid' => '09-8765-4321',
'id' => 'test.config.id',
'type' => 'new_type',
'true_value' => FALSE,
'null_value' => FALSE,
'nested_array' => [
'flat_array' => [
'value2',
'value3',
],
'custom_key' => 'value',
'custom_key_2' => 'value2',
],
];
$edits = $this->configDiffer->diff($configOne, $configTwo)->getEdits();
$expectedEdits = [
[
'copy' => [
'orig' => [
'id : test.config.id',
],
'closing' => [
'id : test.config.id',
],
],
],
[
'delete' => [
'orig' => [
'id_to_remove : test.remove.id',
],
'closing' => FALSE,
],
],
[
'copy' => [
'orig' => [
'nested_array',
'nested_array::custom_key : value',
],
'closing' => [
'nested_array',
'nested_array::custom_key : value',
],
],
],
[
'add' => [
'orig' => FALSE,
'closing' => [
'nested_array::custom_key_2 : value2',
],
],
],
[
'copy' => [
'orig' => [
'nested_array::flat_array',
'nested_array::flat_array::0 : value2',
],
'closing' => [
'nested_array::flat_array',
'nested_array::flat_array::0 : value2',
],
],
],
[
'change' => [
'orig' => [
'nested_array::flat_array::1 : value1',
'nested_array::flat_array::2 : value3',
'null_value : null',
'true_value : true',
'type : old_type',
],
'closing' => [
'nested_array::flat_array::1 : value3',
'null_value : false',
'true_value : false',
'type : new_type',
],
],
],
];
$this->assertEquals(count($expectedEdits), count($edits));
/** @var \Drupal\Component\Diff\Engine\DiffOp $diffOp */
foreach ($edits as $index => $diffOp) {
$this->assertEquals($expectedEdits[$index][$diffOp->type]['orig'], $diffOp->orig);
$this->assertEquals($expectedEdits[$index][$diffOp->type]['closing'], $diffOp->closing);
}
}
}

View File

@@ -0,0 +1,304 @@
<?php
namespace Drupal\Tests\config_update\Unit;
/**
* Tests the \Drupal\config_update\ConfigListerWithProviders class.
*
* The methods from \Drupal\config_update\ConfigLister are also tested.
*
* @group config_update
*
* @coversDefaultClass \Drupal\config_update\ConfigListerWithProviders
*/
class ConfigListerTest extends ConfigUpdateUnitTestBase {
/**
* The config lister to test.
*
* @var \Drupal\config_update\ConfigListerWithProviders
*/
protected $configLister;
/**
* List of configuration by provider in the mocks.
*
* This is an array whose keys are provider names, and whose values are
* each an array containing the provider type, an array of config items
* mocked to be in config/install, and the same for config/optional. In
* all cases, the first item in the array of config items should be tested
* to be provided by that provider, and any others should not be there.
*
* @var array
*/
protected static $configProviderList = [
'foo_module' => [
'module',
['foo.barbaz.one', 'baz.bar.one'],
['foo.barbaz.two'],
],
'foo_theme' => ['theme', ['foo.bar.one'], ['foo.bar.two']],
'standard' => ['profile', ['baz.bar.one'], ['baz.bar.two']],
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$lister = $this->getMockBuilder('Drupal\config_update\ConfigListerWithProviders')
->setConstructorArgs([
$this->getEntityManagerMock(),
$this->getConfigStorageMock('active'),
$this->getConfigStorageMock('extension'),
$this->getConfigStorageMock('optional'),
$this->getModuleHandlerMock(),
$this->getThemeHandlerMock(),
])
->onlyMethods(['listProvidedItems', 'getProfileName'])
->getMock();
$lister->method('getProfileName')
->willReturn('standard');
$map = [];
foreach (self::$configProviderList as $provider => $info) {
// Info has: [type, install storage items, optional storage items].
// Map needs: [type, provider name, isOptional, [config items]].
$map[] = [$info[0], $provider, FALSE, $info[1]];
$map[] = [$info[0], $provider, TRUE, $info[2]];
}
$lister->method('listProvidedItems')
->willReturnMap($map);
$this->configLister = $lister;
}
/**
* @covers \Drupal\config_update\ConfigListerWithProviders::listConfig
* @dataProvider listConfigProvider
*/
public function testListConfig($a, $b, $expected) {
$this->assertEquals($expected, $this->configLister->listConfig($a, $b));
}
/**
* Data provider for self:testListConfig().
*/
public function listConfigProvider() {
return [
// Arguments are $list_type, $name, and return value is that list of
// configuration in active, extension, and optional storage.
['type', 'system.all',
[
[
'foo.bar.one',
'foo.bar.two',
'foo.bar.three',
'foo.barbaz.four',
'foo.barbaz.five',
'foo.barbaz.six',
'something.else',
'another.one',
],
[
'foo.bar.one',
'foo.bar.two',
'foo.bar.seven',
'foo.barbaz.four',
'foo.barnot.three',
'something.else',
],
['foo.barbaz.four'],
],
],
['type', 'system.simple',
[
['something.else', 'another.one'],
['foo.barnot.three', 'something.else'],
[],
],
],
['type', 'foo',
[
['foo.bar.one', 'foo.bar.two', 'foo.bar.three'],
['foo.bar.one', 'foo.bar.two', 'foo.bar.seven'],
[],
],
],
['type', 'unknown.type', [[], [], []]],
['profile', 'dummy',
[
[
'foo.bar.one',
'foo.bar.two',
'foo.bar.three',
'foo.barbaz.four',
'foo.barbaz.five',
'foo.barbaz.six',
'something.else',
'another.one',
],
['baz.bar.one'],
['baz.bar.two'],
],
],
['module', 'foo_module',
[
[
'foo.bar.one',
'foo.bar.two',
'foo.bar.three',
'foo.barbaz.four',
'foo.barbaz.five',
'foo.barbaz.six',
'something.else',
'another.one',
],
['foo.barbaz.one', 'baz.bar.one'],
['foo.barbaz.two'],
],
],
['theme', 'foo_theme',
[
[
'foo.bar.one',
'foo.bar.two',
'foo.bar.three',
'foo.barbaz.four',
'foo.barbaz.five',
'foo.barbaz.six',
'something.else',
'another.one',
],
['foo.bar.one'],
['foo.bar.two'],
],
],
];
}
/**
* @covers \Drupal\config_update\ConfigListerWithProviders::getType
*/
public function testGetType() {
$return = $this->configLister->getType('not_in_list');
$this->assertNull($return);
foreach ($this->entityDefinitionInformation as $info) {
$return = $this->configLister->getType($info['type']);
$this->assertEquals($return->getConfigPrefix(), $info['prefix']);
}
}
/**
* @covers \Drupal\config_update\ConfigListerWithProviders::getTypeByPrefix
*/
public function testGetTypeByPrefix() {
$return = $this->configLister->getTypeByPrefix('not_in_list');
$this->assertNull($return);
foreach ($this->entityDefinitionInformation as $info) {
$return = $this->configLister->getTypeByPrefix($info['prefix']);
$this->assertEquals($return->getConfigPrefix(), $info['prefix']);
}
}
/**
* @covers \Drupal\config_update\ConfigListerWithProviders::getTypeNameByConfigName
*/
public function testGetTypeNameByConfigName() {
$return = $this->configLister->getTypeNameByConfigName('not_in_list');
$this->assertNull($return);
foreach ($this->entityDefinitionInformation as $info) {
$return = $this->configLister->getTypeNameByConfigName($info['prefix'] . '.something');
$this->assertEquals($return, $info['type']);
}
}
/**
* @covers \Drupal\config_update\ConfigListerWithProviders::listTypes
*/
public function testListTypes() {
$return = $this->configLister->listTypes();
// Should return an array in sorted order, of just the config entities
// that $this->getEntityManagerMock() set up.
$expected = ['bar' => 'foo.barbaz', 'baz' => 'baz.foo', 'foo' => 'foo.bar'];
$this->assertEquals(array_keys($return), array_keys($expected));
foreach ($return as $key => $definition) {
$this->assertTrue($definition->entityClassImplements('Drupal\Core\Config\Entity\ConfigEntityInterface'));
$this->assertEquals($definition->getConfigPrefix(), $expected[$key]);
}
}
/**
* @covers \Drupal\config_update\ConfigListerWithProviders::listProviders
*/
public function testListProviders() {
// This method's return value is not sorted in any particular way.
$return = $this->configLister->listProviders();
$expected = [];
foreach (self::$configProviderList as $provider => $info) {
// Info has: [type, install storage items, optional storage items], with
// only the first item in each list that should be present in
// listProviders().
// Expected needs: key is item name, value is [type, provider name].
$expected[$info[1][0]] = [$info[0], $provider];
$expected[$info[2][0]] = [$info[0], $provider];
}
ksort($return);
ksort($expected);
$this->assertEquals($return, $expected);
}
/**
* @covers \Drupal\config_update\ConfigListerWithProviders::getConfigProvider
* @dataProvider getConfigProviderProvider
*/
public function testGetConfigProvider($a, $expected) {
$this->assertEquals($expected, $this->configLister->getConfigProvider($a));
}
/**
* Data provider for self:testGetConfigProvider().
*/
public static function getConfigProviderProvider(): array {
$values = [];
foreach (self::$configProviderList as $provider => $info) {
// Info has: [type, install storage items, optional storage items], with
// the first item in each list that should be OK to test with
// getConfigProvider().
// Values needs: [item, [type, provider name]].
$values[] = [$info[1][0], [$info[0], $provider]];
$values[] = [$info[2][0], [$info[0], $provider]];
}
$values[] = ['not.a.config.item', NULL];
return $values;
}
/**
* @covers \Drupal\config_update\ConfigListerWithProviders::providerHasConfig
* @dataProvider providerHasConfigProvider
*/
public function testProviderHasConfig($a, $b, $expected) {
$this->assertEquals($expected, $this->configLister->providerHasConfig($a, $b));
}
/**
* Data provider for self:testProviderHasConfig().
*/
public static function providerHasConfigProvider(): array {
$values = [];
foreach (self::$configProviderList as $provider => $info) {
// Info has: [type, install storage items, optional storage items].
// Values needs: [type, provider name, TRUE] for valid providers,
// change the last to FALSE for invalid providers.
$values[] = [$info[0], $provider, TRUE];
$values[] = [$info[0], $provider . '_suffix', FALSE];
}
$values[] = ['invalid_type', 'foo_module', FALSE];
return $values;
}
}

View File

@@ -0,0 +1,415 @@
<?php
namespace Drupal\Tests\config_update\Unit;
use Drupal\config_update\ConfigDeleteInterface;
use Drupal\config_update\ConfigReverter;
use Drupal\config_update\ConfigRevertInterface;
/**
* Tests the \Drupal\config_update\ConfigReverter class.
*
* @group config_update
*
* @coversDefaultClass \Drupal\config_update\ConfigReverter
*/
class ConfigReverterTest extends ConfigUpdateUnitTestBase {
/**
* The config reverter to test.
*
* @var \Drupal\config_update\ConfigReverter
*/
protected $configReverter;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->configReverter = new ConfigReverter(
$this->getEntityManagerMock(),
$this->getConfigStorageMock('active'),
$this->getConfigStorageMock('extension'),
$this->getConfigStorageMock('optional'),
$this->getConfigFactoryMock(),
$this->getEventDispatcherMock());
}
/**
* @covers \Drupal\config_update\ConfigReverter::getFromActive
* @dataProvider getFromActiveProvider
*/
public function testGetFromActive($a, $b, $expected) {
$this->assertEquals($expected, $this->configReverter->getFromActive($a, $b));
}
/**
* Data provider for self:testGetFromActive().
*/
public function getFromActiveProvider() {
return [
// Arguments are $type, $name, and return value is the config.
// Some config items that are already prefixed.
['', 'foo.bar.one', ['foo.bar.one' => 'active', 'id' => 'one']],
['system.simple', 'foo.bar.one',
['foo.bar.one' => 'active', 'id' => 'one'],
],
// Config item with a defined entity definition prefix. Entity type 'foo'
// has prefix 'foo.bar'.
['foo', 'one', ['foo.bar.one' => 'active', 'id' => 'one']],
// Unknown type. This should not generate a call into the config read,
// so should not return the known value.
['unknown', 'foo.bar.one', FALSE],
// Missing configuration. Config mock is configured to return FALSE for
// this particular config name.
['system.simple', 'missing', FALSE],
];
}
/**
* @covers \Drupal\config_update\ConfigReverter::getFromExtension
* @dataProvider getFromExtensionProvider
*/
public function testGetFromExtension($a, $b, $expected) {
$this->assertEquals($expected, $this->configReverter->getFromExtension($a, $b));
}
/**
* Data provider for self:testGetFromExtension().
*/
public function getFromExtensionProvider() {
return [
// Arguments are $type, $name, and return value is the config.
// Some config items that are already prefixed, and exist in the mock
// extension storage.
['', 'in.extension', ['in.extension' => 'extension']],
['system.simple', 'in.extension', ['in.extension' => 'extension']],
// Config item with a defined entity definition prefix. Entity type 'foo'
// has prefix 'foo.bar'.
['foo', 'one', ['foo.bar.one' => 'extension', 'id' => 'one']],
// One that exists in both extension and optional storage.
['system.simple', 'in.both', ['in.both' => 'extension']],
// One that exists only in optional storage.
['system.simple', 'in.optional', ['in.optional' => 'optional']],
// Unknown type. This should not generate a call into the config read,
// so should not return the known value.
['unknown', 'in.extension', FALSE],
// Missing configuration. Storage mock is configured to return FALSE for
// this particular config name.
['system.simple', 'missing2', FALSE],
];
}
/**
* @covers \Drupal\config_update\ConfigReverter::import
* @dataProvider importProvider
*/
public function testImport($type, $name, $config_name, $expected, $config_before, $config_after) {
// Clear dispatch log and set pre-config.
$this->dispatchedEvents = [];
if ($config_name) {
$this->configStorage[$config_name] = $config_before;
}
$save_config = $this->configStorage;
// Call the importer and test the Boolean result.
$result = $this->configReverter->import($type, $name);
$this->assertEquals($expected, $result);
if ($result) {
// Verify that the config is correct after import, and logging worked.
$this->assertEquals($config_after, $this->configStorage[$config_name]);
$this->assertCount(2, $this->dispatchedEvents);
$this->assertEquals(ConfigRevertInterface::PRE_IMPORT, $this->dispatchedEvents[0][0]);
$this->assertEquals(ConfigRevertInterface::IMPORT, $this->dispatchedEvents[1][0]);
}
else {
// Verify that the config didn't change and no events were logged.
$this->assertEquals($save_config, $this->configStorage);
$this->assertCount(0, $this->dispatchedEvents);
}
}
/**
* Data provider for self:testImport().
*/
public function importProvider() {
return [
// Elements: type, name, config name, return value,
// config to set up before, config expected after. See also
// getFromExtensionProvider().
[
'system.simple',
'in.extension',
'in.extension',
TRUE,
['in.extension' => 'before'],
['in.extension' => 'extension', '_core' => 'core_for_in.extension'],
],
[
'foo',
'one',
'foo.bar.one',
TRUE,
['foo.bar.one' => 'before', 'id' => 'one'],
[
'foo.bar.one' => 'extension',
'id' => 'one',
'_core' => 'core_for_foo.bar.one',
],
],
[
'system.simple',
'in.both',
'in.both',
TRUE,
['in.both' => 'before'],
['in.both' => 'extension', '_core' => 'core_for_in.both'],
],
[
'system.simple',
'in.optional',
'in.optional',
TRUE,
['in.optional' => 'before'],
['in.optional' => 'optional', '_core' => 'core_for_in.optional'],
],
// Will be altered if the extension config exists.
[
'system.simple',
'in.extension.pre_import',
'in.extension.pre_import',
TRUE,
['prop' => 'unaltered_value'],
[
'prop' => 'altered_value',
'new_prop' => 'new_value',
'_core' => 'core_for_in.extension.pre_import',
],
],
// Will not be altered if the extension config doesn't exist.
[
'system.simple',
'missing2,pre_import',
'missing2.pre_import',
FALSE,
FALSE,
FALSE,
],
[
'unknown',
'in.extension',
FALSE,
FALSE,
FALSE,
FALSE,
],
[
'system.simple',
'missing2',
'missing2',
FALSE,
FALSE,
FALSE,
],
];
}
/**
* @covers \Drupal\config_update\ConfigReverter::revert
* @dataProvider revertProvider
*/
public function testRevert($type, $name, $config_name, $expected, $config_before, $config_after) {
// Clear dispatch log and set pre-config.
$this->dispatchedEvents = [];
if ($config_name) {
$this->configStorage[$config_name] = $config_before;
}
$save_config = $this->configStorage;
// Call the reverter and test the Boolean result.
$result = $this->configReverter->revert($type, $name);
$this->assertEquals($expected, $result);
if ($result) {
// Verify that the config is correct after revert, and logging worked.
$this->assertEquals($config_after, $this->configStorage[$config_name]);
$this->assertCount(2, $this->dispatchedEvents);
$this->assertEquals(ConfigRevertInterface::PRE_REVERT, $this->dispatchedEvents[0][0]);
$this->assertEquals(ConfigRevertInterface::REVERT, $this->dispatchedEvents[1][0]);
}
else {
// Verify that the config didn't change and no events were logged.
$this->assertEquals($save_config, $this->configStorage);
$this->assertCount(0, $this->dispatchedEvents);
}
}
/**
* Data provider for self:testRevert().
*/
public function revertProvider() {
return [
// Elements: type, name, config name, return value,
// config to set up before, config expected after. See also
// getFromExtensionProvider().
// The active config's 'prop' property will not be reverted.
[
'system.simple',
'in.extension.pre_revert',
'in.extension.pre_revert',
TRUE,
['prop' => 'unaltered_value'],
[
'prop' => 'active.pre_revert_value',
'new_prop' => 'new_value',
'_core' => 'core_for_in.extension.pre_revert',
],
],
// The active config's 'prop' property will not be reverted.
[
'foo',
'pre_revert',
'foo.bar.pre_revert',
TRUE,
['foo.bar.pre_revert' => 'active', 'id' => 'one'],
[
'foo.bar.pre_revert' => 'extension',
'id' => 'pre_revert',
'prop' => 'active.pre_revert_value',
'new_prop' => 'new_value',
'_core' => 'core_for_foo.bar.pre_revert',
],
],
[
'system.simple',
'in.extension',
'in.extension',
TRUE,
['in.extension' => 'active'],
['in.extension' => 'extension', '_core' => 'core_for_in.extension'],
],
[
'foo',
'one',
'foo.bar.one',
TRUE,
['foo.bar.one' => 'active', 'id' => 'one'],
[
'foo.bar.one' => 'extension',
'id' => 'one',
'_core' => 'core_for_foo.bar.one',
],
],
[
'system.simple',
'in.both',
'in.both',
TRUE,
['in.both' => 'active'],
['in.both' => 'extension', '_core' => 'core_for_in.both'],
],
[
'system.simple',
'in.optional',
'in.optional',
TRUE,
['in.optional' => 'active'],
['in.optional' => 'optional', '_core' => 'core_for_in.optional'],
],
[
'unknown',
'in.extension',
FALSE,
FALSE,
FALSE,
FALSE,
],
// Missing from extension storage.
[
'system.simple',
'missing2',
'missing2',
FALSE,
FALSE,
FALSE,
],
// Present in extension storage but missing from active storage.
[
'system.simple',
'another',
'another',
FALSE,
FALSE,
FALSE,
],
];
}
/**
* @covers \Drupal\config_update\ConfigReverter::delete
* @dataProvider deleteProvider
*/
public function testDelete($type, $name, $config_name, $expected, $config_before = NULL) {
// Clear dispatch log.
$this->dispatchedEvents = [];
if ($config_name && $config_before) {
$this->configStorage[$config_name] = $config_before;
}
$save_config = $this->configStorage;
// Call the configReverter delete method and test the Boolean result.
$result = $this->configReverter->delete($type, $name);
$this->assertEquals($expected, $result);
if ($result) {
// Verify that the config is missing after delete, and logging worked.
$this->assertNotTrue(isset($this->configStorage[$config_name]));
$this->assertCount(2, $this->dispatchedEvents);
$this->assertEquals(ConfigDeleteInterface::PRE_DELETE, $this->dispatchedEvents[0][0]);
$this->assertEquals(ConfigDeleteInterface::DELETE, $this->dispatchedEvents[1][0]);
}
else {
// Verify that the config didn't change and no events were logged.
$this->assertEquals($save_config, $this->configStorage);
$this->assertCount(0, $this->dispatchedEvents);
}
}
/**
* Data provider for self:testDelete().
*/
public function deleteProvider() {
return [
// Elements: type, name, config name, return value,
// config to set up before (optional).
[
'system.simple',
'in.extension',
'in.extension',
TRUE,
],
[
'foo',
'one',
'foo.bar.one',
TRUE,
['foo.bar.one' => 'before', 'id' => 'one'],
],
[
'unknown',
'in.extension',
FALSE,
FALSE,
],
[
'system.simple',
'missing2',
'missing2',
FALSE,
],
];
}
}

View File

@@ -0,0 +1,614 @@
<?php
namespace Drupal\Tests\config_update\Unit;
use Drupal\Component\EventDispatcher\Event;
use Drupal\config_update\ConfigPreRevertEvent;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Tests\UnitTestCase;
/**
* Base class for unit testing in Config Update Manager.
*
* This class provides some mock classes for unit testing.
*/
abstract class ConfigUpdateUnitTestBase extends UnitTestCase {
/**
* The mocked entity definition information.
*
* They are not sorted, to test that the methods sort them. Also there are a
* couple with prefixes that are subsets of each other.
*
* @var string[]
*
* @see ConfigUpdateUnitTestBase::getEntityManagerMock().
*/
protected $entityDefinitionInformation = [
['prefix' => 'foo.bar', 'type' => 'foo'],
['prefix' => 'foo.barbaz', 'type' => 'bar'],
['prefix' => 'baz.foo', 'type' => 'baz'],
];
/**
* Creates a mock entity manager for the test.
*
* @see ConfigUpdateUnitTestBase::entityDefinitionInformation
*/
protected function getEntityManagerMock() {
$definitions = [];
$map = [];
foreach ($this->entityDefinitionInformation as $info) {
$def = $this->getMockBuilder('Drupal\Core\Config\Entity\ConfigEntityTypeInterface')->getMock();
$def
->expects($this->any())
->method('getConfigPrefix')
->willReturn($info['prefix']);
$def
->expects($this->any())
->method('entityClassImplements')
->willReturn(TRUE);
$def
->method('getKey')
->willReturn('id');
$def->getConfigPrefix();
$definitions[$info['type']] = $def;
$map[] = [$info['type'], FALSE, $def];
$map[] = [$info['type'], TRUE, $def];
}
// Add in a content entity definition, which shouldn't be recognized by the
// config lister class.
$def = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityTypeInterface')->getMock();
$def
->expects($this->any())
->method('entityClassImplements')
->willReturn(FALSE);
$definitions['content_entity'] = $def;
$manager = $this->getMockBuilder('Drupal\Core\Entity\EntityTypeManagerInterface')->getMock();
$manager
->method('getDefinitions')
->willReturn($definitions);
$manager
->method('getDefinition')
->willReturnMap($map);
$manager
->method('getStorage')
->willReturnCallback([$this, 'mockGetStorage']);
return $manager;
}
/**
* Mocks the getStorage() method for the entity manager.
*/
public function mockGetStorage($entity_type) {
// Figure out the config prefix for this entity type.
$prefix = '';
foreach ($this->entityDefinitionInformation as $info) {
if ($info['type'] == $entity_type) {
$prefix = $info['prefix'];
}
}
// This is used in ConfigReverter::import(). Although it is supposed to
// be entity storage, we'll use our mock config object instead.
return new MockConfig('', $prefix, $this);
}
/**
* Array of active configuration information for mocking.
*
* Array structure: Each element is an array whose first element is a
* provider name, and second is an array of config items it provides.
*
* @var array
*
* @see ConfigUpdateUnitTestBase::getConfigStorageMock()
*/
protected $configStorageActiveInfo = [
['foo.bar', ['foo.bar.one', 'foo.bar.two', 'foo.bar.three']],
['foo.barbaz', ['foo.barbaz.four', 'foo.barbaz.five', 'foo.barbaz.six']],
['baz.foo', []],
['',
[
'foo.bar.one',
'foo.bar.two',
'foo.bar.three',
'foo.barbaz.four',
'foo.barbaz.five',
'foo.barbaz.six',
'something.else',
'another.one',
],
],
];
/**
* Array of extension configuration information for mocking.
*
* Array structure: Each element is an array whose first element is a
* provider name, and second is an array of config items it provides.
*
* @var array
*
* @see ConfigUpdateUnitTestBase::getConfigStorageMock()
*/
protected $configStorageExtensionInfo = [
['foo.bar', ['foo.bar.one', 'foo.bar.two', 'foo.bar.seven']],
['baz.foo', []],
// This next item is assumed to be element 2 of the array. If not, you
// will need to change ConfigUpdateUnitTestBase::getConfigStorageMock().
['',
[
'foo.bar.one',
'foo.bar.two',
'foo.bar.seven',
'foo.barbaz.four',
'foo.barnot.three',
'something.else',
],
],
];
/**
* Array of optional configuration information for mocking.
*
* Array structure: Each element is an array whose first element is a
* provider name, and second is an array of config items it provides.
*
* @var array
*
* @see ConfigUpdateUnitTestBase::getConfigStorageMock()
*/
protected $configStorageOptionalInfo = [
['foo.bar', []],
['foo.barbaz', ['foo.barbaz.four']],
// This next item is assumed to be element 2 of the array. If not, you
// will need to change ConfigUpdateUnitTestBase::getConfigStorageMock().
['', ['foo.barbaz.four']],
];
/**
* Creates a mock config storage object for the test.
*
* @param string $type
* Type of storage object to return: 'active', 'extension', or 'optional'.
* In active storage, the read() method is mocked to assume you are reading
* core.extension to get the profile name, so it returns that information.
* For extension and optional storage, the getComponentNames() method is
* mocked, and for all storages, the listAll() method is mocked.
*
* @see ConfigUpdateUnitTestBase::configStorageActiveInfo
* @see ConfigUpdateUnitTestBase::configStorageExtensionInfo
* @see ConfigUpdateUnitTestBase::configStorageOptionalInfo
*/
protected function getConfigStorageMock($type) {
if ($type == 'active') {
$storage = $this->getMockBuilder('Drupal\Core\Config\StorageInterface')->getMock();
// Various tests assume various values of configuration that need to be
// read from active storage.
$map = [
['core.extension', ['profile' => 'standard']],
['foo.bar.one', ['foo.bar.one' => 'active', 'id' => 'one']],
['missing', FALSE],
['in.extension',
['in.extension' => 'active', '_core' => 'core_for_in.extension'],
],
['in.both', ['in.both' => 'active']],
['in.optional', ['in.optional' => 'active']],
['in.extension.pre_revert',
['prop' => 'active.pre_revert_value', '_core' => 'core_for_in.extension'],
],
['foo.bar.pre_revert',
[
'foo.bar.pre_revert' => 'active',
'id' => 'pre_revert',
'prop' => 'active.pre_revert_value',
],
],
];
$storage
->method('read')
->willReturnMap($map);
$storage
->method('listAll')
->willReturnMap($this->configStorageActiveInfo);
}
elseif ($type == 'extension') {
$storage = $this->getMockBuilder('Drupal\Core\Config\ExtensionInstallStorage')->disableOriginalConstructor()->getMock();
$value = [];
foreach ($this->configStorageExtensionInfo[2][1] as $item) {
$value[$item] = 'ignored';
}
$storage
->method('getComponentNames')
->willReturn($value);
$storage
->method('listAll')
->willReturnMap($this->configStorageExtensionInfo);
$map = [
['in.extension', ['in.extension' => 'extension']],
['in.both', ['in.both' => 'extension']],
['in.optional', FALSE],
['foo.bar.one', ['foo.bar.one' => 'extension', 'id' => 'one']],
['another', ['another' => 'extension', 'id' => 'one']],
['in.extension.pre_import', ['prop' => 'extension.pre_import_value']],
['in.extension.pre_revert', ['prop' => 'extension.pre_revert_value']],
['foo.bar.pre_revert',
[
'foo.bar.pre_revert' => 'extension',
'id' => 'pre_revert',
'prop' => 'extension.pre_revert_value',
],
],
['missing2', FALSE],
['missing2.pre_import', FALSE],
];
$storage
->method('read')
->willReturnMap($map);
}
else {
$storage = $this->getMockBuilder('Drupal\Core\Config\ExtensionInstallStorage')->disableOriginalConstructor()->getMock();
$value = [];
foreach ($this->configStorageOptionalInfo[2][1] as $item) {
$value[$item] = 'ignored';
}
$storage
->method('getComponentNames')
->willReturn($value);
$storage
->method('listAll')
->willReturnMap($this->configStorageOptionalInfo);
$map = [
['in.optional', ['in.optional' => 'optional']],
['in.both', ['in.both' => 'optional']],
['missing2', FALSE],
];
$storage
->method('read')
->willReturnMap($map);
}
return $storage;
}
/**
* Creates a mock module handler for the test.
*/
protected function getModuleHandlerMock() {
$manager = $this->getMockBuilder('Drupal\Core\Extension\ModuleHandlerInterface')->getMock();
$manager->method('getModuleList')
->willReturn(['foo_module' => '', 'standard' => '']);
return $manager;
}
/**
* Creates a mock theme handler for the test.
*/
protected function getThemeHandlerMock() {
$manager = $this->getMockBuilder('Drupal\Core\Extension\ThemeHandlerInterface')->getMock();
$manager->method('listInfo')
->willReturn(['foo_theme' => '']);
return $manager;
}
/**
* Creates a mock string translation class for the test.
*/
protected function getTranslationMock() {
$translation = $this->getMockBuilder('Drupal\Core\StringTranslation\TranslationInterface')->getMock();
$translation
->method('translateString')
->willReturnCallback([$this, 'mockTranslate']);
return $translation;
}
/**
* Mocks the translateString() method for the string translation mock object.
*
* @param \Drupal\Core\StringTranslation\TranslatableMarkup $input
* Object to translate.
*
* @return string
* The untranslated string from $input.
*/
public function mockTranslate(TranslatableMarkup $input) {
return $input->getUntranslatedString();
}
/**
* List of mock-dispatched events.
*
* Each element of the array is the call parameters to dispatchEvent() in
* the mocked dispatch class: name and event instance.
*
* @var array
*
* @see ConfigUpdateUnitTestBase::getEventDispatcherMock()
*/
protected $dispatchedEvents = [];
/**
* Mocks the event dispatcher service.
*
* Stores dispatched events in ConfigUpdateUnitTestBase::dispatchedEvents.
*/
protected function getEventDispatcherMock() {
$event = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$event
->method('dispatch')
->willReturnCallback([$this, 'mockDispatch']);
return $event;
}
/**
* Mocks event dispatch.
*
* @see \Symfony\Component\EventDispatcher\EventDispatcherInterface::dispatch()
*/
public function mockDispatch(Event $event, $name = NULL) {
$this->dispatchedEvents[] = [$name, $event];
if ($event instanceof ConfigPreRevertEvent) {
$this->handlePreRevertDispatch($event);
}
return $event;
}
/**
* Handle the pre-revert events.
*
* @param \Drupal\config_update\ConfigPreRevertEvent $event
* The dispatched event.
*/
protected function handlePreRevertDispatch(ConfigPreRevertEvent $event) {
$name = $event->getName();
// Only modify configurations with the pre_import or pre_revert names.
$import = strpos($name, 'pre_import') !== FALSE;
$revert = strpos($name, 'pre_revert') !== FALSE;
if (!$import && !$revert) {
return;
}
$active = $event->getActive();
$value = $event->getValue();
// Always add the new property.
$value['new_prop'] = 'new_value';
// Alter the original property.
if (isset($value['prop'])) {
if ($active) {
// A revert operation is being done, read properties from it.
if (isset($active['prop'])) {
// Don't override the original property.
$value['prop'] = $active['prop'];
}
else {
$value['prop'] = 'altered_active_value';
}
}
else {
$value['prop'] = 'altered_value';
}
}
// Store the modified value.
$event->setValue($value);
}
/**
* Mock config storage for the mock config factory.
*
* This is actually managed by the MockConfig class in this file.
*
* @var array
*/
protected $configStorage = [];
/**
* Gets the value of the mocked config storage.
*/
public function getConfigStorage() {
return $this->configStorage;
}
/**
* Sets the value of the mocked config storage.
*/
public function setConfigStorage($values) {
$this->configStorage = $values;
}
/**
* Creates a mock config factory class for the test.
*/
protected function getConfigFactoryMock() {
$config = $this->getMockBuilder('Drupal\Core\Config\ConfigFactoryInterface')->getMock();
$config
->method('getEditable')
->willReturnCallback([$this, 'mockGetEditable']);
return $config;
}
/**
* Mocks the getEditable() method for the mock config factory.
*
* @param string $name
* Name of the config object to get an editable object for.
*
* @return MockConfig
* Editable mock config object.
*/
public function mockGetEditable($name) {
return new MockConfig($name, '', $this);
}
}
/**
* Mock class for mutable configuration, config entity, and entity storage.
*/
class MockConfig {
/**
* Name of the config.
*
* @var string
*/
protected $name = '';
/**
* Prefix for the entity type being mocked, for entity storage mocking.
*
* @var string
*/
protected $entityPrefix = '';
/**
* Test class this comes from.
*
* @var \Drupal\Tests\config_update\Unit\ConfigUpdateUnitTestBase
*/
protected $test;
/**
* Current value of the configuration.
*
* @var array
*/
protected $value = '';
/**
* Constructs a mock config object.
*
* @param string $name
* Name of the config that is being mocked. Can be blank.
* @param string $entity_prefix
* Prefix for the entity type that is being mocked. Often blank.
* @param \Drupal\Tests\config_update\Unit\ConfigUpdateUnitTestBase $test
* Test class this comes from.
*/
public function __construct($name, $entity_prefix, ConfigUpdateUnitTestBase $test) {
$this->name = $name;
$this->entityPrefix = $entity_prefix;
$this->test = $test;
$storage = $test->getConfigStorage();
if ($name && isset($storage[$name])) {
$value = $storage[$name];
$value['is_new'] = FALSE;
}
else {
$value['is_new'] = TRUE;
}
$value['_core'] = 'core_for_' . $name;
$this->value = $value;
}
/**
* Gets a component of the configuration value.
*/
public function get($key) {
return $this->value[$key] ?? NULL;
}
/**
* Sets a component of the configuration value.
*/
public function set($key, $value) {
$this->value[$key] = $value;
return $this;
}
/**
* Sets the entire configuration value.
*/
public function setData($value) {
// Retain the _core key.
$core = $this->value['_core'] ?? '';
$this->value = $value;
if ($core) {
$this->value['_core'] = $core;
}
return $this;
}
/**
* Saves the configuration.
*/
public function save() {
$config = $this->test->getConfigStorage();
$config[$this->name] = $this->value;
$this->test->setConfigStorage($config);
return $this;
}
/**
* Deletes the configuration.
*/
public function delete() {
$config = $this->test->getConfigStorage();
unset($config[$this->name]);
$this->test->setConfigStorage($config);
return $this;
}
/**
* Mocks the createFromStorageRecord() method from entity storage.
*/
public function createFromStorageRecord($values) {
if (!$this->entityPrefix) {
return NULL;
}
// This is supposed to return an entity, but the only method we need is
// save(), so instead set up and return this object.
$this->name = $this->entityPrefix . '.' . $values['id'];
$this->value = $values;
$this->value['_core'] = 'core_for_' . $this->name;
return $this;
}
/**
* Mocks the updateFromStorageRecord() method from entity storage.
*/
public function updateFromStorageRecord($object, $values) {
return $object->createFromStorageRecord($values);
}
/**
* Mocks the load() method for entity storage.
*/
public function load($id) {
$full_name = $this->entityPrefix . '.' . $id;
$configs = $this->test->getConfigStorage();
if (isset($configs[$full_name])) {
$this->value = $configs[$full_name];
$this->name = $full_name;
$this->value['_core'] = 'core_for_' . $full_name;
return $this;
}
return NULL;
}
}