clean install

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

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
/vendor/
/web/
/node_modules/
.env
composer.lock
yarn.lock
/.editorconfig
/.gitattributes
#PHPUnit output
junit.xml
.phpunit.result.cache
/composer.spoons.json
/composer.spoons.lock
/.env
.envrc
+118
View File
@@ -0,0 +1,118 @@
################
# DrupalCI GitLabCI template
#
# Gitlab-ci.yml to replicate DrupalCI testing for Contrib
#
# With thanks to:
# * The GitLab Acceleration Initiative participants
# * DrupalSpoons
################
################
# Guidelines
#
# This template is designed to give any Contrib maintainer everything they need to test, without requiring modification. It is also designed to keep up to date with Core Development automatically through the use of include files that can be centrally maintained.
#
# However, you can modify this template if you have additional needs for your project.
################
################
# Includes
#
# Additional configuration can be provided through includes.
# One advantage of include files is that if they are updated upstream, the changes affect all pipelines using that include.
#
# Includes can be overridden by re-declaring anything provided in an include, here in gitlab-ci.yml
# https://docs.gitlab.com/ee/ci/yaml/includes.html#override-included-configuration-values
################
include:
################
# DrupalCI includes:
# As long as you include this, any future includes added by the Drupal Association will be accessible to your pipelines automatically.
# View these include files at https://git.drupalcode.org/project/gitlab_templates/
################
- project: $_GITLAB_TEMPLATES_REPO
ref: $_GITLAB_TEMPLATES_REF
file:
- '/includes/include.drupalci.main.yml'
# EXPERIMENTAL: For Drupal 7, remove the above line and uncomment the below.
# - '/includes/include.drupalci.main-d7.yml'
- '/includes/include.drupalci.variables.yml'
- '/includes/include.drupalci.workflows.yml'
################
# Pipeline configuration variables
#
# These are the variables provided to the Run Pipeline form that a user may want to override.
#
# Docs at https://git.drupalcode.org/project/gitlab_templates/-/blob/1.0.x/includes/include.drupalci.variables.yml
################
# variables:
# SKIP_ESLINT: '1'
#
# Start custom overrides.
# Based on https://git.drupalcode.org/project/keycdn/-/blob/8.x-1.x/.gitlab-ci.yml
#
variables:
# #Disable default phpunit job in favor of the d9/10 variants below.
# SKIP_PHPUNIT: 1
# SKIP_COMPOSER: 1
# _PHPUNIT_EXTRA: --verbose
# Broaden test coverage.
OPT_IN_TEST_PREVIOUS_MAJOR: 1
OPT_IN_TEST_MAX_PHP: 1
OPT_IN_TEST_NEXT_MINOR: 1
OPT_IN_TEST_NEXT_MAJOR: 1
# Convenient, and we have no secrets.
_SHOW_ENVIRONMENT_VARIABLES: 1
###################################################################################
#
# *
# /(
# ((((,
# /(((((((
# ((((((((((*
# ,(((((((((((((((
# ,(((((((((((((((((((
# ((((((((((((((((((((((((*
# *(((((((((((((((((((((((((((((
# ((((((((((((((((((((((((((((((((((*
# *(((((((((((((((((( .((((((((((((((((((
# ((((((((((((((((((. /(((((((((((((((((*
# /((((((((((((((((( .(((((((((((((((((,
# ,(((((((((((((((((( ((((((((((((((((((
# .(((((((((((((((((((( .(((((((((((((((((
# ((((((((((((((((((((((( ((((((((((((((((/
# (((((((((((((((((((((((((((/ ,(((((((((((((((*
# .((((((((((((((/ /(((((((((((((. ,(((((((((((((((
# *(((((((((((((( ,(((((((((((((/ *((((((((((((((.
# ((((((((((((((, /(((((((((((((. ((((((((((((((,
# (((((((((((((/ ,(((((((((((((* ,(((((((((((((,
# *((((((((((((( .((((((((((((((( ,(((((((((((((
# ((((((((((((/ /((((((((((((((((((. ,((((((((((((/
# ((((((((((((( *(((((((((((((((((((((((* *((((((((((((
# ((((((((((((( ,(((((((((((((..((((((((((((( *((((((((((((
# ((((((((((((, /((((((((((((* /((((((((((((/ ((((((((((((
# ((((((((((((( /((((((((((((/ (((((((((((((* ((((((((((((
# (((((((((((((/ /(((((((((((( ,((((((((((((, *((((((((((((
# (((((((((((((( *(((((((((((/ *((((((((((((. ((((((((((((/
# *((((((((((((((((((((((((((, /(((((((((((((((((((((((((
# ((((((((((((((((((((((((( ((((((((((((((((((((((((,
# .(((((((((((((((((((((((/ ,(((((((((((((((((((((((
# ((((((((((((((((((((((/ ,(((((((((((((((((((((/
# *((((((((((((((((((((( (((((((((((((((((((((,
# ,(((((((((((((((((((((, ((((((((((((((((((((/
# ,(((((((((((((((((((((* /((((((((((((((((((((
# ((((((((((((((((((((((, ,/((((((((((((((((((((,
# ,(((((((((((((((((((((((((((((((((((((((((((((((((((
# .(((((((((((((((((((((((((((((((((((((((((((((
# .((((((((((((((((((((((((((((((((((((,.
# .,(((((((((((((((((((((((((.
#
###################################################################################
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+23
View File
@@ -0,0 +1,23 @@
# MIGRATE TOOLS
* Introduction
## Introduction
The Migrate Tools module provides tools for running and managing Drupal
8 migrations.
Drush commands supported include:
- migrate-status - Lists migrations and their status.
- migrate-import - Performs import operations.
- migrate-rollback - Performs rollback operations.
- migrate-stop - Cleanly stops a running operation.
- migrate-reset-status - Sets a migration status to Idle if it's
gotten stuck.
- migrate-messages - Lists any messages associated with a migration
import.
The UI at this point provides a front-end equivalent to the
migrate-status and migrate-messages commands. It will be enhanced to
allow running the other operations, as well as provide the ability to
create and alter migrations.
+49
View File
@@ -0,0 +1,49 @@
{
"name": "drupal/migrate_tools",
"description": "Tools to assist in developing and running migrations.",
"type": "drupal-module",
"homepage": "http://drupal.org/project/migrate_tools",
"authors": [
{
"name": "Mike Ryan",
"homepage":"https://www.drupal.org/u/mikeryan",
"role": "Maintainer"
},
{
"name": "Lucas Hedding",
"homepage": "https://www.drupal.org/u/heddn",
"role": "Maintainer"
}
],
"support": {
"issues": "https://www.drupal.org/project/issues/migrate_tools",
"slack": "#migrate",
"source": "https://git.drupalcode.org/project/migrate_tools"
},
"license": "GPL-2.0-or-later",
"minimum-stability": "stable",
"prefer-stable": false,
"config": {
"preferred-install": "dist"
},
"require": {
"php": ">=7.4",
"drupal/core": ">=9.1"
},
"require-dev": {
"drupal/migrate_source_csv": ">=3",
"drush/drush": ">=11",
"drupal/migrate_plus": ">=5"
},
"suggest": {
"drush/drush": ">=11",
"drupal/migrate_plus": ">=5"
},
"extra": {
"drush": {
"services": {
"drush.services.yml": ">=9"
}
}
}
}
@@ -0,0 +1,6 @@
services:
migrate_tools.commands:
class: Drupal\migrate_tools\Drush\Commands\MigrateToolsCommands
arguments: ['@plugin.manager.migration', '@date.formatter', '@entity_type.manager', '@keyvalue']
tags:
- { name: drush.command }
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

@@ -0,0 +1,16 @@
type: module
name: Migrate Tools
description: 'Tools to assist in developing and running migrations.'
package: Migration
core_version_requirement: '^9.1 || ^10 || ^11'
configure: entity.migration_group.list
dependencies:
- drupal:migrate
test_dependencies:
- migrate_plus:migrate_plus
- migrate_source_csv:migrate_source_csv (>=8.x-3.0)
# Information added by Drupal.org packaging script on 2024-11-05
version: '6.0.5'
project: 'migrate_tools'
datestamp: 1730824459
@@ -0,0 +1,48 @@
<?php
/**
* Implements hook_schema().
*/
function migrate_tools_schema(): array {
$schema['migrate_tools_sync_source_ids'] = [
'description' => 'Table storing SyncSourceIds entries for the --sync option.',
'fields' => [
'id' => array(
'description' => 'Primary Key: Unique ID.',
'type' => 'serial',
'not null' => TRUE,
),
'migration_id' => [
'description' => 'The migration ID.',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
],
'source_ids' => [
'description' => 'Array of source IDs, in the same order as defined in \Drupal\migrate\Row::$sourceIds.',
'type' => 'blob',
// "normal" size for "blob" is 16KB on MySQL, and 4GB or unlimited on
// other DBMS. That should more than enough for a single set of IDs.
// @see https://www.drupal.org/node/159605
'size' => 'normal',
'not null' => TRUE,
'serialize' => TRUE,
],
],
'indexes' => [
'migration_id' => ['migration_id'],
],
'primary key' => ['id'],
];
return $schema;
}
/**
* Adds a table in the database dedicated to SyncSourceIds entries.
*/
function migrate_tools_update_10000(): void {
$schema = migrate_tools_schema();
foreach($schema as $tableName => $schemaDefinition) {
\Drupal::database()->schema()->createTable($tableName, $schemaDefinition);
}
}
@@ -0,0 +1,5 @@
migrate_tools.add_group_action:
route_name: entity.migration_group.add_form
title: 'Add migration group'
appears_on:
- entity.migration_group.list
@@ -0,0 +1,51 @@
# Component routing definition
entity.migration.overview:
route_name: entity.migration.overview
base_route: entity.migration.overview
title: View
entity.migration.overview_general:
title: Overview
route_name: entity.migration.overview
parent_id: entity.migration.overview
entity.migration.overview_source:
title: Source
route_name: entity.migration.source
parent_id: entity.migration.overview
weight: 1
entity.migration.overview_process:
title: Process
route_name: entity.migration.process
parent_id: entity.migration.overview
weight: 2
entity.migration.overview_destination:
title: Destination
route_name: entity.migration.destination
parent_id: entity.migration.overview
weight: 3
entity.migration.execute_form:
route_name: migrate_tools.execute
base_route: entity.migration.overview
title: Execute
entity.migration.edit_form:
route_name: entity.migration.edit_form
base_route: entity.migration.overview
title: Edit
migrate_tools.messages:
route_name: migrate_tools.messages
base_route: entity.migration.overview
title: Messages
entity.migration.delete_form:
route_name: entity.migration.delete_form
base_route: entity.migration.overview
title: Delete
weight: 10
entity.migration.overview_general_edit:
title: Overview
route_name: entity.migration.edit_form
parent_id: entity.migration.edit_form
@@ -0,0 +1,101 @@
<?php
/**
* @file Module file for Migrate Tools.
*/
declare(strict_types = 1);
/**
* @file
* Provides tools for implementing and managing migrations.
*/
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\migrate\Plugin\MigrateSourceInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Drupal\migrate_tools\Controller\MigrationGroupListBuilder;
use Drupal\migrate_tools\Controller\MigrationListBuilder;
use Drupal\migrate_tools\Form\MigrationDeleteForm;
use Drupal\migrate_tools\Form\MigrationEditForm;
use Drupal\migrate_tools\Form\MigrationGroupAddForm;
use Drupal\migrate_tools\Form\MigrationGroupDeleteForm;
use Drupal\migrate_tools\Form\MigrationGroupEditForm;
use Drupal\migrate_tools\MigrateTools;
/**
* Implements hook_entity_type_build().
*/
function migrate_tools_entity_type_build(array &$entity_types): void {
// Inject our UI into the general migration and migration group config
// entities.
/** @var \Drupal\Core\Config\Entity\ConfigEntityType[] $entity_types */
if (array_key_exists('migration', $entity_types)) {
$entity_types['migration']
->set('admin_permission', 'administer migrations')
->setHandlerClass('list_builder', MigrationListBuilder::class)
->setFormClass('edit', MigrationEditForm::class)
->setFormClass('delete', MigrationDeleteForm::class)
->setLinkTemplate('list-form', '/admin/structure/migrate/manage/{migration_group}/migrations');
}
if (array_key_exists('migration_group', $entity_types)) {
$entity_types['migration_group']
->set('admin_permission', 'administer migrations')
->setHandlerClass('list_builder', MigrationGroupListBuilder::class)
->setFormClass('add', MigrationGroupAddForm::class)
->setFormClass('edit', MigrationGroupEditForm::class)
->setFormClass('delete', MigrationGroupDeleteForm::class)
->setLinkTemplate('edit-form', '/admin/structure/migrate/manage/{migration_group}')
->setLinkTemplate('delete-form', '/admin/structure/migrate/manage/{migration_group}/delete');
}
}
/**
* Implements hook_menu_links_discovered_alter().
*/
function migrate_tools_menu_links_discovered_alter(&$links): void {
if (\Drupal::moduleHandler()->moduleExists('migrate_plus')) {
$links['migrate_tools.menu'] = [
'title' => 'Migrations',
'route_name' => 'entity.migration_group.list',
'description' => new TranslatableMarkup('Manage migration processes.'),
'parent' => 'system.admin_structure',
];
}
}
/**
* Implements hook_migration_plugins_alter().
*/
function migrate_tools_migration_plugins_alter(array &$migrations): void {
foreach (array_keys($migrations) as $id) {
// Process all includes.
if (!array_key_exists('include', $migrations[$id])) {
continue;
}
\Drupal::service('migrate_tools.shared_config_include_handler')->include($migrations[$id]);
}
}
/**
* Implements hook_migrate_prepare_row().
*
* @throws \Exception
*
* @see \Drupal\migrate_tools\EventSubscriber\MigrationImportSync
* @see \Drupal\migrate\Plugin\migrate\source\SourcePluginBase::next()
*/
function migrate_tools_migrate_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration): void {
/** @var MigrateTools $migrateTools */
$migrateTools = \Drupal::service('migrate_tools.migrate_tools');
// Act on migrations that have a Sync source, and that are currently in the
// phase of Syncing their IDs.
if (!empty($migration->syncSource) && $migrateTools->isMigrationSyncing($migration->getPluginId())) {
// Keep track of all source rows here, as SourcePluginBase::next() might
// skip some rows, and we need them all to detect missing items in source to
// delete in destination.
$migrateTools->addToSyncSourceIds($migration->getPluginId(), $row->getSourceIdValues());
}
}
@@ -0,0 +1,3 @@
'administer migrations':
title: 'Administer migrations'
description: Create, edit, and manage migration processed.
@@ -0,0 +1,152 @@
entity.migration_group.list:
path: '/admin/structure/migrate'
defaults:
_entity_list: 'migration_group'
_title: 'Migrations'
requirements:
_permission: 'administer migrations'
entity.migration_group.add_form:
path: '/admin/structure/migrate/add'
defaults:
_title: 'Add migration group'
_entity_form: migration_group.add
requirements:
_entity_create_access: migration_group
entity.migration_group.edit_form:
path: '/admin/structure/migrate/manage/{migration_group}'
defaults:
_title: 'Edit migration group'
_entity_form: migration_group.edit
requirements:
_entity_access: migration_group.update
entity.migration_group.delete_form:
path: '/admin/structure/migrate/manage/{migration_group}/delete'
defaults:
_title: 'Delete migration group'
_entity_form: migration_group.delete
requirements:
_entity_access: migration_group.delete
entity.migration.list:
path: '/admin/structure/migrate/manage/{migration_group}/migrations'
defaults:
_entity_list: 'migration'
_title: 'Migrations'
requirements:
_permission: 'administer migrations'
entity.migration.overview:
path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}'
defaults:
_controller: '\Drupal\migrate_tools\Controller\MigrationController::overview'
_title: 'Migration overview'
_migrate_group: true
requirements:
_permission: 'administer migrations'
options:
parameters:
migration:
type: entity:migration
migration_group:
type: entity:migration_group
entity.migration.source:
path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/source'
defaults:
_controller: '\Drupal\migrate_tools\Controller\MigrationController::source'
_title: 'Source'
_migrate_group: true
requirements:
_permission: 'administer migrations'
options:
parameters:
migration:
type: entity:migration
migration_group:
type: entity:migration_group
entity.migration.process:
path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/process'
defaults:
_controller: '\Drupal\migrate_tools\Controller\MigrationController::process'
_title: 'Process'
_migrate_group: true
requirements:
_permission: 'administer migrations'
options:
parameters:
migration:
type: entity:migration
migration_group:
type: entity:migration_group
entity.migration.destination:
path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/destination'
defaults:
_controller: '\Drupal\migrate_tools\Controller\MigrationController::destination'
_title: 'Destination'
_migrate_group: true
requirements:
_permission: 'administer migrations'
options:
parameters:
migration:
type: entity:migration
migration_group:
type: entity:migration_group
entity.migration.edit_form:
path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/edit'
defaults:
_title: 'Edit migration'
_entity_form: migration.edit
_migrate_group: true
requirements:
_entity_access: migration.update
options:
parameters:
migration:
type: entity:migration
migration_group:
type: entity:migration_group
entity.migration.delete_form:
path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/delete'
defaults:
_title: 'Delete migration'
_entity_form: migration.delete
_migrate_group: true
requirements:
_entity_access: migration.delete
options:
parameters:
migration:
type: entity:migration
migration_group:
type: entity:migration_group
migrate_tools.messages:
path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/messages'
defaults:
_controller: '\Drupal\migrate_tools\Controller\MessageController::overview'
_title_callback: '\Drupal\migrate_tools\Controller\MessageController::title'
_migrate_group: true
requirements:
_permission: 'administer migrations'
options:
parameters:
migration:
type: entity:migration
migration_group:
type: entity:migration_group
migrate_tools.execute:
path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/execute'
defaults:
_form: '\Drupal\migrate_tools\Form\MigrationExecuteForm'
_title: 'Execute migration'
_migrate_group: true
requirements:
_permission: 'administer migrations'
options:
parameters:
migration:
type: entity:migration
migration_group:
type: entity:migration_group
@@ -0,0 +1,34 @@
services:
logger.channel.migrate_tools:
class: Drupal\Core\Logger\LoggerChannel
factory: logger.factory:get
arguments: ['migrate_tools']
route_processor.migrate_group:
class: Drupal\migrate_tools\Routing\RouteProcessor
arguments: ['@entity_type.manager']
tags:
- { name: route_processor_outbound }
migrate_tools.migration_drush_command_progress:
class: Drupal\migrate_tools\EventSubscriber\MigrationDrushCommandProgress
tags:
- { name: event_subscriber }
arguments: ['@logger.channel.migrate_tools']
migrate_tools.migration_sync:
class: Drupal\migrate_tools\EventSubscriber\MigrationImportSync
tags:
- { name: event_subscriber }
arguments:
- '@event_dispatcher'
- '@migrate_tools.migrate_tools'
plugin.manager.migrate_shared_config:
class: Drupal\migrate_tools\MigrateSharedConfigPluginManager
arguments: ['@module_handler', '@cache.discovery']
migrate_tools.shared_config_include_handler:
class: Drupal\migrate_tools\MigrateIncludeHandler
arguments: ['@plugin.manager.migrate_shared_config']
migrate_tools.migrate_tools:
class: Drupal\migrate_tools\MigrateTools
arguments: ['@database']
@@ -0,0 +1,193 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Controller;
use Drupal\Component\Utility\Html;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\PagerSelectExtender;
use Drupal\Core\Database\Query\TableSortExtender;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Drupal\migrate_plus\Entity\MigrationGroupInterface;
use Drupal\migrate_plus\Entity\MigrationInterface as MigratePlusMigrationInterface;
use Drupal\migrate_tools\MigrateTools;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Returns responses for migrate_tools message routes.
*/
class MessageController extends ControllerBase {
protected Connection $database;
protected MigrationPluginManagerInterface $migrationPluginManager;
/**
* Constructs a MessageController object.
*
* @param \Drupal\Core\Database\Connection $database
* A database connection.
* @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migration_plugin_manager
* The migration plugin manager.
*/
public function __construct(Connection $database, MigrationPluginManagerInterface $migration_plugin_manager) {
$this->database = $database;
$this->migrationPluginManager = $migration_plugin_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container): self {
return new static(
$container->get('database'),
$container->get('plugin.manager.migration')
);
}
/**
* Gets an array of log level classes.
*
* @return array
* An array of log level classes.
*/
public static function getLogLevelClassMap(): array {
return [
MigrationInterface::MESSAGE_INFORMATIONAL => 'migrate-message-4',
MigrationInterface::MESSAGE_NOTICE => 'migrate-message-3',
MigrationInterface::MESSAGE_WARNING => 'migrate-message-2',
MigrationInterface::MESSAGE_ERROR => 'migrate-message-1',
];
}
/**
* Displays a listing of migration messages.
*
* Messages are truncated at 56 chars.
*
* @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group
* The migration group.
* @param \Drupal\migrate_plus\Entity\MigrationInterface $migration
* The $migration.
*
* @return array
* A render array as expected by drupal_render().
*/
public function overview(MigrationGroupInterface $migration_group, MigratePlusMigrationInterface $migration): array {
$header = [];
$build = [];
$rows = [];
$classes = static::getLogLevelClassMap();
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration_plugin */
$migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray());
$source_id_field_names = array_keys($migration_plugin->getSourcePlugin()->getIds());
$column_number = 1;
foreach ($source_id_field_names as $source_id_field_name) {
$header[] = [
'data' => $source_id_field_name,
'field' => 'sourceid' . $column_number++,
'class' => [RESPONSIVE_PRIORITY_MEDIUM],
];
}
$header[] = [
'data' => $this->t('Severity level'),
'field' => 'level',
'class' => [RESPONSIVE_PRIORITY_LOW],
];
$header[] = [
'data' => $this->t('Message'),
'field' => 'message',
];
$header[] = [
'data' => $this->t('Destination ID'),
'field' => 'destid',
];
$header[] = [
'data' => $this->t('Status'),
'field' => 'source_row_status',
];
$result = [];
$message_table = $migration_plugin->getIdMap()->messageTableName();
if ($this->database->schema()->tableExists($message_table)) {
$map_table = $migration_plugin->getIdMap()->mapTableName();
$query = $this->database->select($message_table, 'msg')
->extend(PagerSelectExtender::class)
->extend(TableSortExtender::class);
$query->innerJoin($map_table, 'map', 'msg.source_ids_hash=map.source_ids_hash');
$query->fields('msg');
$query->fields('map');
$result = $query
->limit(50)
->orderByHeader($header)
->execute();
}
$level_mapping = MigrateTools::getLogLevelLabelMapping();
$status_mapping = MigrateTools::getStatusLevelLabelMapping();
foreach ($result as $message_row) {
$column_number = 1;
$data = [];
foreach ($source_id_field_names as $source_id_field_name) {
$column_name = 'sourceid' . $column_number++;
$data[$column_name] = $message_row->$column_name;
}
$data['level'] = $level_mapping[$message_row->level] ?: $message_row->level;
$data['message'] = $message_row->message;
$column_number = 1;
foreach ($migration_plugin->getDestinationPlugin()->getIds() as $dest_id_field_name => $dest_id_schema) {
$column_name = 'destid' . $column_number++;
$data['destid']['data'][] = $message_row->$column_name;
$data['destid']['#destination_fields'][$dest_id_field_name] =
$data['destid']['#destination_fields'][$column_name] = $message_row->$column_name;
}
$destid = array_filter($data['destid']['data']);
$data['destid']['data'] = [
'#markup' => $destid ? implode(MigrateTools::DEFAULT_ID_LIST_DELIMITER, $data['destid']['data']) : '',
];
$data['status'] = $status_mapping[$message_row->source_row_status];
$rows[] = [
'class' => [
Html::getClass('migrate-message-' . $message_row->level),
$classes[$message_row->level],
],
'data' => $data,
];
}
$build['message_table'] = [
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#attributes' => ['id' => $message_table, 'class' => [$message_table]],
'#empty' => $this->t('No messages for this migration.'),
];
$build['message_pager'] = ['#type' => 'pager'];
return $build;
}
/**
* Get the title of the page.
*
* @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group
* The migration group.
* @param \Drupal\migrate_plus\Entity\MigrationInterface $migration
* The $migration.
*
* @return \Drupal\Core\StringTranslation\TranslatableMarkup
* The translated title.
*/
public function title(MigrationGroupInterface $migration_group, MigratePlusMigrationInterface $migration): TranslatableMarkup {
return $this->t(
'Messages of %migration',
['%migration' => $migration->label()]
);
}
}
@@ -0,0 +1,272 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Controller;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Url;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Drupal\migrate_plus\Entity\MigrationGroupInterface;
use Drupal\migrate_plus\Entity\MigrationInterface;
use Drupal\migrate_tools\MigrateBatchExecutable;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Returns responses for migrate_tools migration view routes.
*/
class MigrationController extends ControllerBase implements ContainerInjectionInterface {
protected MigrationPluginManagerInterface $migrationPluginManager;
protected CurrentRouteMatch $currentRouteMatch;
/**
* Constructs a new MigrationController object.
*
* @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migration_plugin_manager
* The plugin manager for config entity-based migrations.
* @param \Drupal\Core\Routing\CurrentRouteMatch $currentRouteMatch
* The current route match.
*/
public function __construct(MigrationPluginManagerInterface $migration_plugin_manager, CurrentRouteMatch $currentRouteMatch) {
$this->migrationPluginManager = $migration_plugin_manager;
$this->currentRouteMatch = $currentRouteMatch;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container): self {
return new static(
$container->get('plugin.manager.migration'),
$container->get('current_route_match')
);
}
/**
* Displays an overview of a migration entity.
*
* @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group
* The migration group.
* @param \Drupal\migrate_plus\Entity\MigrationInterface $migration
* The $migration.
*
* @return array
* A render array as expected by drupal_render().
*/
public function overview(MigrationGroupInterface $migration_group, MigrationInterface $migration): array {
$build = [];
$build['overview'] = [
'#type' => 'fieldset',
'#title' => $this->t('Overview'),
];
$build['overview']['group'] = [
'#title' => $this->t('Group:'),
'#markup' => Xss::filterAdmin($migration_group->label()),
'#type' => 'item',
];
$build['overview']['description'] = [
'#title' => $this->t('Description:'),
'#markup' => Xss::filterAdmin($migration->label()),
'#type' => 'item',
];
$migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray());
$migration_dependencies = $migration_plugin->getMigrationDependencies();
if (!empty($migration_dependencies['required'])) {
$build['overview']['dependencies'] = [
'#title' => $this->t('Migration Dependencies') ,
'#markup' => Xss::filterAdmin(implode(', ', $migration_dependencies['required'])),
'#type' => 'item',
];
}
if (!empty($migration_dependencies['optional'])) {
$build['overview']['soft_dependencies'] = [
'#title' => $this->t('Soft Migration Dependencies'),
'#markup' => Xss::filterAdmin(implode(', ', $migration_dependencies['optional'])),
'#type' => 'item',
];
}
return $build;
}
/**
* Display source information of a migration entity.
*
* @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group
* The migration group.
* @param \Drupal\migrate_plus\Entity\MigrationInterface $migration
* The $migration.
*
* @return array
* A render array as expected by drupal_render().
*/
public function source(MigrationGroupInterface $migration_group, MigrationInterface $migration): array {
$build = [];
// Source field information.
$build['source'] = [
'#type' => 'fieldset',
'#title' => $this->t('Source'),
'#group' => 'detail',
'#description' => $this->t('<p>These are the fields available from the source of this migration task. The machine names listed here may be used as sources in the process pipeline.</p>'),
'#description_display' => 'after',
'#attributes' => [
'id' => 'migration-detail-source',
],
];
$migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray());
$source = $migration_plugin->getSourcePlugin();
$build['source']['query'] = [
'#type' => 'item',
'#title' => $this->t('Query'),
'#markup' => '<pre>' . Xss::filterAdmin($source) . '</pre>',
];
$header = [$this->t('Machine name'), $this->t('Description')];
$rows = [];
foreach ($source->fields($migration_plugin) as $machine_name => $description) {
$rows[] = [
['data' => Html::escape($machine_name)],
['data' => Xss::filterAdmin($description)],
];
}
$build['source']['fields'] = [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t('No fields'),
];
return $build;
}
/**
* Display process information of a migration entity.
*
* @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group
* The migration group.
* @param \Drupal\migrate_plus\Entity\MigrationInterface $migration
* The $migration.
*
* @return array
* A render array as expected by drupal_render().
*/
public function process(MigrationGroupInterface $migration_group, MigrationInterface $migration): array {
$build = [];
$migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray());
// Process information.
$build['process'] = [
'#type' => 'fieldset',
'#title' => $this->t('Process'),
];
$header = [
$this->t('Destination'),
$this->t('Source'),
$this->t('Process plugin'),
$this->t('Default'),
];
$rows = [];
foreach ($migration_plugin->getProcess() as $destination_id => $process_line) {
$row = [];
$row[] = ['data' => Html::escape($destination_id)];
if (isset($process_line[0]['source'])) {
if (is_array($process_line[0]['source'])) {
$process_line[0]['source'] = implode(', ', $process_line[0]['source']);
}
$row[] = ['data' => Xss::filterAdmin($process_line[0]['source'])];
}
else {
$row[] = '';
}
if (isset($process_line[0]['plugin'])) {
$process_line_plugins = [];
foreach ($process_line as $process_line_row) {
$process_line_plugins[] = Xss::filterAdmin($process_line_row['plugin']);
}
$row[] = ['data' => implode(', ', $process_line_plugins)];
}
else {
$row[] = '';
}
if (isset($process_line[0]['default_value'])) {
$row[] = ['data' => Xss::filterAdmin($process_line[0]['default_value'])];
}
else {
$row[] = '';
}
$rows[] = $row;
}
$build['process']['fields'] = [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t('No process defined.'),
];
return $build;
}
/**
* Displays destination information of a migration entity.
*
* @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group
* The migration group.
* @param \Drupal\migrate_plus\Entity\MigrationInterface $migration
* The $migration.
*
* @return array
* A render array as expected by drupal_render().
*/
public function destination(MigrationGroupInterface $migration_group, MigrationInterface $migration): array {
$build = [];
$migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray());
// Destination field information.
$build['destination'] = [
'#type' => 'fieldset',
'#title' => $this->t('Destination'),
'#group' => 'detail',
'#description' => $this->t('<p>These are the fields available in the destination plugin of this migration task. The machine names are those available to be used as the keys in the process pipeline.</p>'),
'#description_display' => 'after',
'#attributes' => [
'id' => 'migration-detail-destination',
],
];
$destination = $migration_plugin->getDestinationPlugin();
$build['destination']['type'] = [
'#type' => 'item',
'#title' => $this->t('Type'),
'#markup' => Xss::filterAdmin($destination->getPluginId()),
];
$header = [$this->t('Machine name'), $this->t('Description')];
$rows = [];
$destination_fields = $destination->fields() ?: [];
foreach ($destination_fields as $machine_name => $description) {
$rows[] = [
['data' => Html::escape($machine_name)],
['data' => Xss::filterAdmin($description)],
];
}
$build['destination']['fields'] = [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t('No fields'),
];
return $build;
}
}
@@ -0,0 +1,72 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Controller;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
/**
* Provides a listing of migration group entities.
*
* @package Drupal\migrate_tools\Controller
*
* @ingroup migrate_tools
*/
class MigrationGroupListBuilder extends ConfigEntityListBuilder {
/**
* Builds the header row for the entity listing.
*
* @return array
* A render array structure of header strings.
*
* @see \Drupal\Core\Entity\Controller\EntityListController::render()
*/
public function buildHeader(): array {
$header = [];
$header['label'] = $this->t('Migration Group');
$header['machine_name'] = $this->t('Machine Name');
$header['description'] = $this->t('Description');
$header['source_type'] = $this->t('Source Type');
return $header + parent::buildHeader();
}
/**
* Builds a row for an entity in the entity listing.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity for which to build the row.
*
* @return array
* A render array of the table row for displaying the entity.
*
* @see \Drupal\Core\Entity\EntityListController::render()
*/
public function buildRow(EntityInterface $entity): array {
$row = [];
$row['label'] = $entity->label();
$row['machine_name'] = $entity->id();
$row['description'] = $entity->get('description');
$row['source_type'] = $entity->get('source_type');
return $row + parent::buildRow($entity);
}
/**
* {@inheritdoc}
*/
public function getDefaultOperations(EntityInterface $entity): array {
$operations = parent::getDefaultOperations($entity);
$operations['list'] = [
'title' => $this->t('List migrations'),
'weight' => 0,
'url' => Url::fromRoute('entity.migration.list', ['migration_group' => $entity->id()]),
];
return $operations;
}
}
@@ -0,0 +1,247 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Controller;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Url;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Drupal\migrate_plus\Entity\Migration;
use Drupal\migrate_plus\Entity\MigrationGroup;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a listing of migration entities in a given group.
*
* @package Drupal\migrate_tools\Controller
*
* @ingroup migrate_tools
*/
class MigrationListBuilder extends ConfigEntityListBuilder implements EntityHandlerInterface {
protected CurrentRouteMatch $currentRouteMatch;
protected MigrationPluginManagerInterface $migrationPluginManager;
protected LoggerInterface $logger;
/**
* Constructs a new EntityListBuilder object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The entity storage class.
* @param \Drupal\Core\Routing\CurrentRouteMatch $current_route_match
* The current route match service.
* @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migration_plugin_manager
* The plugin manager for config entity-based migrations.
* @param \Psr\Log\LoggerInterface $logger
* The logger service.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, CurrentRouteMatch $current_route_match, MigrationPluginManagerInterface $migration_plugin_manager, LoggerInterface $logger) {
parent::__construct($entity_type, $storage);
$this->currentRouteMatch = $current_route_match;
$this->migrationPluginManager = $migration_plugin_manager;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type): self {
return new static(
$entity_type,
$container->get('entity_type.manager')->getStorage($entity_type->id()),
$container->get('current_route_match'),
$container->get('plugin.manager.migration'),
$container->get('logger.channel.migrate_tools')
);
}
/**
* Retrieve the migrations belonging to the appropriate group.
*
* @return array
* An array of entity IDs.
*/
protected function getEntityIds(): array {
$migration_group = $this->currentRouteMatch->getParameter('migration_group');
$query = $this->getStorage()->getQuery()
->accessCheck(TRUE)
->sort($this->entityType->getKey('id'));
$migration_groups = MigrationGroup::loadMultiple();
if (array_key_exists($migration_group, $migration_groups)) {
$query->condition('migration_group', $migration_group);
}
else {
$query->notExists('migration_group');
}
// Only add the pager if a limit is specified.
if ($this->limit) {
$query->pager($this->limit);
}
return $query->execute();
}
/**
* Builds the header row for the entity listing.
*
* @return array
* A render array structure of header strings.
*
* @see \Drupal\Core\Entity\EntityListController::render()
*/
public function buildHeader(): array {
$header = [];
$header['label'] = $this->t('Migration');
$header['machine_name'] = $this->t('Machine Name');
$header['status'] = $this->t('Status');
$header['total'] = $this->t('Total');
$header['imported'] = $this->t('Imported');
$header['unprocessed'] = $this->t('Unprocessed');
$header['messages'] = $this->t('Messages');
$header['last_imported'] = $this->t('Last Imported');
$header['operations'] = $this->t('Operations');
return $header;
}
/**
* Builds a row for a migration plugin.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The migration plugin for which to build the row.
*
* @return array
* A render array of the table row for displaying the plugin information.
*
* @see \Drupal\Core\Entity\EntityListController::render()
*/
public function buildRow(EntityInterface $entity): array {
$row = [];
try {
assert($entity instanceof Migration);
$migration = $this->migrationPluginManager->createInstance($entity->id());
if (!$migration) {
return $row;
}
$migration_group = $entity->get('migration_group');
if (!$migration_group) {
$migration_group = 'default';
}
$route_parameters = [
'migration_group' => $migration_group,
'migration' => $migration->id(),
];
$row['label'] = [
'data' => [
'#type' => 'link',
'#title' => $migration->label(),
'#url' => Url::fromRoute("entity.migration.overview", $route_parameters),
],
];
$row['machine_name'] = $migration->id();
$row['status'] = $migration->getStatusLabel();
}
catch (\Exception $e) {
$this->logger->warning('Migration entity id %id is malformed: %orig', [
'%id' => $entity->id(),
'%orig' => $e->getMessage(),
]);
return $row;
}
try {
// Derive the stats.
$source_plugin = $migration->getSourcePlugin();
$row['total'] = $source_plugin->count();
$map = $migration->getIdMap();
$row['imported'] = $map->importedCount();
// -1 indicates uncountable sources.
if ($row['total'] == -1) {
$row['total'] = $this->t('N/A');
$row['unprocessed'] = $this->t('N/A');
}
else {
$row['unprocessed'] = $row['total'] - $map->processedCount();
}
$row['messages'] = [
'data' => [
'#type' => 'link',
'#title' => $map->messageCount(),
'#url' => Url::fromRoute("migrate_tools.messages", $route_parameters),
],
];
$migrate_last_imported_store = \Drupal::keyValue('migrate_last_imported');
$last_imported = $migrate_last_imported_store->get($migration->id(), FALSE);
if ($last_imported) {
/** @var \Drupal\Core\Datetime\DateFormatter $date_formatter */
$date_formatter = \Drupal::service('date.formatter');
$row['last_imported'] = $date_formatter->format((int) ($last_imported / 1000),
'custom', 'Y-m-d H:i:s');
}
else {
$row['last_imported'] = '';
}
$row['operations']['data'] = [
'#type' => 'dropbutton',
'#links' => [
'simple_form' => [
'title' => $this->t('Execute'),
'url' => Url::fromRoute('migrate_tools.execute', [
'migration_group' => $migration_group,
'migration' => $migration->id(),
]),
],
],
];
}
catch (\Throwable $throwable) {
$this->handleThrowable($row);
}
return $row;
}
/**
* Derive the row data.
*
* @param array $row
* The table row.
*/
protected function handleThrowable(array &$row): void {
$row['status'] = $this->t('No data found');
$row['total'] = $this->t('N/A');
$row['imported'] = $this->t('N/A');
$row['unprocessed'] = $this->t('N/A');
$row['messages'] = $this->t('N/A');
$row['last_imported'] = $this->t('N/A');
$row['operations'] = $this->t('N/A');
}
/**
* Add group route parameter.
*
* @param \Drupal\Core\Url $url
* The URL associated with an operation.
* @param string $migration_group
* The migration's parent group.
*/
protected function addGroupParameter(Url $url, $migration_group): void {
if (!$migration_group) {
$migration_group = 'default';
}
$route_parameters = $url->getRouteParameters() + ['migration_group' => $migration_group];
$url->setRouteParameters($route_parameters);
}
}
@@ -0,0 +1,55 @@
<?php
namespace Drupal\migrate_tools\Discovery;
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
use Drupal\Core\Plugin\Discovery\YamlDirectoryDiscovery;
/**
* Extends YAML directory discovery to allow BC with single-file discovery.
*
* @todo Mark plugins from the decorated discovery as deprecated.
*
* @todo Remove this in 7.0.0 and use YamlDirectoryDiscovery directly.
*/
class YamlDiscoveryDecorator extends YamlDirectoryDiscovery {
/**
* The Discovery object being decorated.
*
* @var \Drupal\Component\Plugin\Discovery\DiscoveryInterface
*/
protected $decorated;
/**
* Constructs a YamlDiscoveryDecorator object.
*
* @param \Drupal\Component\Plugin\Discovery\DiscoveryInterface $decorated
* The discovery object that is being decorated.
* @param string $name
* The file name suffix to use for discovery; for instance, 'test' will
* become 'MODULE.test.yml'.
* @param array $directories
* An array of directories to scan.
*/
public function __construct(DiscoveryInterface $decorated, array $directories, $file_cache_key_suffix, $key = 'id') {
parent::__construct($directories, $file_cache_key_suffix, $key);
$this->decorated = $decorated;
}
/**
* {@inheritdoc}
*/
public function getDefinitions() {
return parent::getDefinitions() + $this->decorated->getDefinitions();
}
/**
* Passes through all unknown calls onto the decorated object.
*/
public function __call($method, $args) {
return call_user_func_array([$this->decorated, $method], $args);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,50 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\migrate\MigrateMessageInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
/**
* Print message in drush from migrate message. Drush 9 version.
*
* @package Drupal\migrate_tools
*/
class Drush9LogMigrateMessage implements MigrateMessageInterface, LoggerAwareInterface {
use LoggerAwareTrait;
/**
* The map between migrate status and drush log levels.
*
* @var array
*/
protected array $map = [
'status' => 'notice',
];
/**
* DrushLogMigrateMessage constructor.
*/
public function __construct(LoggerInterface $logger) {
$this->setLogger($logger);
}
/**
* Output a message from the migration.
*
* @param string $message
* The message to display.
* @param string $type
* The type of message to display.
*/
public function display($message, $type = 'status'): void {
$type = $this->map[$type] ?? $type;
$this->logger->log($type, $message);
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\MigrateMessageInterface;
/**
* Logger implementation for drush.
*
* @package Drupal\migrate_tools
*/
class DrushLogMigrateMessage extends MigrateMessage implements MigrateMessageInterface {
/**
* Output a message from the migration.
*
* @param string $message
* The message to display.
* @param string $type
* The type of message to display.
*
* @see drush_log()
*/
public function display($message, $type = 'status'): void {
$type = $this->map[$type] ?? RfcLogLevel::NOTICE;
\Drupal::service(('logger.channel.migrate_tools'))->log($type, $message);
}
}
@@ -0,0 +1,119 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\EventSubscriber;
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Plugin\MigrationInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Import and rollback progress bar.
*/
class MigrationDrushCommandProgress implements EventSubscriberInterface {
protected LoggerInterface $logger;
protected ?ProgressBar $symfonyProgressBar = NULL;
/**
* MigrationDrushCommandProgress constructor.
*
* @param \Psr\Log\LoggerInterface $logger
* The logger service.
*/
public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[MigrateEvents::POST_ROW_SAVE][] = ['updateProgressBar', -10];
$events[MigrateEvents::MAP_DELETE][] = ['updateProgressBar', -10];
$events[MigrateEvents::POST_IMPORT][] = ['clearProgress', 10];
$events[MigrateEvents::POST_ROLLBACK][] = ['clearProgress', 10];
return $events;
}
/**
* Initializes the progress bar.
*
* This must be called before the progress bar can be used.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* The output.
* @param \Drupal\migrate\Plugin\MigrationInterface $migration
* The migration.
* @param array $options
* Additional options of the command.
*/
public function initializeProgress(OutputInterface $output, MigrationInterface $migration, array $options = []): void {
// Don't display progress bar if explicitly disabled.
if (!empty($migration->skipProgressBar)) {
return;
}
// If the source is configured to skip counts, a progress bar is not
// possible.
if (!empty($migration->getSourceConfiguration()['skip_count'])) {
return;
}
try {
// Clone so that any generators aren't initialized prematurely.
$source = clone $migration->getSourcePlugin();
$count = (int) $source->count();
// In case the --limit option is set, reduce the count.
if (array_key_exists('limit', $options) && $options['limit'] > 0 && $options['limit'] < $count) {
$count = (int) $options['limit'];
}
$this->symfonyProgressBar = new ProgressBar($output, $count);
}
catch (\Exception $exception) {
if (!empty($migration->continueOnFailure)) {
$this->logger->error($exception->getMessage());
}
else {
throw $exception;
}
}
}
/**
* Event callback for advancing the progress bar.
*/
public function updateProgressBar(): void {
if ($this->isProgressBar()) {
$this->symfonyProgressBar->advance();
}
}
/**
* Event callback for removing the progress bar after operation is finished.
*/
public function clearProgress(): void {
if ($this->isProgressBar()) {
$this->symfonyProgressBar->clear();
}
}
/**
* Determine if a progress bar should be displayed.
*
* @return bool
* TRUE if a progress bar should be displayed, FALSE otherwise.
*/
protected function isProgressBar(): bool {
// Can't do anything if the progress bar is not initialised; this probably
// means we're not running as a Drush command, therefore do nothing.
if ($this->symfonyProgressBar === NULL) {
return FALSE;
}
return TRUE;
}
}
@@ -0,0 +1,143 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\EventSubscriber;
use Drupal\Core\State\StateInterface;
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateImportEvent;
use Drupal\migrate\Event\MigrateRollbackEvent;
use Drupal\migrate\Event\MigrateRowDeleteEvent;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_plus\Event\MigrateEvents as MigratePlusEvents;
use Drupal\migrate_tools\MigrateTools;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Import and sync source and destination.
*/
class MigrationImportSync implements EventSubscriberInterface {
protected EventDispatcherInterface $dispatcher;
protected MigrateTools $migrateTools;
/**
* MigrationImportSync constructor.
*
* @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
* The event dispatcher.
*/
public function __construct(EventDispatcherInterface $dispatcher, MigrateTools $migrateTools) {
$this->dispatcher = $dispatcher;
$this->migrateTools = $migrateTools;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[MigrateEvents::PRE_IMPORT][] = ['sync'];
$events[MigrateEvents::POST_IMPORT][] = ['cleanSyncData'];
return $events;
}
/**
* Event callback to sync source and destination.
*
* @param \Drupal\migrate\Event\MigrateImportEvent $event
* The migration import event.
*
* @throws \Exception
*/
public function sync(MigrateImportEvent $event): void {
$migration = $event->getMigration();
if (!empty($migration->syncSource)) {
$migrationId = $migration->getPluginId();
// Clear Sync IDs for this migration before starting preparing rows.
$this->migrateTools->clearSyncSourceIds($migrationId);
// Activate the syncing state for this migration, so
// migrate_tools_migrate_prepare_row() can record all IDs.
$this->migrateTools->setMigrationSyncingState($migrationId, TRUE);
// Loop through the source to register existing source ids.
// @see migrate_tools_migrate_prepare_row().
// Clone so that any generators aren't initialized prematurely.
$source = clone $migration->getSourcePlugin();
$source->rewind();
while ($source->valid()) {
$source->next();
}
// Deactivate the syncing state for this migration, so
// migrate_tools_migrate_prepare_row() does not record any further IDs
// during the actual migration process.
$this->migrateTools->setMigrationSyncingState($migrationId, FALSE);
$source_id_values = $this->migrateTools->getSyncSourceIds($migrationId);
$id_map = $migration->getIdMap();
$id_map->rewind();
$destination = $migration->getDestinationPlugin();
while ($id_map->valid()) {
$map_source_id = $id_map->currentSource();
foreach ($source->getIds() as $id_key => $id_config) {
if ($id_config['type'] === 'string') {
$map_source_id[$id_key] = (string) $map_source_id[$id_key];
}
elseif ($id_config['type'] === 'integer') {
$map_source_id[$id_key] = (int) $map_source_id[$id_key];
}
}
if (!in_array($map_source_id, $source_id_values, TRUE)) {
$destination_ids = $id_map->currentDestination();
if ($destination_ids !== NULL) {
$this->dispatchRowDeleteEvent(MigrateEvents::PRE_ROW_DELETE, $migration, $destination_ids);
if (class_exists(MigratePlusEvents::class)) {
$this->dispatchRowDeleteEvent(MigratePlusEvents::MISSING_SOURCE_ITEM, $migration, $destination_ids);
}
$destination->rollback($destination_ids);
$this->dispatchRowDeleteEvent(MigrateEvents::POST_ROW_DELETE, $migration, $destination_ids);
}
$id_map->delete($map_source_id);
}
$id_map->next();
}
$this->dispatcher->dispatch(new MigrateRollbackEvent($migration), MigrateEvents::POST_ROLLBACK);
}
}
/**
* Cleans Sync data after a migration is complete.
*
* @param \Drupal\migrate\Event\MigrateImportEvent $event
* The migration import event.
*/
public function cleanSyncData(MigrateImportEvent $event): void {
$migration = $event->getMigration();
$migrationId = $migration->getPluginId();
$this->migrateTools->clearSyncSourceIds($migrationId);
}
/**
* Dispatches MigrateRowDeleteEvent event.
*
* @param string $event_name
* The event name to dispatch.
* @param \Drupal\migrate\Plugin\MigrationInterface $migration
* The active migration.
* @param array $destination_ids
* The destination identifier values of the record.
*/
protected function dispatchRowDeleteEvent(string $event_name, MigrationInterface $migration, array $destination_ids): void {
// Symfony changing dispatcher so implementation could change.
$this->dispatcher->dispatch(new MigrateRowDeleteEvent($migration, $destination_ids), $event_name);
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Form\FormStateInterface;
/**
* Class MigrationAddForm.
*
* Provides the add form for our migration entity.
*
* @package Drupal\migrate_tools\Form
*
* @ingroup migrate_tools
*/
class MigrationAddForm extends MigrationFormBase {
/**
* Returns the actions provided by this form.
*
* For our add form, we only need to change the text of the submit button.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*
* @return array
* An array of supported actions for the current entity form.
*/
protected function actions(array $form, FormStateInterface $form_state): array {
$actions = parent::actions($form, $form_state);
unset($actions['submit']);
return $actions;
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
/**
* Provides the delete form for our Migration entity.
*
* @package Drupal\migrate_tools\Form
*
* @ingroup migrate_tools
*/
class MigrationDeleteForm extends EntityConfirmFormBase {
/**
* Gathers a confirmation question.
*
* @return string
* Translated string.
*/
public function getQuestion(): TranslatableMarkup {
return $this->t('Are you sure you want to delete migration %label?', [
'%label' => $this->entity->label(),
]);
}
/**
* Gather the confirmation text.
*
* @return string
* Translated string.
*/
public function getConfirmText(): TranslatableMarkup {
return $this->t('Delete Migration');
}
/**
* Gets the cancel URL.
*
* @return \Drupal\Core\Url
* The URL to go to if the user cancels the deletion.
*/
public function getCancelUrl(): Url {
return new Url('entity.migration_group.list');
}
/**
* The submit handler for the confirm form.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
// Delete the entity.
$this->entity->delete();
// Set a message that the entity was deleted.
$this->messenger()->addStatus($this->t('Migration %label was deleted.', [
'%label' => $this->entity->label(),
]));
// Redirect the user to the list controller when complete.
$form_state->setRedirectUrl($this->getCancelUrl());
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Provides the edit form for our Migration entity.
*
* @package Drupal\migrate_tools\Form
*
* @ingroup migrate_tools
*/
class MigrationEditForm extends MigrationFormBase {
/**
* Returns the actions provided by this form.
*
* For the edit form, we only need to change the text of the submit button.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*
* @return array
* An array of supported actions for the current entity form.
*/
public function actions(array $form, FormStateInterface $form_state): array {
$actions = parent::actions($form, $form_state);
$actions['submit']['#value'] = $this->t('Update Migration');
return $actions;
}
/**
* Add group route parameter.
*
* @param \Drupal\Core\Url $url
* The URL associated with an operation.
* @param string $migration_group
* The migration's parent group.
*/
protected function addGroupParameter(Url $url, string $migration_group): void {
$route_parameters = $url->getRouteParameters() + ['migration_group' => $migration_group];
$url->setRouteParameters($route_parameters);
}
}
@@ -0,0 +1,265 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Drupal\migrate_tools\MigrateBatchExecutable;
use Drupal\migrate_tools\MigrateTools;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* This form is specifically for configuring process pipelines.
*/
class MigrationExecuteForm extends FormBase {
/**
* Plugin manager for migration plugins.
*/
protected MigrationPluginManagerInterface $migrationPluginManager;
/**
* Constructs a new MigrationExecuteForm object.
*
* @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migration_plugin_manager
* The plugin manager for config entity-based migrations.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The current route match.
*/
public function __construct(MigrationPluginManagerInterface $migration_plugin_manager, RouteMatchInterface $route_match) {
$this->migrationPluginManager = $migration_plugin_manager;
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container): self {
return new static(
$container->get('plugin.manager.migration'),
$container->get('current_route_match')
);
}
/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'migration_execute_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$form = $form ?: [];
/** @var \Drupal\migrate_plus\Entity\MigrationInterface $migration */
$migration = $this->getRouteMatch()->getParameter('migration');
$form['#title'] = $this->t('Execute migration %label', ['%label' => $migration->label()]);
$form = $this->buildFormOperations($form, $form_state);
$form = $this->buildFormOptions($form, $form_state);
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Execute'),
];
return $form;
}
/**
* Build the operation form field.
*
* @param array $form
* The execution form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* The execution form updated with the operations.
*/
protected function buildFormOperations(array $form, FormStateInterface $form_state): array {
// Build the migration execution form.
$options = [
'import' => $this->t('Import'),
'rollback' => $this->t('Rollback'),
'stop' => $this->t('Stop'),
'reset' => $this->t('Reset'),
];
$form['operation'] = [
'#type' => 'radios',
'#title' => $this->t('Operation'),
'#description' => $this->t('Choose an operation to run.'),
'#options' => $options,
'#default_value' => 'import',
'#required' => TRUE,
'import' => [
'#description' => $this->t('Imports all previously unprocessed records from the source, plus any records marked for update, into destination Drupal objects.'),
],
'rollback' => [
'#description' => $this->t('Deletes all Drupal objects created by the import.'),
],
'stop' => [
'#description' => $this->t('Cleanly interrupts any import or rollback processes that may currently be running.'),
],
'reset' => [
'#description' => $this->t('Sometimes a process may fail to stop cleanly, and be left stuck in an Importing or Rolling Back status. Choose Reset to clear the status and permit other operations to proceed.'),
],
];
return $form;
}
/**
* Build the execution options form field.
*
* @param array $form
* The execution form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* The execution form updated with the execution options.
*/
protected function buildFormOptions(array $form, FormStateInterface $form_state): array {
$form['options'] = [
'#type' => 'details',
'#title' => $this->t('Additional execution options'),
'#open' => FALSE,
];
$form['options']['update'] = [
'#type' => 'checkbox',
'#title' => $this->t('Update'),
'#description' => $this->t('Check this box to update all previously-imported content in addition to importing new content. Leave unchecked to only import new content'),
];
$form['options']['force'] = [
'#type' => 'checkbox',
'#title' => $this->t('Ignore dependencies'),
'#description' => $this->t('Check this box to ignore dependencies when running imports - all tasks will run whether or not their dependent tasks have completed.'),
];
$form['options']['limit'] = [
'#type' => 'number',
'#title' => $this->t('Limit to:'),
'#size' => 10,
'#description' => $this->t('Set a limit of how many items to process for each migration task.'),
'#min' => 1,
];
$form['options']['idlist'] = [
'#type' => 'textfield',
'#title' => $this->t('ID List'),
'#maxlength' => 255,
'#size' => 60,
'#pattern' => '^[0-9]+(' . MigrateTools::DEFAULT_ID_LIST_DELIMITER . '[0-9]+)?(,?[0-9]+(' . MigrateTools::DEFAULT_ID_LIST_DELIMITER . '[0-9]+)?)*$',
'#description' => $this->t('Comma-separated list of IDs to process.'),
'#states' => [
'enabled' => [
':input[name="operation"]' => [['value' => 'import'], 'or', ['value' => 'rollback']],
],
],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$migration = $this->getRouteMatch()->getParameter('migration');
if ($migration) {
$migration_id = $migration->id();
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration_plugin */
$migration_plugin = $this->migrationPluginManager->createInstance($migration_id, $migration->toArray());
$migrateMessage = new MigrateMessage();
switch ($form_state->getValue('operation')) {
case 'import':
$executable = new MigrateBatchExecutable($migration_plugin, $migrateMessage, $this->buildOptions($form_state));
$executable->batchImport();
break;
case 'rollback':
$executable = new MigrateBatchExecutable($migration_plugin, $migrateMessage, $this->buildOptions($form_state));
$status = $executable->rollback();
if ($status === MigrationInterface::RESULT_COMPLETED) {
$this->messenger()->addStatus($this->t('Rollback completed', ['@id' => $migration_id]));
}
else {
$this->messenger()->addError($this->t('Rollback of !name migration failed.', ['!name' => $migration_id]));
}
break;
case 'stop':
$migration_plugin->interruptMigration(MigrationInterface::RESULT_STOPPED);
$status = $migration_plugin->getStatus();
switch ($status) {
case MigrationInterface::STATUS_IDLE:
$this->messenger()->addStatus($this->t('Migration @id is idle', ['@id' => $migration_id]));
break;
case MigrationInterface::STATUS_DISABLED:
$this->messenger()->addWarning($this->t('Migration @id is disabled', ['@id' => $migration_id]));
break;
case MigrationInterface::STATUS_STOPPING:
$this->messenger()->addWarning($this->t('Migration @id is already stopping', ['@id' => $migration_id]));
break;
default:
$migration->interruptMigration(MigrationInterface::RESULT_STOPPED);
$this->messenger()->addStatus($this->t('Migration @id requested to stop', ['@id' => $migration_id]));
break;
}
break;
case 'reset':
$status = $migration_plugin->getStatus();
if ($status === MigrationInterface::STATUS_IDLE) {
$this->messenger()->addWarning($this->t('Migration @id is already Idle', ['@id' => $migration_id]));
}
else {
$this->messenger()->addStatus($this->t('Migration @id reset to Idle', ['@id' => $migration_id]));
}
$migration_plugin->setStatus(MigrationInterface::STATUS_IDLE);
break;
}
}
}
/**
* Build migrate execute options from the submitted form values.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* Options array for the migrate execution.
*/
protected function buildOptions(FormStateInterface $form_state) {
$options = [
'limit' => $form_state->getValue('limit') ?: 0,
'update' => $form_state->getValue('update') ?: 0,
'force' => $form_state->getValue('force') ?: 0,
];
if ($idlist = $form_state->getValue('idlist')) {
$options['idlist'] = $idlist;
}
return $options;
}
}
@@ -0,0 +1,157 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\migrate_plus\Entity\Migration;
use Drupal\migrate_plus\Entity\MigrationGroup;
/**
* Base form for a migration.
*
* @package Drupal\migrate_tools\Form
*
* @ingroup migrate_tools
*/
class MigrationFormBase extends EntityForm {
/**
* Overrides Drupal\Core\Entity\EntityFormController::form().
*
* Builds the entity add/edit form.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*
* @return array
* An associative array containing the migration add/edit form.
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
// Get anything we need from the base class.
$form = parent::buildForm($form, $form_state);
$migration = $this->entity;
assert($migration instanceof Migration);
$form['warning'] = [
'#markup' => $this->t('Creating migrations is not yet supported. See <a href=":url">:url</a>', [
':url' => 'https://www.drupal.org/node/2573241',
]),
];
// Build the form.
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#maxlength' => 255,
'#default_value' => $migration->label(),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#title' => $this->t('Machine name'),
'#default_value' => $migration->id(),
'#machine_name' => [
'exists' => [$this, 'exists'],
'replace_pattern' => '([^a-z0-9_]+)|(^custom$)',
'error' => 'The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".',
],
'#disabled' => !$migration->isNew(),
];
$groups = MigrationGroup::loadMultiple();
$group_options = [];
foreach ($groups as $group) {
$group_options[$group->id()] = $group->label();
}
if (!$migration->migration_group && isset($group_options['default'])) {
$migration->set('migration_group', 'default');
}
$form['migration_group'] = [
'#type' => 'select',
'#title' => $this->t('Migration Group'),
'#empty_value' => '',
'#default_value' => $migration->migration_group,
'#options' => $group_options,
'#description' => $this->t('Assign this migration to an existing group.'),
];
return $form;
}
/**
* Checks for an existing migration group.
*
* @param string|int $entity_id
* The entity ID.
* @param array $element
* The form element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return bool
* TRUE if this format already exists, FALSE otherwise.
*/
public function exists($entity_id, array $element, FormStateInterface $form_state): bool {
$query = $this->entityTypeManager->getStorage('migration')
->getQuery()
->accessCheck(TRUE);
// Query the entity ID to see if its in use.
$result = $query->condition('id', $element['#field_prefix'] . $entity_id)
->execute();
// We don't need to return the ID, only if it exists or not.
return (bool) $result;
}
/**
* Overrides Drupal\Core\Entity\EntityFormController::actions().
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*
* @return array
* An array of supported actions for the current entity form.
*/
protected function actions(array $form, FormStateInterface $form_state): array {
// Get the basic actions from the base class.
$actions = parent::actions($form, $form_state);
// Change the submit button text.
$actions['submit']['#value'] = $this->t('Save');
// Return the result.
return $actions;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state): void {
$migration = $this->getEntity();
$status = $migration->save();
if ($status == SAVED_UPDATED) {
// If we edited an existing entity...
$this->messenger()->addStatus($this->t('Migration %label has been updated.', ['%label' => $migration->label()]));
}
else {
// If we created a new entity...
$this->messenger()->addStatus($this->t('Migration %label has been added.', ['%label' => $migration->label()]));
}
// Redirect the user back to the listing route after the save operation.
$form_state->setRedirect('entity.migration.list',
['migration_group' => $migration->get('migration_group')]);
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Form\FormStateInterface;
/**
* Class MigrationGroupAddForm.
*
* Provides the add form for our migration_group entity.
*
* @package Drupal\migrate_tools\Form
*
* @ingroup migrate_tools
*/
class MigrationGroupAddForm extends MigrationGroupFormBase {
/**
* Returns the actions provided by this form.
*
* For our add form, we only need to change the text of the submit button.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*
* @return array
* An array of supported actions for the current entity form.
*/
protected function actions(array $form, FormStateInterface $form_state): array {
$actions = parent::actions($form, $form_state);
$actions['submit']['#value'] = $this->t('Create Migration Group');
return $actions;
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
/**
* Provides the delete form for our Migration Group entity.
*
* @package Drupal\migrate_tools\Form
*
* @ingroup migrate_tools
*/
class MigrationGroupDeleteForm extends EntityConfirmFormBase {
/**
* Gathers a confirmation question.
*
* @return string
* Translated string.
*/
public function getQuestion(): TranslatableMarkup {
return $this->t('Are you sure you want to delete migration group %label?', [
'%label' => $this->entity->label(),
]);
}
/**
* Gather the confirmation text.
*
* @return string
* Translated string.
*/
public function getConfirmText(): TranslatableMarkup {
return $this->t('Delete Migration Group');
}
/**
* Gets the cancel URL.
*
* @return \Drupal\Core\Url
* The URL to go to if the user cancels the deletion.
*/
public function getCancelUrl(): Url {
return new Url('entity.migration_group.list');
}
/**
* The submit handler for the confirm form.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
// Delete the entity.
$this->entity->delete();
// Set a message that the entity was deleted.
$this->messenger()->addStatus($this->t('Migration group %label was deleted.', [
'%label' => $this->entity->label(),
]));
// Redirect the user to the list controller when complete.
$form_state->setRedirectUrl($this->getCancelUrl());
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides the edit form for our Migration Group entity.
*
* @package Drupal\migrate_tools\Form
*
* @ingroup migrate_tools
*/
class MigrationGroupEditForm extends MigrationGroupFormBase {
/**
* Returns the actions provided by this form.
*
* For the edit form, we only need to change the text of the submit button.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*
* @return array
* An array of supported actions for the current entity form.
*/
public function actions(array $form, FormStateInterface $form_state): array {
$actions = parent::actions($form, $form_state);
$actions['submit']['#value'] = $this->t('Update Migration Group');
return $actions;
}
}
@@ -0,0 +1,144 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
/**
* Base form for migration groups.
*
* @package Drupal\migrate_tools\Form
*
* @ingroup migrate_tools
*/
class MigrationGroupFormBase extends EntityForm {
/**
* Overrides Drupal\Core\Entity\EntityFormController::form().
*
* Builds the entity add/edit form.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*
* @return array
* An associative array containing the migration group add/edit form.
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
// Get anything we need from the base class.
$form = parent::buildForm($form, $form_state);
/** @var \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group */
$migration_group = $this->entity;
// Build the form.
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#maxlength' => 255,
'#default_value' => $migration_group->label(),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#title' => $this->t('Machine name'),
'#default_value' => $migration_group->id(),
'#machine_name' => [
'exists' => [$this, 'exists'],
'replace_pattern' => '([^a-z0-9_]+)|(^custom$)',
'error' => 'The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".',
],
'#disabled' => !$migration_group->isNew(),
];
$form['description'] = [
'#type' => 'textfield',
'#title' => $this->t('Description'),
'#maxlength' => 255,
'#default_value' => $migration_group->get('description'),
];
$form['source_type'] = [
'#type' => 'textfield',
'#title' => $this->t('Source type'),
'#description' => $this->t('Type of source system the group is migrating from, for example "Drupal 6" or "WordPress 4".'),
'#maxlength' => 255,
'#default_value' => $migration_group->get('source_type'),
];
// Return the form.
return $form;
}
/**
* Checks for an existing migration group.
*
* @param string|int $entity_id
* The entity ID.
* @param array $element
* The form element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return bool
* TRUE if this format already exists, FALSE otherwise.
*/
public function exists($entity_id, array $element, FormStateInterface $form_state): bool {
$query = $this->entityTypeManager->getStorage('migration_group')
->getQuery()
->accessCheck(TRUE);
// Query the entity ID to see if its in use.
$result = $query->condition('id', $element['#field_prefix'] . $entity_id)
->execute();
// We don't need to return the ID, only if it exists or not.
return (bool) $result;
}
/**
* Overrides Drupal\Core\Entity\EntityFormController::actions().
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* An associative array containing the current state of the form.
*
* @return array
* An array of supported actions for the current entity form.
*/
protected function actions(array $form, FormStateInterface $form_state): array {
// Get the basic actions from the base class.
$actions = parent::actions($form, $form_state);
// Change the submit button text.
$actions['submit']['#value'] = $this->t('Save');
// Return the result.
return $actions;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state): void {
$migration_group = $this->getEntity();
$status = $migration_group->save();
if ($status == SAVED_UPDATED) {
// If we edited an existing entity...
$this->messenger()->addStatus($this->t('Migration group %label has been updated.', ['%label' => $migration_group->label()]));
}
else {
// If we created a new entity...
$this->messenger()->addStatus($this->t('Migration group %label has been added.', ['%label' => $migration_group->label()]));
}
// Redirect the user back to the listing route after the save operation.
$form_state->setRedirect('entity.migration_group.list');
}
}
@@ -0,0 +1,273 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\migrate\MigrateMessageInterface;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
/**
* Class to filter ID map by an ID list.
*/
class IdMapFilter extends \FilterIterator implements MigrateIdMapInterface {
/**
* List of specific source IDs to import.
*/
protected array $idList;
/**
* IdMapFilter constructor.
*
* @param \Drupal\migrate\Plugin\MigrateIdMapInterface $id_map
* The ID map.
* @param array $id_list
* The id list to use in the filter.
*/
public function __construct(MigrateIdMapInterface $id_map, array $id_list) {
parent::__construct($id_map);
$this->idList = $id_list;
}
/**
* {@inheritdoc}
*/
public function accept(): bool {
// Row is included.
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
if (empty($this->idList) || in_array(array_values($this->currentSource()), $this->idList)) {
return TRUE;
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function saveIdMapping(Row $row, array $destination_id_values, $status = self::STATUS_IMPORTED, $rollback_action = self::ROLLBACK_DELETE): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->saveIdMapping($row, $destination_id_values, $status, $rollback_action);
}
/**
* {@inheritdoc}
*/
public function saveMessage(array $source_id_values, $message, $level = MigrationInterface::MESSAGE_ERROR): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->saveMessage($source_id_values, $message, $level);
}
/**
* {@inheritdoc}
*/
public function getMessages(array $source_id_values = [], $level = NULL): \Traversable {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->getMessages($source_id_values, $level);
}
/**
* {@inheritdoc}
*/
public function prepareUpdate(): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->prepareUpdate();
}
/**
* {@inheritdoc}
*/
public function processedCount(): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->processedCount();
}
/**
* {@inheritdoc}
*/
public function importedCount(): int {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->importedCount();
}
/**
* {@inheritdoc}
*/
public function updateCount(): int {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->updateCount();
}
/**
* {@inheritdoc}
*/
public function errorCount(): int {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->errorCount();
}
/**
* {@inheritdoc}
*/
public function messageCount(): int {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->messageCount();
}
/**
* {@inheritdoc}
*/
public function delete(array $source_id_values, $messages_only = FALSE): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->delete($source_id_values, $messages_only);
}
/**
* {@inheritdoc}
*/
public function deleteDestination(array $destination_id_values): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->deleteDestination($destination_id_values);
}
/**
* {@inheritdoc}
*/
public function clearMessages(): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->clearMessages();
}
/**
* {@inheritdoc}
*/
public function getRowBySource(array $source_id_values): array {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->getRowBySource($source_id_values);
}
/**
* {@inheritdoc}
*/
public function getRowByDestination(array $destination_id_values): array {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->getRowByDestination($destination_id_values);
}
/**
* {@inheritdoc}
*/
public function getRowsNeedingUpdate($count): array {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->getRowsNeedingUpdate($count);
}
/**
* {@inheritdoc}
*/
public function lookupSourceId(array $destination_id_values): array {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->lookupSourceId($destination_id_values);
}
/**
* {@inheritdoc}
*/
public function lookupDestinationIds(array $source_id_values): array {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->lookupDestinationIds($source_id_values);
}
/**
* {@inheritdoc}
*/
public function currentDestination(): array {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->currentDestination();
}
/**
* {@inheritdoc}
*/
public function currentSource(): array {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->currentSource() ?? [];
}
/**
* {@inheritdoc}
*/
public function destroy(): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->destroy();
}
/**
* {@inheritdoc}
*/
public function getQualifiedMapTableName(): string {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->getQualifiedMapTableName();
}
/**
* {@inheritdoc}
*/
public function setMessage(MigrateMessageInterface $message): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->setMessage($message);
}
/**
* {@inheritdoc}
*/
public function setUpdate(array $source_id_values): void {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
$map->setUpdate($source_id_values);
}
/**
* {@inheritdoc}
*/
public function getPluginId(): string {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->getPluginId();
}
/**
* {@inheritdoc}
*/
public function getPluginDefinition(): array {
$map = $this->getInnerIterator();
\assert($map instanceof MigrateIdMapInterface);
return $map->getPluginDefinition();
}
}
@@ -0,0 +1,331 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\MigrateMessageInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
/**
* Defines a migrate executable class for batch migrations through UI.
*/
class MigrateBatchExecutable extends MigrateExecutable {
/**
* Representing a batch import operation.
*/
public const BATCH_IMPORT = 1;
/**
* Indicates if we need to update existing rows or skip them.
*
* @var int
*/
protected int $updateExistingRows = 0;
/**
* Indicates if we need import dependent migrations also.
*
* @var int
*/
protected int $checkDependencies = 0;
/**
* The ID list as single string expression.
*
* @var string
*/
protected string $idlistExpression = '';
protected bool $syncSource = FALSE;
protected $batchContext;
protected array $configuration = [];
protected MigrationPluginManagerInterface $migrationPluginManager;
/**
* {@inheritdoc}
*/
public function __construct(MigrationInterface $migration, MigrateMessageInterface $message, array $options = []) {
if (isset($options['update'])) {
$this->updateExistingRows = $options['update'];
}
if (isset($options['force'])) {
$this->checkDependencies = $options['force'];
}
if (isset($options['sync'])) {
$this->syncSource = $options['sync'];
}
if (isset($options['configuration'])) {
$this->configuration = $options['configuration'];
}
if (isset($options['idlist'])) {
$this->idlistExpression = $options['idlist'];
}
parent::__construct($migration, $message, $options);
$this->migrationPluginManager = \Drupal::getContainer()->get('plugin.manager.migration');
}
/**
* Sets the current batch content so listeners can update the messages.
*
* @param array|\DrushBatchContext $context
* The batch context.
*/
public function setBatchContext(&$context): void {
$this->batchContext = &$context;
}
/**
* Gets a reference to the current batch context.
*
* The batch context.
*/
public function &getBatchContext() {
return $this->batchContext;
}
/**
* Setup batch operations for running the migration.
*/
public function batchImport(): void {
// Create the batch operations for each migration that needs to be executed.
// This includes the migration for this executable, but also the dependent
// migrations.
$operations = $this->batchOperations([$this->migration], 'import', [
'limit' => $this->itemLimit,
'update' => $this->updateExistingRows,
'force' => $this->checkDependencies,
'sync' => $this->syncSource,
'idlist' => $this->idlistExpression ?: NULL,
'configuration' => $this->configuration,
]);
if (count($operations) > 0) {
$batch = [
'operations' => $operations,
'title' => $this->t('Migrating %migrate', ['%migrate' => $this->migration->label()]),
'init_message' => $this->t('Start migrating %migrate', ['%migrate' => $this->migration->label()]),
'progress_message' => $this->t('Migrating %migrate', ['%migrate' => $this->migration->label()]),
'error_message' => $this->t('An error occurred while migrating %migrate.', ['%migrate' => $this->migration->label()]),
'finished' => [static::class, 'batchFinishedImport'],
];
batch_set($batch);
}
}
/**
* Helper to generate the batch operations for importing migrations.
*
* @param \Drupal\migrate\Plugin\MigrationInterface[] $migrations
* The migrations.
* @param string $operation
* The batch operation to perform.
* @param array $options
* The migration options.
*
* @return array
* The batch operations to perform.
*/
protected function batchOperations(array $migrations, string $operation, array $options = []): array {
$operations = [];
foreach ($migrations as $migration) {
if (!empty($options['update'])) {
if (empty($options['idlist'])) {
$migration->getIdMap()->prepareUpdate();
}
else {
$source_id_values_list = MigrateTools::buildIdList($options);
$keys = array_keys($migration->getSourcePlugin()->getIds());
foreach ($source_id_values_list as $source_id_values) {
$migration->getIdMap()->setUpdate(array_combine($keys, $source_id_values));
}
}
}
if (!empty($options['force'])) {
$migration->set('requirements', []);
}
else {
$dependencies = $migration->getMigrationDependencies();
if (!empty($dependencies['required'])) {
$required_migrations = $this->migrationPluginManager->createInstances($dependencies['required']);
// For dependent migrations will need to be migrate all items.
$operations = array_merge($operations, $this->batchOperations($required_migrations, $operation, [
'limit' => 0,
'update' => $options['update'],
'force' => $options['force'],
'sync' => $options['sync'],
]));
}
}
$operations[] = [
sprintf('%s::%s', static::class, 'batchProcessImport'),
[$migration->id(), $options],
];
}
return $operations;
}
/**
* Batch 'operation' callback.
*
* @param string $migration_id
* The migration id.
* @param array $options
* The batch executable options.
* @param array|\DrushBatchContext $context
* The sandbox context.
*/
public static function batchProcessImport(string $migration_id, array $options, &$context): void {
if (empty($context['sandbox'])) {
$context['finished'] = 0;
$context['sandbox'] = [];
$context['sandbox']['total'] = 0;
$context['sandbox']['counter'] = 0;
$context['sandbox']['batch_limit'] = 0;
$context['sandbox']['operation'] = self::BATCH_IMPORT;
}
// Prepare the migration executable.
$message = new MigrateMessage();
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = \Drupal::getContainer()->get('plugin.manager.migration')->createInstance($migration_id, $options['configuration'] ?? []);
unset($options['configuration']);
// Each batch run we need to reinitialize the counter for the migration.
if (!empty($options['limit']) && isset($context['results'][$migration->id()]['@numitems'])) {
$options['limit'] -= $context['results'][$migration->id()]['@numitems'];
}
$executable = new static($migration, $message, $options);
if (empty($context['sandbox']['total'])) {
$context['sandbox']['total'] = $executable->getSource()->count();
$context['sandbox']['batch_limit'] = $executable->calculateBatchLimit($context);
$context['results'][$migration->id()] = [
'@numitems' => 0,
'@created' => 0,
'@updated' => 0,
'@failures' => 0,
'@ignored' => 0,
'@name' => $migration->id(),
];
}
// Every iteration, we reset our batch counter.
$context['sandbox']['batch_counter'] = 0;
// Make sure we know our batch context.
$executable->setBatchContext($context);
// Do the import.
$result = $executable->import();
// Store the result; will need to combine the results of all our iterations.
$context['results'][$migration->id()] = [
'@numitems' => $context['results'][$migration->id()]['@numitems'] + $executable->getProcessedCount(),
'@created' => $context['results'][$migration->id()]['@created'] + $executable->getCreatedCount(),
'@updated' => $context['results'][$migration->id()]['@updated'] + $executable->getUpdatedCount(),
'@failures' => $context['results'][$migration->id()]['@failures'] + $executable->getFailedCount(),
'@ignored' => $context['results'][$migration->id()]['@ignored'] + $executable->getIgnoredCount(),
'@name' => $migration->id(),
];
// Do some housekeeping.
if ($result !== MigrationInterface::RESULT_INCOMPLETE) {
$context['finished'] = 1;
}
else {
$context['sandbox']['counter'] = $context['results'][$migration->id()]['@numitems'];
if ($context['sandbox']['counter'] <= $context['sandbox']['total']) {
$context['finished'] = ((float) $context['sandbox']['counter'] / (float) $context['sandbox']['total']);
$context['message'] = t('Importing %migration (@percent%).', [
'%migration' => $migration->label(),
'@percent' => (int) ($context['finished'] * 100),
]);
}
}
}
/**
* Finished callback for import batches.
*
* @param bool $success
* A boolean indicating whether the batch has completed successfully.
* @param array $results
* The value set in $context['results'] by callback_batch_operation().
* @param array $operations
* If $success is FALSE, contains the operations that remained unprocessed.
*/
public static function batchFinishedImport(bool $success, array $results, array $operations): void {
if ($success) {
foreach ($results as $migration_id => $result) {
$singular_message = "Processed 1 item (@created created, @updated updated, @failures failed, @ignored ignored) - done with '@name'";
$plural_message = "Processed @numitems items (@created created, @updated updated, @failures failed, @ignored ignored) - done with '@name'";
\Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($result['@numitems'],
$singular_message,
$plural_message,
$result));
}
}
}
/**
* {@inheritdoc}
*/
public function checkStatus(): int {
$status = parent::checkStatus();
if ($status === MigrationInterface::RESULT_COMPLETED) {
// Do some batch housekeeping.
$context = $this->getBatchContext();
if (!empty($context['sandbox']) && $context['sandbox']['operation'] === self::BATCH_IMPORT) {
$context['sandbox']['batch_counter']++;
if ($context['sandbox']['batch_counter'] >= $context['sandbox']['batch_limit']) {
$status = MigrationInterface::RESULT_INCOMPLETE;
}
}
}
return $status;
}
/**
* Calculates how much a single batch iteration will handle.
*
* @param array|\DrushBatchContext $context
* The sandbox context.
*
* @return float
* The batch limit.
*/
public function calculateBatchLimit($context): float {
// @todo Maybe we need some other more sophisticated logic here?
return ceil($context['sandbox']['total'] / 100);
}
/**
* Suppress progress messages since we are executing via batch UI.
*
* @param bool $done
* TRUE if this is the last items to process. Otherwise FALSE.
*/
protected function progressMessage($done = TRUE) {}
}
+450
View File
@@ -0,0 +1,450 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateImportEvent;
use Drupal\migrate\Event\MigrateMapDeleteEvent;
use Drupal\migrate\Event\MigrateMapSaveEvent;
use Drupal\migrate\Event\MigratePreRowSaveEvent;
use Drupal\migrate\Event\MigrateRollbackEvent;
use Drupal\migrate\Event\MigrateRowDeleteEvent;
use Drupal\migrate\MigrateExecutable as MigrateExecutableBase;
use Drupal\migrate\MigrateMessageInterface;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_plus\Event\MigrateEvents as MigratePlusEvents;
use Drupal\migrate_plus\Event\MigratePrepareRowEvent;
/**
* Defines a migrate executable class for drush.
*/
class MigrateExecutable extends MigrateExecutableBase {
/**
* Counters of map statuses.
*
* Set of counters, keyed by MigrateIdMapInterface::STATUS_* constant.
*/
protected array $saveCounters = [
MigrateIdMapInterface::STATUS_FAILED => 0,
MigrateIdMapInterface::STATUS_IGNORED => 0,
MigrateIdMapInterface::STATUS_IMPORTED => 0,
MigrateIdMapInterface::STATUS_NEEDS_UPDATE => 0,
];
/**
* Counter of map saves, used to detect the item limit threshold.
*
* @var int
*/
protected $itemLimitCounter = 0;
/**
* Counter of map deletions.
*/
protected int $deleteCounter = 0;
/**
* Maximum number of items to process in this migration.
*
* 0 indicates no limit is to be applied.
*
* @var int
*/
protected $itemLimit = 0;
/**
* Frequency (in items) at which progress messages should be emitted.
*
* @var int
*/
protected $feedback = 0;
/**
* List of specific source IDs to import.
*/
protected array $idlist = [];
/**
* Count of number of items processed so far in this migration.
*
* @var int
*/
protected $counter = 0;
/**
* Whether the destination item exists before saving.
*/
protected bool $preExistingItem = FALSE;
/**
* List of event listeners we have registered.
*/
protected $listeners = [];
/**
* {@inheritdoc}
*/
public function __construct(MigrationInterface $migration, MigrateMessageInterface $message = NULL, array $options = []) {
parent::__construct($migration, $message);
if (isset($options['limit'])) {
$this->itemLimit = $options['limit'];
}
if (isset($options['feedback'])) {
$this->feedback = $options['feedback'];
}
if (isset($options['sync'])) {
$this->migration->set('syncSource', $options['sync']);
}
$this->idlist = MigrateTools::buildIdList($options);
$this->listeners[MigrateEvents::MAP_SAVE] = [
$this,
'onMapSave',
];
$this->listeners[MigrateEvents::MAP_DELETE] = [
$this,
'onMapDelete',
];
$this->listeners[MigrateEvents::POST_IMPORT] = [
$this,
'onPostImport',
];
$this->listeners[MigrateEvents::POST_ROLLBACK] = [
$this,
'onPostRollback',
];
$this->listeners[MigrateEvents::PRE_ROW_SAVE] = [
$this,
'onPreRowSave',
];
$this->listeners[MigrateEvents::POST_ROW_DELETE] = [
$this,
'onPostRowDelete',
];
if (class_exists(MigratePlusEvents::class)) {
$this->listeners[MigratePlusEvents::PREPARE_ROW] = [
$this,
'onPrepareRow',
];
}
foreach ($this->listeners as $event => $listener) {
$this->resetListeners($event);
$this->getEventDispatcher()->addListener($event, $listener);
}
}
/**
* Count up any map save events.
*
* @param \Drupal\migrate\Event\MigrateMapSaveEvent $event
* The map event.
*/
public function onMapSave(MigrateMapSaveEvent $event) {
// Only count saves for this migration.
if ($event->getMap()->getQualifiedMapTableName() == $this->migration->getIdMap()->getQualifiedMapTableName()) {
$fields = $event->getFields();
$this->itemLimitCounter++;
// Distinguish between creation and update.
if ($fields['source_row_status'] == MigrateIdMapInterface::STATUS_IMPORTED &&
$this->preExistingItem
) {
$this->saveCounters[MigrateIdMapInterface::STATUS_NEEDS_UPDATE]++;
}
else {
$this->saveCounters[$fields['source_row_status']]++;
}
}
}
/**
* Count up any rollback events.
*
* @param \Drupal\migrate\Event\MigrateMapDeleteEvent $event
* The map event.
*/
public function onMapDelete(MigrateMapDeleteEvent $event) {
$this->deleteCounter++;
}
/**
* Return the number of items created.
*
* @return int
* The number of items created.
*/
public function getCreatedCount() {
return $this->saveCounters[MigrateIdMapInterface::STATUS_IMPORTED];
}
/**
* Return the number of items updated.
*
* @return int
* The updated count.
*/
public function getUpdatedCount() {
return $this->saveCounters[MigrateIdMapInterface::STATUS_NEEDS_UPDATE];
}
/**
* Return the number of items ignored.
*
* @return int
* The ignored count.
*/
public function getIgnoredCount() {
return $this->saveCounters[MigrateIdMapInterface::STATUS_IGNORED];
}
/**
* Return the number of items that failed.
*
* @return int
* The failed count.
*/
public function getFailedCount() {
return $this->saveCounters[MigrateIdMapInterface::STATUS_FAILED];
}
/**
* Return the total number of items processed.
*
* Note that STATUS_NEEDS_UPDATE is not counted, since this is typically set
* on stubs created as side effects, not on the primary item being imported.
*
* @return int
* The processed count.
*/
public function getProcessedCount() {
return $this->saveCounters[MigrateIdMapInterface::STATUS_IMPORTED] +
$this->saveCounters[MigrateIdMapInterface::STATUS_NEEDS_UPDATE] +
$this->saveCounters[MigrateIdMapInterface::STATUS_IGNORED] +
$this->saveCounters[MigrateIdMapInterface::STATUS_FAILED];
}
/**
* Return the number of items rolled back.
*
* @return int
* The rollback count.
*/
public function getRollbackCount() {
return $this->deleteCounter;
}
/**
* Reset all the per-status counters to 0.
*/
protected function resetCounters() {
foreach ($this->saveCounters as $status => $count) {
$this->saveCounters[$status] = 0;
}
$this->deleteCounter = 0;
}
/**
* React to migration completion.
*
* @param \Drupal\migrate\Event\MigrateImportEvent $event
* The map event.
*/
public function onPostImport(MigrateImportEvent $event) {
$migrate_last_imported_store = \Drupal::keyValue('migrate_last_imported');
$migrate_last_imported_store->set($event->getMigration()->id(), round(\Drupal::time()->getCurrentMicroTime() * 1000));
$this->progressMessage();
$this->removeListeners();
$unused_ids = $this->getSource()->getRemainingIdList();
if ($unused_ids) {
$this->message->display($this->t("The following specified IDs were not found in the source IDs: @idlist.", [
'@idlist' => implode(', ', array_map(static fn($ids): string => implode(':', $ids), $unused_ids)),
]));
}
}
/**
* Clean up all our event listeners.
*/
protected function removeListeners() {
foreach ($this->listeners as $event => $listener) {
// Don't remove the listener for the events that are currently being
// dispatched.
if ($event !== MigrateEvents::POST_IMPORT && $event !== MigrateEvents::POST_ROLLBACK) {
$this->getEventDispatcher()->removeListener($event, $listener);
}
}
}
/**
* Clean up the event listeners that cannot be removed by removeListeners().
*
* @param string $event_name
* The name of the event to remove.
*/
protected function resetListeners(string $event_name) {
if (in_array($event_name, [
MigrateEvents::POST_IMPORT,
MigrateEvents::POST_ROLLBACK,
], TRUE)) {
foreach ($this->getEventDispatcher()->getListeners($event_name) as $registered_listener) {
if ($registered_listener[0] instanceof self) {
$this->getEventDispatcher()->removeListener($event_name, $registered_listener);
}
}
}
}
/**
* Emit information on what we've done.
*
* Either since the last feedback or the beginning of this migration.
*
* @param bool $done
* TRUE if this is the last items to process. Otherwise FALSE.
*/
protected function progressMessage($done = TRUE) {
$processed = $this->getProcessedCount();
if ($done) {
$singular_message = "Processed 1 item (@created created, @updated updated, @failures failed, @ignored ignored) - done with '@name'";
$plural_message = "Processed @numitems items (@created created, @updated updated, @failures failed, @ignored ignored) - done with '@name'";
}
else {
$singular_message = "Processed 1 item (@created created, @updated updated, @failures failed, @ignored ignored) - continuing with '@name'";
$plural_message = "Processed @numitems items (@created created, @updated updated, @failures failed, @ignored ignored) - continuing with '@name'";
}
$this->message->display(\Drupal::translation()->formatPlural($processed,
$singular_message, $plural_message,
[
'@numitems' => $processed,
'@created' => $this->getCreatedCount(),
'@updated' => $this->getUpdatedCount(),
'@failures' => $this->getFailedCount(),
'@ignored' => $this->getIgnoredCount(),
'@name' => $this->migration->id(),
]
));
}
/**
* React to rollback completion.
*
* @param \Drupal\migrate\Event\MigrateRollbackEvent $event
* The map event.
*/
public function onPostRollback(MigrateRollbackEvent $event) {
$migrate_last_imported_store = \Drupal::keyValue('migrate_last_imported');
$migrate_last_imported_store->set($event->getMigration()->id(), FALSE);
$this->rollbackMessage();
// If this is a sync import, then don't remove listeners or post import will
// not be executed. Leave it to post import to remove listeners.
if (empty($event->getMigration()->syncSource)) {
$this->removeListeners();
}
}
/**
* Emit information on what we've done.
*
* Either since the last feedback or the beginning of this migration.
*
* @param bool $done
* TRUE if this is the last items to rollback. Otherwise FALSE.
*/
protected function rollbackMessage($done = TRUE) {
$translation = \Drupal::translation();
if (($rolled_back = $this->getRollbackCount()) === 0) {
$this->message->display($translation->translate(
"No item has been rolled back - done with '@name'",
['@name' => $this->migration->id()])
);
return;
}
if ($done) {
$singular_message = "Rolled back 1 item - done with '@name'";
$plural_message = "Rolled back @numitems items - done with '@name'";
}
else {
$singular_message = "Rolled back 1 item - continuing with '@name'";
$plural_message = "Rolled back @numitems items - continuing with '@name'";
}
$this->message->display($translation->formatPlural($rolled_back,
$singular_message, $plural_message,
[
'@numitems' => $rolled_back,
'@name' => $this->migration->id(),
]
));
}
/**
* React to an item about to be imported.
*
* @param \Drupal\migrate\Event\MigratePreRowSaveEvent $event
* The pre-save event.
*/
public function onPreRowSave(MigratePreRowSaveEvent $event) {
$id_map = $event->getRow()->getIdMap();
if (!empty($id_map['destid1'])) {
$this->preExistingItem = TRUE;
}
else {
$this->preExistingItem = FALSE;
}
}
/**
* React to item rollback.
*
* @param \Drupal\migrate\Event\MigrateRowDeleteEvent $event
* The post-save event.
*/
public function onPostRowDelete(MigrateRowDeleteEvent $event) {
if ($this->feedback && ($this->deleteCounter) && $this->deleteCounter % $this->feedback == 0) {
$this->rollbackMessage(FALSE);
$this->resetCounters();
}
}
/**
* React to a new row.
*
* @param \Drupal\migrate_plus\Event\MigratePrepareRowEvent $event
* The prepare-row event.
*
* @throws \Drupal\migrate\MigrateSkipRowException
*/
public function onPrepareRow(MigratePrepareRowEvent $event) {
if ($this->feedback && $this->counter && $this->counter % $this->feedback == 0) {
$this->progressMessage(FALSE);
$this->resetCounters();
}
$this->counter++;
if ($this->itemLimit && ($this->itemLimitCounter + 1) >= $this->itemLimit) {
$event->getMigration()->interruptMigration(MigrationInterface::RESULT_COMPLETED);
}
}
/**
* {@inheritdoc}
*/
protected function getSource() {
if (!isset($this->source)) {
// Re-set $this->source which the call to the parent will have set.
$this->source = new SourceFilter(parent::getSource(), $this->idlist);
}
return $this->source;
}
/**
* {@inheritdoc}
*/
protected function getIdMap(): IdMapFilter {
return new IdMapFilter(parent::getIdMap(), $this->idlist);
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Component\Utility\NestedArray;
/**
* Merged included shared migrate configuration.
*/
final class MigrateIncludeHandler {
private PluginManagerInterface $sharedConfiguration;
public function __construct(PluginManagerInterface $shared_config) {
$this->sharedConfiguration = $shared_config;
}
/**
* Include the shared configuration.
*/
public function include(array &$migration): void {
// Handle one or multiple includes.
$includes = (array) $migration['include'];
foreach ($includes as $include) {
$definition = $this->sharedConfiguration->getDefinition($include);
// Remove the shared configuration plugin metadata.
unset($definition['id'], $definition['class'], $definition['provider']);
$migration = NestedArray::mergeDeep($definition, $migration);
}
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\Core\Plugin\PluginBase;
/**
* Default class used for migrate_shared_configuration plugins.
*/
final class MigrateSharedConfigDefault extends PluginBase implements MigrateSharedConfigInterface {
/**
* {@inheritdoc}
*/
public function id(): string {
return $this->pluginDefinition['id'];
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
/**
* Interface for migrate_shared_configuration plugins.
*/
interface MigrateSharedConfigInterface {
/**
* Returns the ID.
*
* @return string
* The shared configuration ID.
*/
public function id(): string;
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Plugin\Discovery\YamlDiscovery;
use Drupal\Core\Plugin\Factory\ContainerFactory;
use Drupal\migrate_tools\Discovery\YamlDiscoveryDecorator;
/**
* Defines a plugin manager to deal with migrate_shared_configuration.
*
* Modules can define migrate_shared_configuration in a
* MODULE_NAME.migrate_shared_configuration.yml file contained in the module's
* base directory. The migrate_shared_configuration has the following structure:
*
* @code
* MACHINE_NAME:
* source:
* key: drupal7
* MACHINE_NAME_2:
* source:
* batch_size: 1000
* @endcode
*
* Where everything besides MACHINE_NAME is the shared configuration.
*
* @see \Drupal\migrate_tools\MigrateSharedConfigDefault
* @see \Drupal\migrate_tools\MigrateSharedConfigInterface
* @see plugin_api
*/
final class MigrateSharedConfigPluginManager extends DefaultPluginManager {
/**
* {@inheritdoc}
*/
protected $defaults = [
// The migrate_shared_configuration id. Set by the plugin system based on
// the top-level YAML key.
'id' => '',
// Default plugin class.
'class' => MigrateSharedConfigDefault::class,
];
public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache_backend) {
$this->factory = new ContainerFactory($this);
$this->moduleHandler = $module_handler;
$this->alterInfo('migrate_shared_configuration_info');
$this->setCacheBackend($cache_backend, 'migrate_shared_configuration_plugins');
}
/**
* {@inheritdoc}
*/
protected function getDiscovery(): DiscoveryInterface {
if (!isset($this->discovery)) {
// @todo Remove this in 7.0.0.
$old_discovery = new YamlDiscovery('migrate_shared_configuration', $this->moduleHandler->getModuleDirectories());
$directories = array_map(function ($directory) {
return [$directory . '/migrate_shared_configuration'];
}, $this->moduleHandler->getModuleDirectories());
$this->discovery = new YamlDiscoveryDecorator($old_discovery, $directories, 'migrate_shared_configuration');
}
return $this->discovery;
}
}
@@ -0,0 +1,223 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\Core\Database\Connection;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Plugin\MigrationInterface;
/**
* Utility functionality for use in migrate_tools.
*/
class MigrateTools {
/**
* Default ID list delimiter.
*/
public const DEFAULT_ID_LIST_DELIMITER = ':';
/**
* Maximum number of source IDs to keep in memory before flushing them
* to database.
*/
protected const MAX_BUFFERED_SYNC_SOURCE_IDS_ENTRIES = 1000;
/**
* Sync Ids buffered in RAM before flushing them to database.
*/
protected array $bufferedSyncIdsEntries = [];
/**
* Array keeping track of migrations being in the Syncing IDs phase.
* Structure: List of `string => bool` where the key is the migration ID and
* the value is a boolean indicating whether it is currently syncing.
*/
protected array $syncingMigrations = [];
/**
* Connection to the database.
*/
public Connection $connection;
/**
* MigrateTools constructor.
*
* @param Connection $connection
* Connection to the database.
*/
public function __construct(Connection $connection) {
$this->connection = $connection;
}
/**
* Build the list of specific source IDs to import.
*
* @param array $options
* The migration executable options.
*
* The ID list.
*/
public static function buildIdList(array $options): array {
$options += [
'idlist' => NULL,
'idlist-delimiter' => self::DEFAULT_ID_LIST_DELIMITER,
];
$id_list = [];
if (is_scalar($options['idlist'])) {
$id_list = explode(',', (string) $options['idlist']);
array_walk($id_list, function (&$value) use ($options): void {
$value = str_getcsv($value, $options['idlist-delimiter']);
});
}
return $id_list;
}
/**
* Clears all SyncSourceIds entries from the database, for given migration.
*
* @param string $migrationId
* Migration ID.
*/
public function clearSyncSourceIds(string $migrationId): void
{
$query = $this->connection->delete('migrate_tools_sync_source_ids')
->condition('migration_id', $migrationId);
$query->execute();
}
/**
* Adds a SyncSourceIds entry to the database, for given migration.
*
* @param string $migrationId
* Migration ID.
* @param array $sourceIds
* A set of SyncSourceIds. Gets serialized to retain its structure.
*
* @throws \Exception
*/
public function addToSyncSourceIds(string $migrationId, array $sourceIds): void
{
$this->bufferedSyncIdsEntries[] = [
'migration_id' => $migrationId,
// Serialize source IDs before saving them to retain their structure.
'source_ids' => serialize($sourceIds),
];
if (count($this->bufferedSyncIdsEntries) >= static::MAX_BUFFERED_SYNC_SOURCE_IDS_ENTRIES) {
$this->flushSyncSourceIdsToDatabase();
}
}
/**
* Flushes any pending SyncSourceIds to the database.
*
* @throws \Exception
*/
protected function flushSyncSourceIdsToDatabase(): void {
if (empty($this->bufferedSyncIdsEntries)) {
// Nothing to flush, do nothing.
return;
}
// Batch insert all buffered pending entries.
$query = $this->connection->insert('migrate_tools_sync_source_ids')
->fields(['migration_id', 'source_ids']);
foreach($this->bufferedSyncIdsEntries as $entry) {
$query->values($entry);
}
$query->execute();
// Clear buffered pending entries.
$this->bufferedSyncIdsEntries = [];
}
/**
* Returns all SyncSourceIds from the database, for given migration.
*
* @param string $migrationId
* Migration ID.
*
* @return array
* Ids, structured as they were inserted.
*
* @throws \Exception
*/
public function getSyncSourceIds(string $migrationId): array
{
// Ensure all data was flushed to database before retrieving all of them.
$this->flushSyncSourceIdsToDatabase();
// Retrieve all IDs.
$serializedSourceIds = $this->connection->query(
'SELECT source_ids FROM {migrate_tools_sync_source_ids} WHERE migration_id = :mid',
[':mid' => $migrationId],
)
->fetchCol();
// Unserialize source IDs to restore their structure.
array_walk($serializedSourceIds, static function(&$entry) {
$entry = unserialize($entry);
});
return $serializedSourceIds;
}
/**
* Sets the syncing state of a migration.
*
* @param string $migrationId
* Migration ID.
* @param bool $isSyncing
* State to set.
*/
public function setMigrationSyncingState(string $migrationId, bool $isSyncing): void
{
$this->syncingMigrations[$migrationId] = $isSyncing;
}
/**
* Returns the syncing state of a migration.
*
* @param string $migrationId
* Migration ID.
*
* @return bool
* Whether the migration is currently syncing its IDs or not.
*/
public function isMigrationSyncing(string $migrationId): bool
{
return $this->syncingMigrations[$migrationId] ?? FALSE;
}
/**
* Returns a mapping of log levels to a human-friendly label.
*
* @return array
* An array of log level labels.
*/
public static function getLogLevelLabelMapping() {
return [
MigrationInterface::MESSAGE_ERROR => t('Error'),
MigrationInterface::MESSAGE_WARNING => t('Warning'),
MigrationInterface::MESSAGE_NOTICE => t('Notice'),
MigrationInterface::MESSAGE_INFORMATIONAL => t('Informational'),
];
}
/**
* Returns a mapping of status levels to a human-friendly label.
*
* @return array
* An array of migration status labels.
*/
public static function getStatusLevelLabelMapping() {
return [
MigrateIdMapInterface::STATUS_IMPORTED => t('Imported'),
MigrateIdMapInterface::STATUS_NEEDS_UPDATE => t('Pending'),
MigrateIdMapInterface::STATUS_IGNORED => t('Ignored'),
MigrateIdMapInterface::STATUS_FAILED => t('Failed'),
];
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools\Routing;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface;
use Symfony\Component\Routing\Route;
/**
* Route processor to expand migrate_group.
*/
class RouteProcessor implements OutboundRouteProcessorInterface {
private EntityTypeManagerInterface $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL): void {
if ($route->hasDefault('_migrate_group')) {
$parameters['migration_group'] = 'default';
if ($this->entityTypeManager->hasHandler('migration', 'storage')) {
$migration = $this->entityTypeManager
->getStorage('migration')
->load($parameters['migration']);
if (($migration !== NULL) && $group = $migration->get('migration_group')) {
$parameters['migration_group'] = $group;
}
}
}
}
}
@@ -0,0 +1,133 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
use Drupal\migrate\Plugin\MigrateSourceInterface;
use Drupal\migrate\Row;
/**
* Class to filter source by an ID list.
*/
class SourceFilter extends \FilterIterator implements MigrateSourceInterface {
/**
* Whether to filter the source IDs.
*/
protected bool $filterSourceIds;
/**
* List of specific source IDs to import.
*
* The accept() method removes an item from this when it successfully filters
* a value.
*/
protected array $idList;
/**
* SourceFilter constructor.
*
* @param \Drupal\migrate\Plugin\MigrateSourceInterface $source
* The ID map.
* @param array $id_list
* The id list to use in the filter.
*/
public function __construct(MigrateSourceInterface $source, array $id_list) {
parent::__construct($source);
$this->idList = $id_list;
$this->filterSourceIds = !empty($this->idList);
}
/**
* {@inheritdoc}
*/
public function accept(): bool {
// No idlist filtering, don't filter.
if (!$this->filterSourceIds) {
return TRUE;
}
// Some source plugins do not extend SourcePluginBase. These cannot be
// filtered so warn and return all values.
if (!$this->getInnerIterator() instanceof SourcePluginBase) {
trigger_error(sprintf('The source plugin %s is not an instance of %s. Extend from %s to support idlist filtering.', $this->getInnerIterator()->getPluginId(), SourcePluginBase::class, SourcePluginBase::class));
return TRUE;
}
$id_list_key = \array_search(array_values($this->getInnerIterator()->getCurrentIds()), $this->idList);
if ($id_list_key !== FALSE) {
// Row is included.
unset($this->idList[$id_list_key]);
return TRUE;
}
return FALSE;
}
/**
* Gets the remaining ID list.
*
* An array of the IDs which were not used by the filter.
*/
public function getRemainingIdList(): array {
return $this->idList;
}
/**
* {@inheritdoc}
*/
public function fields() {
return $this->getInnerIterator()->fields();
}
/**
* {@inheritdoc}
*/
public function prepareRow(Row $row) {
return $this->getInnerIterator()->prepareRow($row);
}
/**
* {@inheritdoc}
*/
public function __toString(): string {
return $this->getInnerIterator()->__toString();
}
/**
* {@inheritdoc}
*/
public function getIds() {
return $this->getInnerIterator()->getIds();
}
/**
* {@inheritdoc}
*/
public function getSourceModule() {
return $this->getInnerIterator()->getSourceModule();
}
/**
* {@inheritdoc}
*/
public function count(): int {
return $this->getInnerIterator()->count();
}
/**
* {@inheritdoc}
*/
public function getPluginId() {
return $this->getInnerIterator()->getPluginId();
}
/**
* {@inheritdoc}
*/
public function getPluginDefinition() {
return $this->getInnerIterator()->getPluginDefinition();
}
}
@@ -0,0 +1,39 @@
langcode: en
status: true
id: csv_source_test
label: Test edit of column aliases for CSV source plugin
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: { }
migration_group: csv_test
source:
plugin: csv
path: 'public://test.csv'
header_offset: 0
enclosure: '"'
ids:
- vid
fields:
-
name: vid
label: Vocabulary Id
-
name: name
label: Name
-
name: description
label: Description
process:
vid: vid
name: name
description: description
destination:
plugin: entity:taxonomy_vocabulary
migration_dependencies:
required: { }
optional: { }
dependencies:
enforced:
module:
- csv_source_test
@@ -0,0 +1,8 @@
id: csv_test
label: CSV source plugin edit test
description: Test editing of source plugin via the UI
source_type: CSV
dependencies:
enforced:
module:
- csv_source_test
@@ -0,0 +1,13 @@
type: module
name: CSV Source edit test
description: 'Test editing of source plugin via the UI.'
package: Testing
dependencies:
- drupal:migrate
- migrate_plus:migrate_plus
- migrate_plus:migrate_source_csv
# Information added by Drupal.org packaging script on 2024-11-05
version: '6.0.5'
project: 'migrate_tools'
datestamp: 1730824459
@@ -0,0 +1,11 @@
name: Test module for migrate shared configuration
type: module
package: Testing
dependencies:
- drupal:migrate
- migrate_tools:migrate_tools
# Information added by Drupal.org packaging script on 2024-11-05
version: '6.0.5'
project: 'migrate_tools'
datestamp: 1730824459
@@ -0,0 +1,6 @@
my_default_configuration:
source:
batch_size: 2
one_off_configuration:
destination:
batch_size: 2
@@ -0,0 +1,3 @@
id: my_single_file_default_configuration
destination:
my_single_file_default_configuration: value
@@ -0,0 +1,16 @@
id: test_stub_conflicts_migration
label: Test stub conflicts migration
include: my_default_configuration
source:
plugin: embedded_data
batch_size: 1000
data_rows:
- label: foo
- label: bar
- label: baz
ids:
label:
type: string
process: { }
destination:
plugin: 'entity:entity_test'
@@ -0,0 +1,15 @@
id: test_stub_migration
label: Test stub migration
include: my_default_configuration
source:
plugin: embedded_data
data_rows:
- label: foo
- label: bar
- label: baz
ids:
label:
type: string
process: { }
destination:
plugin: 'entity:entity_test'
@@ -0,0 +1,18 @@
id: test_stub_multiple_includes_migration
label: Test stub multiple includes migration
include:
- my_default_configuration
- my_single_file_default_configuration
- one_off_configuration
source:
plugin: embedded_data
data_rows:
- label: foo
- label: bar
- label: baz
ids:
label:
type: string
process: { }
destination:
plugin: 'entity:entity_test'
@@ -0,0 +1,35 @@
langcode: en
status: true
id: fruit_terms
label: Fruit Terms
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: { }
migration_group: default
source:
plugin: embedded_data
data_rows:
-
name: Apple
-
name: Banana
-
name: Orange
ids:
name:
type: string
constants:
vocabulary: fruit
process:
name: name
vid: constants/vocabulary
destination:
plugin: entity:taxonomy_term
migration_dependencies:
required: { }
optional: { }
dependencies:
enforced:
module:
- migrate_tools_test
@@ -0,0 +1,35 @@
langcode: en
status: false
id: fruit_terms_disabled
label: Fruit Terms (Disabled)
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: { }
migration_group: disabled
source:
plugin: embedded_data
data_rows:
-
name: Apple
-
name: Banana
-
name: Orange
ids:
name:
type: string
constants:
vocabulary: fruit
process:
name: name
vid: constants/vocabulary
destination:
plugin: entity:taxonomy_term
migration_dependencies:
required: { }
optional: { }
dependencies:
enforced:
module:
- migrate_tools_test
@@ -0,0 +1,22 @@
langcode: en
status: true
id: invalid_plugin
label: Invalid Plugin
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: { }
migration_group: default
source:
plugin: does_not_exist
process:
name: name
destination:
plugin: entity:taxonomy_term
migration_dependencies:
required: { }
optional: { }
dependencies:
enforced:
module:
- migrate_tools_test
@@ -0,0 +1,22 @@
langcode: en
status: true
id: source_exception
label: Source Exception
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: { }
migration_group: default
source:
plugin: migrate_exception_source_test
process:
name: name
destination:
plugin: entity:taxonomy_term
migration_dependencies:
required: { }
optional: { }
dependencies:
enforced:
module:
- migrate_tools_test
@@ -0,0 +1,12 @@
langcode: en
status: true
id: default
label: Default
description: ''
source_type: ''
module: null
shared_configuration: null
dependencies:
enforced:
module:
- migrate_tools_test
@@ -0,0 +1,12 @@
langcode: en
status: true
id: disabled
label: Disabled
description: 'Contains disabled migrations for testing'
source_type: ''
module: null
shared_configuration: null
dependencies:
enforced:
module:
- migrate_tools_test
@@ -0,0 +1,6 @@
services:
migrate_tools_test.commands:
class: \Drupal\migrate_tools_test\Commands\MigrateToolsTestCommands
arguments: ['@plugin.manager.migration']
tags:
- { name: drush.command }
@@ -0,0 +1,12 @@
type: module
name: Migrate Tools Test
description: 'Test module to test Migrate Tools.'
package: Testing
dependencies:
- drupal:migrate
- migrate_plus:migrate_plus
# Information added by Drupal.org packaging script on 2024-11-05
version: '6.0.5'
project: 'migrate_tools'
datestamp: 1730824459
@@ -0,0 +1,42 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools_test\Commands;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\Plugin\MigrationPluginManager;
use Drupal\migrate_tools\MigrateBatchExecutable;
use Drush\Commands\DrushCommands;
/**
* Migrate Tools Test drush commands.
*/
final class MigrateToolsTestCommands extends DrushCommands {
protected MigrationPluginManager $migrationPluginManager;
/**
* MigrateToolsTestCommands constructor.
*
* @param \Drupal\migrate\Plugin\MigrationPluginManager $migrationPluginManager
* The Migration Plugin Manager.
*/
public function __construct(MigrationPluginManager $migrationPluginManager) {
parent::__construct();
$this->migrationPluginManager = $migrationPluginManager;
}
/**
* Run a batch import of fruit terms as a test.
*
* @command migrate:batch-import-fruit
*/
public function batchImportFruit(): void {
$fruit_migration = $this->migrationPluginManager->createInstance('fruit_terms');
$executable = new MigrateBatchExecutable($fruit_migration, new MigrateMessage());
$executable->batchImport();
drush_backend_batch_process();
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types = 1);
namespace Drupal\migrate_tools_test\Plugin\migrate\source;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
/**
* A simple migrate source for testing exception handling.
*
* @MigrateSource(
* id = "migrate_exception_source_test",
* source_module = "migrate_tools_test"
* )
*/
final class ExceptionThrowingTestSource extends SourcePluginBase {
/**
* {@inheritdoc}
*/
public function fields(): array {
return [];
}
/**
* {@inheritdoc}
*/
public function __toString(): string {
return '';
}
/**
* {@inheritdoc}
*/
public function getIds(): array {
return [];
}
/**
* {@inheritdoc}
*/
protected function initializeIterator(): \ArrayIterator {
return new \ArrayIterator();
}
/**
* {@inheritdoc}
*/
public function rewind(): void {
throw new \Exception('Rewind Failure');
}
}
@@ -0,0 +1,27 @@
langcode: en
status: true
id: url_404_source_test
label: Test 404 URLs in the UI
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: { }
migration_group: url_test
source:
plugin: url
data_fetcher_plugin: file
urls: 'http://localhost/does-not-exist.xml'
data_parser_plugin: simple_xml
item_selector: /rss/channel/item
fields: { }
ids: { }
process: { }
destination:
plugin: 'entity:node'
migration_dependencies:
required: { }
optional: { }
dependencies:
enforced:
module:
- url_source_test
@@ -0,0 +1,8 @@
id: url_test
label: URL source plugin edit test
description: Test editing of URL source plugin via the UI
source_type: URL
dependencies:
enforced:
module:
- url_source_test
@@ -0,0 +1,12 @@
type: module
name: URL Source edit test
description: 'Test editing of URL source plugin via the UI.'
package: Testing
dependencies:
- drupal:migrate
- migrate_plus:migrate_plus
# Information added by Drupal.org packaging script on 2024-11-05
version: '6.0.5'
project: 'migrate_tools'
datestamp: 1730824459
@@ -0,0 +1,46 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Functional;
use Drupal\Tests\BrowserTestBase;
use Drush\TestTraits\DrushTestTrait;
/**
* Test that batch import runs correctly in drush command.
*
* @group migrate_tools
*/
final class DrushBatchImportTest extends BrowserTestBase {
use DrushTestTrait;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $modules = [
'migrate_tools_test',
'migrate_tools',
'migrate_plus',
'taxonomy',
'text',
'system',
'user',
];
/**
* Tests that a batch import run from a custom drush command succeeds.
*/
public function testBatchImportInDrushComand(): void {
$this->drush('migrate:batch-import-fruit');
$migration = \Drupal::service('plugin.manager.migration')->createInstance('fruit_terms');
$id_map = $migration->getIdMap();
$this->assertSame(3, $id_map->importedCount());
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Functional;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Tests\BrowserTestBase;
use Drush\TestTraits\DrushTestTrait;
/**
* Execute drush on fully functional website using source generators.
*
* @group migrate_tools
*/
final class DrushCommandsGeneratorTest extends BrowserTestBase {
use DrushTestTrait;
/**
* The source CSV data.
*
* @var string
*/
private string $sourceData;
/**
* {@inheritdoc}
*/
protected static $modules = [
'csv_source_test',
'migrate',
'migrate_plus',
'migrate_source_csv',
'migrate_tools',
'taxonomy',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Setup the file system so we create the source CSV.
$this->container->get('stream_wrapper_manager')->registerWrapper('public', PublicStream::class, StreamWrapperInterface::NORMAL);
$fs = \Drupal::service('file_system');
$fs->mkdir('public://sites/default/files', NULL, TRUE);
// The source data for this test.
$this->sourceData = <<<'EOD'
vid,name,description,hierarchy,weight
tags,Tags,Use tags to group articles,0,0
forums,Sujet de discussion,Forum navigation vocabulary,1,0
test_vocabulary,Test Vocabulary,This is the vocabulary description,1,0
genre,Genre,Genre description,1,0
EOD;
// Write the data to the filepath given in the test migration.
file_put_contents('public://test.csv', $this->sourceData);
}
/**
* Tests synced import.
*/
public function testSyncImport(): void {
$this->drush('mim', ['csv_source_test']);
$this->assertStringContainsString('1/4', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/4\/4[^\n]+\[notice\][^\n]+Processed 4 items \(4 created, 0 updated, 0 failed, 0 ignored\) - done with \'csv_source_test\'/', $this->getErrorOutput());
$this->assertStringNotContainsString('5/5', $this->getErrorOutput());
$vocabulary = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->load('genre');
$this->assertEquals('Genre', $vocabulary->label());
$this->assertEquals(4, \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->getQuery()->accessCheck(TRUE)->count()->execute());
// Remove one vocab and replace with another.
$this->sourceData = str_replace('genre,Genre,Genre description,1,0', 'fruit,Fruit,Fruit description,1,0', $this->sourceData);
file_put_contents('public://test.csv', $this->sourceData);
// Execute sync migration.
$this->drush('mim', ['csv_source_test'], ['sync' => NULL, 'update' => NULL]);
$this->assertMatchesRegularExpression('/1\/4[^\n]+25%[^\n]+\[notice\][^\n]+Rolled back 1 item - done with \'csv_source_test\'/', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/4\/4[^\n]+100%/', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/5\/5[^\n]+100%[^\n]+\[notice\][^\n]+Processed 4 items \(1 created, 3 updated, 0 failed, 0 ignored\) - done with \'csv_source_test\'/', $this->getErrorOutput());
// Flush cache so recently deleted vocabulary actually goes away.
drupal_flush_all_caches();
$this->assertEquals(4, \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->getQuery()->accessCheck(TRUE)->count()->execute());
$this->assertEmpty(\Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->load('genre'));
// Remove one vocab and replace with another (reverse previous change).
$this->sourceData = str_replace('fruit,Fruit,Fruit description,1,0', 'genre,Genre,Genre description,1,0', $this->sourceData);
file_put_contents('public://test.csv', $this->sourceData);
// Execute sync migration without update enforced.
$this->drush('mim', ['csv_source_test'], ['sync' => NULL]);
$this->assertStringContainsString('1/4', $this->getErrorOutput());
$this->assertStringContainsString('25%', $this->getErrorOutput());
$this->assertStringContainsString('Rolled back 1 item - done with \'csv_source_test\'', $this->getErrorOutput());
$this->assertStringNotContainsString('3 updated', $this->getErrorOutput());
$this->assertStringContainsString('Processed 1 item (1 created, 0 updated, 0 failed, 0 ignored) - done with \'csv_source_test\'', $this->getErrorOutput());
// Flush cache so recently deleted vocabulary actually goes away.
drupal_flush_all_caches();
$this->assertEquals(4, \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->getQuery()->accessCheck()->count()->execute());
$this->assertEmpty(\Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->load('fruit'));
/** @var \Drupal\migrate\Plugin\MigrateIdMapInterface $id_map */
$id_map = $this->container->get('plugin.manager.migration')->createInstance('csv_source_test')->getIdMap();
$this->assertCount(4, $id_map);
}
}
@@ -0,0 +1,225 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Functional;
use Drupal\Tests\BrowserTestBase;
use Drush\TestTraits\DrushTestTrait;
/**
* Execute drush on fully functional website.
*
* @group migrate_tools
*/
final class DrushCommandsTest extends BrowserTestBase {
use DrushTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = [
'migrate_tools_test',
'migrate_tools',
'migrate_plus',
'taxonomy',
'text',
'system',
'user',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests migrate:import with feedback.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function testFeedback(): void {
$this->drush('mim', ['fruit_terms'], ['feedback' => 2]);
$this->assertMatchesRegularExpression('/1\/3[^\n]+\[notice\][^\n]+Processed 2 items \(2 created, 0 updated, 0 failed, 0 ignored\) - continuing with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/3\/3[^\n]+\[notice\][^\n]+Processed 1 item \(1 created, 0 updated, 0 failed, 0 ignored\) - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertStringNotContainsString('Processed 4 items', $this->getErrorOutput());
}
/**
* Tests migrate:import with limit.
*/
public function testLimit(): void {
$this->drush('mim', ['fruit_terms'], ['limit' => 2]);
$this->assertMatchesRegularExpression('/\[notice\][^\n]+Processed 2 items \(2 created, 0 updated, 0 failed, 0 ignored\)/', $this->getErrorOutput());
$this->assertStringContainsString('done with \'fruit_terms\'', $this->getErrorOutput());
$this->assertStringNotContainsString('Processed 3 items', $this->getErrorOutput());
}
/**
* Test that migrations continue after a failure if the option is set.
*/
public function testContinueOnFailure(): void {
// Option not set, fruit_terms should not run.
$this->drush('mim', ['invalid_plugin,fruit_terms'], [], NULL, NULL, 1);
$this->assertStringNotContainsString("done with 'fruit_terms'", $this->getErrorOutput());
// Option set, fruit_terms should run.
$this->drush('mim', ['invalid_plugin,fruit_terms'], ['continue-on-failure' => NULL]);
$this->assertStringContainsString("done with 'fruit_terms'", $this->getErrorOutput());
// Option not set, fruit_terms should not run.
$this->drush('mr', ['invalid_plugin,fruit_terms'], [], NULL, NULL, 1);
$this->assertStringNotContainsString("done with 'fruit_terms'", $this->getErrorOutput());
// Option set, fruit_terms should run.
$this->drush('mr', ['invalid_plugin,fruit_terms'], ['continue-on-failure' => NULL]);
$this->assertStringContainsString("done with 'fruit_terms'", $this->getErrorOutput());
// Option not set, fruit_terms should not display.
$this->drush('ms', ['invalid_plugin,fruit_terms'], ['format' => 'json'], NULL, NULL, 1);
// This demonstrates we surface the exception but not as an error.
$this->assertStringNotContainsString('[error] The "does_not_exist" plugin does not exist', $this->getErrorOutput());
$this->assertStringContainsString('The "does_not_exist" plugin does not exist', $this->getErrorOutput());
$this->assertStringNotContainsString('fruit_terms Idle 3', $this->getOutput());
// Option set, fruit_terms should display.
$this->drush('ms', ['invalid_plugin,fruit_terms'], ['continue-on-failure' => NULL]);
$this->assertMatchesRegularExpression('/\[error\][^\n]+The "does_not_exist" plugin does not exist/', $this->getErrorOutput());
$this->assertStringContainsString('fruit_terms Idle 3', $this->getOutput());
}
/**
* Tests many of the migrate drush commands.
*/
public function testDrush(): void {
$this->drush('ms', [], [], NULL, NULL, 1);
$this->assertStringContainsString('The "does_not_exist" plugin does not exist.', $this->getErrorOutput());
$this->container->get('config.factory')->getEditable('migrate_plus.migration.invalid_plugin')->delete();
// Flush cache so the recently removed invalid migration is cleared.
drupal_flush_all_caches();
$this->drush('ms', [], ['format' => 'json']);
$expected = [
[
'group' => 'Default (default)',
'id' => 'fruit_terms',
'imported' => 0,
'status' => 'Idle',
'total' => 3,
'unprocessed' => 3,
'message_count' => 0,
'last_imported' => '',
],
[
'group' => 'Default (default)',
'id' => 'source_exception',
'imported' => 0,
'status' => 'Idle',
'total' => 0,
'unprocessed' => 0,
'message_count' => 0,
'last_imported' => '',
],
];
$this->assertEquals($expected, $this->getOutputFromJSON());
$this->drush('mim', ['fruit_terms']);
$this->assertStringContainsString('1/3', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/3\/3[^\n]+\[notice\][^\n]+Processed 3 items \(3 created, 0 updated, 0 failed, 0 ignored\) - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertStringNotContainsString('Processed 4 items', $this->getErrorOutput());
$this->drush('mim', ['fruit_terms'], [
'update' => NULL,
'force' => NULL,
'execute-dependencies' => NULL,
]);
$this->assertStringContainsString('1/3', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/3\/3[^\n]+\[notice\][^\n]+Processed 3 items \(0 created, 3 updated, 0 failed, 0 ignored\) - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertStringNotContainsString('Processed 4 items', $this->getErrorOutput());
$this->drush('mrs', ['fruit_terms']);
$this->assertStringContainsString('Migration fruit_terms is already Idle', $this->getErrorOutput());
$this->drush('mfs', ['fruit_terms'], ['format' => 'json']);
$expected = [
[
'machine_name' => 'name',
'description' => 'name',
],
];
$this->assertEquals($expected, $this->getOutputFromJSON());
$this->drush('mr', ['fruit_terms']);
$this->assertStringContainsString('1/3', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/3\/3[^\n]+\[notice\][^\n]+Rolled back 3 items - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertStringNotContainsString('Processed 4 items', $this->getErrorOutput());
$this->drush('migrate:stop', ['fruit_terms']);
$this->assertMatchesRegularExpression('/warning\][^\n]+Migration fruit_terms is idle/', $this->getErrorOutput());
$this->drush('mim', ['fruit_terms'], ['skip-progress-bar' => NULL]);
$this->assertMatchesRegularExpression('/\[notice\][^\n]+Processed 3 items \(3 created, 0 updated, 0 failed, 0 ignored\) - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->drush('mr', ['fruit_terms'], ['skip-progress-bar' => NULL]);
$this->assertMatchesRegularExpression('/\[notice\][^\n]+Rolled back 3 items - done with \'fruit_terms\'/', $this->getErrorOutput());
}
/**
* Fully test migrate messages.
*/
public function testMessages(): void {
$this->drush('mim', ['fruit_terms']);
$this->drush('mmsg', ['fruit_terms']);
$this->assertMatchesRegularExpression('/\[notice\][^\n]+No messages for this migration/', $this->getErrorOutput());
/** @var \Drupal\migrate\Plugin\MigrateIdMapInterface $id_map */
$id_map = $this->container->get('plugin.manager.migration')->createInstance('fruit_terms')->getIdMap();
$id_map->saveMessage(['name' => 'Apple'], 'You picked a bad one.');
$this->drush('mmsg', ['fruit_terms'], ['format' => 'json']);
$expected = [
[
'level' => 'Error',
'message' => 'You picked a bad one.',
'source_ids' => 'Apple',
'destination_ids' => '1',
],
];
$this->assertEquals($expected, $this->getOutputFromJSON());
$this->drush('mmsg', ['fruit_terms'], ['format' => 'csv']);
$expected = <<<EOT
"Source ID(s)","Destination ID(s)",Level,Message
Apple,1,Error,"You picked a bad one."
EOT;
$this->assertEquals($expected, $this->getOutput());
}
/**
* Tests synced import with and without update enforced.
*/
public function testSyncImport(): void {
$this->drush('mim', ['fruit_terms']);
$this->assertStringContainsString('1/3', $this->getErrorOutput());
$this->assertStringContainsString('3/3', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/3\/3[^\n]+\[notice\][^\n]+Processed 3 items \(3 created, 0 updated, 0 failed, 0 ignored\) - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertStringNotContainsString('Processed 4 items', $this->getErrorOutput());
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(2);
$this->assertEquals('Banana', $term->label());
$this->assertEquals(3, \Drupal::entityTypeManager()->getStorage('taxonomy_term')->getQuery()->accessCheck(TRUE)->count()->execute());
$source = $this->container->get('config.factory')->getEditable('migrate_plus.migration.fruit_terms')->get('source');
unset($source['data_rows'][1]);
$source['data_rows'][] = ['name' => 'Grape'];
$this->container->get('config.factory')->getEditable('migrate_plus.migration.fruit_terms')->set('source', $source)->save();
// Flush cache so the recently changed migration can be refreshed.
drupal_flush_all_caches();
$this->drush('mim', ['fruit_terms'], ['sync' => NULL, 'update' => NULL]);
$this->assertStringContainsString('1/3', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/4\/4[^\n]+\[notice\][^\n]+Processed 3 items \(1 created, 2 updated, 0 failed, 0 ignored\) - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertStringNotContainsString('Processed 5 items', $this->getErrorOutput());
$this->assertEquals(3, \Drupal::entityTypeManager()->getStorage('taxonomy_term')->getQuery()->accessCheck(TRUE)->count()->execute());
$this->assertEmpty(\Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(2));
unset($source['data_rows'][2]);
$source['data_rows'][] = ['name' => 'Pear'];
$this->container->get('config.factory')->getEditable('migrate_plus.migration.fruit_terms')->set('source', $source)->save();
// Flush cache so the recently changed migration can be refreshed.
drupal_flush_all_caches();
$this->drush('mim', ['fruit_terms'], ['sync' => NULL]);
$this->assertMatchesRegularExpression('/1\/3[^\n]+\[notice\][^\n]+Rolled back 1 item - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertMatchesRegularExpression('/\[notice\][^\n]+Processed 1 item \(1 created, 0 updated, 0 failed, 0 ignored\) - done with \'fruit_terms\'/', $this->getErrorOutput());
$this->assertStringNotContainsString('2 updated', $this->getErrorOutput());
$this->assertStringNotContainsString('5', $this->getErrorOutput());
$this->assertEquals(3, \Drupal::entityTypeManager()->getStorage('taxonomy_term')->getQuery()->accessCheck(TRUE)->count()->execute());
$this->assertEmpty(\Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(3));
/** @var \Drupal\migrate\Plugin\MigrateIdMapInterface $id_map */
$id_map = $this->container->get('plugin.manager.migration')->createInstance('fruit_terms')->getIdMap();
$this->assertCount(3, $id_map);
}
}
@@ -0,0 +1,134 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Functional;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\VocabularyInterface;
use Drupal\Tests\BrowserTestBase;
/**
* Execution form test.
*
* @group migrate_tools
*/
final class MigrateExecutionFormTest extends BrowserTestBase {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
protected static $modules = [
'user',
'filter',
'field',
'node',
'text',
'taxonomy',
'migrate',
'migrate_plus',
'migrate_tools',
'migrate_tools_test',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
private VocabularyInterface $vocabulary;
private QueryInterface $vocabularyQuery;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->vocabulary = $this->createVocabulary([
'vid' => 'fruit',
'name' => 'Fruit',
]);
$this->vocabularyQuery = $this->container->get('entity_type.manager')
->getStorage('taxonomy_term')
->getQuery()
->accessCheck(TRUE);
// Log in as user 1. Migrations in the UI can only be performed as user 1.
$this->drupalLogin($this->rootUser);
}
/**
* Tests execution of import and rollback of a migration.
*
* @throws \Behat\Mink\Exception\ExpectationException
*/
public function testExecution(): void {
$group = 'default';
$migration = 'fruit_terms';
$urlPath = "/admin/structure/migrate/manage/{$group}/migrations/{$migration}/execute";
$real_count = $this->vocabularyQuery->count()->execute();
$expected_count = 0;
$this->assertEquals($expected_count, $real_count);
$this->drupalGet($urlPath);
$this->assertSession()->responseContains('Choose an operation to run');
$edit = [
'operation' => 'import',
];
$this->drupalGet($urlPath);
$this->submitForm($edit, 'Execute');
$real_count = $this->vocabularyQuery->count()->execute();
$expected_count = 3;
$this->assertEquals($expected_count, $real_count);
$edit = [
'operation' => 'rollback',
];
$this->drupalGet($urlPath);
$this->submitForm($edit, 'Execute');
$real_count = $this->vocabularyQuery->count()->execute();
$expected_count = 0;
$this->assertEquals($expected_count, $real_count);
$edit = [
'operation' => 'import',
];
$this->drupalGet($urlPath);
$this->submitForm($edit, 'Execute');
$real_count = $this->vocabularyQuery->count()->execute();
$expected_count = 3;
$this->assertEquals($expected_count, $real_count);
}
/**
* Creates a custom vocabulary based on default settings.
*
* @param array $values
* An array of settings to change from the defaults.
* Example: 'vid' => 'foo'.
*
* @return \Drupal\taxonomy\VocabularyInterface
* Created vocabulary.
*/
protected function createVocabulary(array $values = []): VocabularyInterface {
// Find a non-existent random vocabulary name.
if (!isset($values['vid'])) {
do {
$id = strtolower($this->randomMachineName(8));
} while (Vocabulary::load($id));
}
else {
$id = $values['vid'];
}
$values += [
'id' => $id,
'name' => $id,
];
$vocabulary = Vocabulary::create($values);
$status = $vocabulary->save();
$this->assertSame($status, SAVED_NEW);
return $vocabulary;
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Execution form test.
*
* @group migrate_tools
*/
final class MigrateListBuilderTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'user',
'migrate',
'migrate_plus',
'migrate_tools',
'migrate_tools_test',
];
/**
* {@inheritdoc}
*/
protected $profile = 'testing';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Log in as user 1. Migrations in the UI can only be performed as user 1.
$this->drupalLogin($this->rootUser);
}
/**
* Test migrate UI list page with default migrations.
*/
public function testMigrateListBuilderDefault(): void {
// List migrations from default group.
$this->drupalGet('/admin/structure/migrate/manage/default/migrations');
$this->assertSession()->statusCodeEquals(200);
}
/**
* Test migrate UI list page with disabled migrations.
*/
public function testMigrateListBuilderDisabled(): void {
// List migrations containing disabled migrations.
$this->drupalGet('/admin/structure/migrate/manage/disabled/migrations');
$this->assertSession()->statusCodeEquals(200);
}
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Functional;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Tests\BrowserTestBase;
/**
* Test the URL column alias edit form.
*
* @group migrate_tools
*/
final class SourceUrlFormTest extends BrowserTestBase {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
protected static $modules = [
'migrate',
'migrate_plus',
'migrate_tools',
'url_source_test',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The migration group for the test migration.
*
* @var string
*/
private string $group;
/**
* The test migration id.
*
* @var string
*/
private string $migration;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Log in as user 1. Migrations in the UI can only be performed as user 1.
$this->drupalLogin($this->rootUser);
// Select the group and migration to test.
$this->group = 'url_test';
$this->migration = 'url_404_source_test';
}
/**
* Tests the form ensure graceful 404 handling.
*
* @throws \Behat\Mink\Exception\ExpectationException
*/
public function testSourceUrl404Form(): void {
// Assert the test migration is listed.
$this->drupalGet("/admin/structure/migrate/manage/{$this->group}/migrations");
$session = $this->assertSession();
$session->responseContains('Test 404 URLs in the UI');
}
}
@@ -0,0 +1,319 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Kernel {
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Drupal\migrate_tools\Drush\Commands\MigrateToolsCommands;
use Drupal\migrate_tools\MigrateTools;
use Drupal\Tests\migrate\Kernel\MigrateTestBase;
use Drush\Log\DrushLoggerManager;
use Psr\Log\LoggerInterface;
/**
* Tests for the Drush 9 commands.
*
* @group migrate_tools
*/
final class DrushTest extends MigrateTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'migrate_tools_test',
'migrate_tools',
'migrate_plus',
'taxonomy',
'text',
'system',
'user',
];
/**
* Base options array for import.
*
* @var array
*/
private array $importBaseOptions = [
'all' => NULL,
'group' => NULL,
'tag' => NULL,
'limit' => NULL,
'feedback' => NULL,
'idlist' => NULL,
'idlist-delimiter' => MigrateTools::DEFAULT_ID_LIST_DELIMITER,
'update' => NULL,
'force' => NULL,
'execute-dependencies' => NULL,
'skip-progress-bar' => FALSE,
'continue-on-failure' => FALSE,
'sync' => FALSE,
];
private ?MigrateToolsCommands $commands = NULL;
private MigrationPluginManagerInterface $migrationPluginManager;
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
$this->installConfig('migrate_plus');
$this->installConfig('migrate_tools_test');
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('user');
$this->installSchema('user', ['users_data']);
$this->installSchema('migrate_tools', ['migrate_tools_sync_source_ids']);
$this->migrationPluginManager = $this->container->get('plugin.manager.migration');
// Handle Drush 10 vs Drush 11 differences.
$logger_class = class_exists(DrushLoggerManager::class) ? DrushLoggerManager::class : LoggerInterface::class;
$this->logger = $this->prophesize($logger_class)->reveal();
$this->commands = new MigrateToolsCommands(
$this->migrationPluginManager,
$this->container->get('date.formatter'),
$this->container->get('entity_type.manager'),
$this->container->get('keyvalue'));
$this->commands->setLogger($this->logger);
}
/**
* Tests drush ms.
*/
public function testStatus(): void {
$this->executeMigration('fruit_terms');
$result = $this->commands->status('fruit_terms', [
'group' => NULL,
'tag' => NULL,
'names-only' => FALSE,
]);
$rows = $result->getArrayCopy();
$this->assertCount(1, $rows);
$row = reset($rows);
$this->assertSame('fruit_terms', $row['id']);
$this->assertSame(3, $row['total']);
$this->assertSame(3, $row['imported']);
$this->assertSame('Idle', $row['status']);
// Migrate status should not display migrate_drupal migrations if no
// source database is defined.
\Drupal::service('module_installer')->uninstall([
'migrate_tools_test',
]);
$this->enableModules(['migrate_drupal']);
$this->migrationPluginManager->clearCachedDefinitions();
$rows = $this->commands->status();
$this->assertEmpty($rows);
}
/**
* Tests that a failing status throws an exception (i.e. exit code).
*/
public function testFailingStatusThrowsException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('The "does_not_exist" plugin does not exist.');
$this->commands->status('invalid_plugin');
}
/**
* Tests drush mim.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function testImport(): void {
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance('fruit_terms');
$id_map = $migration->getIdMap();
$this->commands->import('fruit_terms', array_merge($this->importBaseOptions, ['idlist' => 'Apple']));
$this->assertSame(1, $id_map->importedCount());
$this->commands->import('fruit_terms', $this->importBaseOptions);
$this->assertSame(3, $id_map->importedCount());
$this->commands->import('fruit_terms', array_merge($this->importBaseOptions, [
'idlist' => 'Apple',
'update' => TRUE,
]));
$this->assertCount(0, $id_map->getRowsNeedingUpdate(100));
}
/**
* Tests that a failing import throws an exception (i.e. exit code).
*/
public function testFailingImportThrowsException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('source_exception migration failed.');
$this->commands->import('source_exception', $this->importBaseOptions);
}
/**
* Tests drush mmsg.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function testMessages(): void {
$this->executeMigration('fruit_terms');
$message = $this->getRandomGenerator()->string(16);
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance('fruit_terms');
$id_map = $migration->getIdMap();
$id_map->saveMessage(['name' => 'Apple'], $message);
/** @var \Consolidation\OutputFormatters\StructuredData\RowsOfFields $result */
$result = $this->commands->messages('fruit_terms', [
'csv' => FALSE,
'idlist' => NULL,
'idlist-delimiter' => MigrateTools::DEFAULT_ID_LIST_DELIMITER,
]);
$rows = $result->getArrayCopy();
$this->assertSame($message, $rows[0]['message']);
}
/**
* Tests that a failing messages throws an exception (i.e. exit code).
*/
public function testFailingMessagesThrowsException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Migration does_not_exist does not exist');
$this->commands->messages('does_not_exist', [
'csv' => FALSE,
'idlist' => NULL,
'idlist-delimiter' => MigrateTools::DEFAULT_ID_LIST_DELIMITER,
]);
}
/**
* Tests drush mr.
*/
public function testRollback(): void {
$this->executeMigration('fruit_terms');
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance('fruit_terms');
$id_map = $migration->getIdMap();
$this->assertSame(3, $id_map->importedCount());
$this->commands->rollback('fruit_terms', $this->importBaseOptions);
$this->assertSame(0, $id_map->importedCount());
}
/**
* Tests that a failing rollback throws an exception (i.e. exit code).
*/
public function testFailingRollbackThrowsException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('source_exception migration failed');
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance('source_exception');
$migration->setStatus(MigrationInterface::STATUS_IMPORTING);
$this->commands->rollback('source_exception', $this->importBaseOptions);
}
/**
* Tests drush mrs.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function testReset(): void {
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance('fruit_terms');
$migration->setStatus(MigrationInterface::STATUS_IMPORTING);
$status = $this->commands->status('fruit_terms', [
'group' => NULL,
'tag' => NULL,
'names-only' => FALSE,
])->getArrayCopy()[0]['status'];
$this->assertSame('Importing', $status);
$this->commands->resetStatus('fruit_terms');
$this->assertSame(MigrationInterface::STATUS_IDLE, $migration->getStatus());
}
/**
* Tests that a failing reset status throws an exception (i.e. exit code).
*/
public function testFailingResetStatusThrowsException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Migration does_not_exist does not exist');
$this->commands->resetStatus('does_not_exist');
}
/**
* Tests drush mst.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function testStop(): void {
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->migrationPluginManager->createInstance('fruit_terms');
$migration->setStatus(MigrationInterface::STATUS_IMPORTING);
$this->commands->stop('fruit_terms');
$this->assertSame(MigrationInterface::STATUS_STOPPING, $migration->getStatus());
}
/**
* Tests that a failing stop throws an exception (i.e. exit code).
*/
public function testFailingStopThrowsException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Migration does_not_exist does not exist');
$this->commands->stop('does_not_exist');
}
/**
* Tests drush mfs.
*/
public function testFieldsSource(): void {
/** @var \Consolidation\OutputFormatters\StructuredData\RowsOfFields $result */
$result = $this->commands->fieldsSource('fruit_terms');
$rows = $result->getArrayCopy();
$this->assertCount(1, $rows);
$this->assertSame('name', $rows[0]['machine_name']);
$this->assertSame('name', $rows[0]['description']);
}
/**
* Tests that a failing fields source throws an exception (i.e. exit code).
*/
public function testFailingFieldsSourceThrowsException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Migration does_not_exist does not exist');
$this->commands->fieldsSource('does_not_exist');
}
}
}
namespace {
if (!function_exists('dt')) {
/**
* Stub for dt().
*
* @param string $message
* The text.
* @param array $replace
* The replacement values.
*
* The text.
*/
function dt($message, array $replace = []): string {
return strtr($message, $replace);
}
}
if (!function_exists('drush_op')) {
/**
* Stub for drush_op.
*
* @param callable $callable
* The function to call.
*/
function drush_op(callable $callable) {
$args = func_get_args();
array_shift($args);
return call_user_func_array($callable, $args);
}
}
}
@@ -0,0 +1,93 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Kernel;
use Drupal\migrate_tools\MigrateExecutable;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\VocabularyInterface;
use Drupal\Tests\migrate\Kernel\MigrateTestBase;
/**
* Tests imports.
*
* @group migrate_tools
*/
final class MigrateImportTest extends MigrateTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'field',
'system',
'taxonomy',
'text',
'user',
'system',
];
protected $collectMessages = TRUE;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('user');
$this->installEntitySchema('taxonomy_vocabulary');
$this->installEntitySchema('taxonomy_term');
$this->installConfig(['taxonomy']);
}
/**
* Tests rolling back configuration and content entities.
*/
public function testImport(): void {
// We use vocabularies to demonstrate importing and rolling back
// configuration entities.
$vocabulary_data_rows = [
['id' => '1', 'name' => 'categories', 'weight' => '2'],
['id' => '2', 'name' => 'tags', 'weight' => '1'],
];
$ids = ['id' => ['type' => 'integer']];
$definition = [
'id' => 'vocabularies',
'migration_tags' => ['Import and rollback test'],
'source' => [
'plugin' => 'embedded_data',
'data_rows' => $vocabulary_data_rows,
'ids' => $ids,
],
'process' => [
'vid' => 'id',
'name' => 'name',
'weight' => 'weight',
],
'destination' => ['plugin' => 'entity:taxonomy_vocabulary'],
];
/** @var \Drupal\migrate\Plugin\MigrationInterface $vocabulary_migration */
$vocabulary_migration = \Drupal::service('plugin.manager.migration')->createStubMigration($definition);
$vocabulary_id_map = $vocabulary_migration->getIdMap();
// Test id list import.
$executable = new MigrateExecutable($vocabulary_migration, $this, ['idlist' => 2]);
$executable->import();
/** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
$vocabulary = Vocabulary::load(1);
$this->assertEmpty($vocabulary);
$map_row = $vocabulary_id_map->getRowBySource(['id' => 1]);
$this->assertEmpty($map_row);
/** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
$vocabulary = Vocabulary::load(2);
$this->assertInstanceOf(VocabularyInterface::class, $vocabulary);
$map_row = $vocabulary_id_map->getRowBySource(['id' => 2]);
$this->assertEquals($map_row['destid1'], $vocabulary->id());
}
}
@@ -0,0 +1,103 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Kernel;
use Drupal\migrate_tools\MigrateExecutable;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\VocabularyInterface;
use Drupal\Tests\migrate\Kernel\MigrateTestBase;
/**
* Tests rolling back of imports.
*
* @group migrate_tools
*/
final class MigrateRollbackTest extends MigrateTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'field',
'system',
'taxonomy',
'text',
'user',
];
protected $collectMessages = TRUE;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('user');
$this->installEntitySchema('taxonomy_vocabulary');
$this->installEntitySchema('taxonomy_term');
$this->installConfig(['taxonomy']);
}
/**
* Tests rolling back configuration and content entities.
*/
public function testRollback(): void {
// We use vocabularies to demonstrate importing and rolling back
// configuration entities.
$vocabulary_data_rows = [
['id' => '1', 'name' => 'categories', 'weight' => '2'],
['id' => '2', 'name' => 'tags', 'weight' => '1'],
];
$ids = ['id' => ['type' => 'integer']];
$definition = [
'id' => 'vocabularies',
'migration_tags' => ['Import and rollback test'],
'source' => [
'plugin' => 'embedded_data',
'data_rows' => $vocabulary_data_rows,
'ids' => $ids,
],
'process' => [
'vid' => 'id',
'name' => 'name',
'weight' => 'weight',
],
'destination' => ['plugin' => 'entity:taxonomy_vocabulary'],
];
/** @var \Drupal\migrate\Plugin\MigrationInterface $vocabulary_migration */
$vocabulary_migration = \Drupal::service('plugin.manager.migration')->createStubMigration($definition);
$vocabulary_id_map = $vocabulary_migration->getIdMap();
// Import and validate vocabulary config entities were created.
$executable = new MigrateExecutable($vocabulary_migration, $this, []);
$executable->import();
foreach ($vocabulary_data_rows as $row) {
/** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
$vocabulary = Vocabulary::load($row['id']);
$this->assertInstanceOf(VocabularyInterface::class, $vocabulary);
$map_row = $vocabulary_id_map->getRowBySource(['id' => $row['id']]);
$this->assertEquals($map_row['destid1'], $vocabulary->id());
}
// Test id list rollback.
$rollback_executable = new MigrateExecutable($vocabulary_migration, $this, ['idlist' => 1]);
$rollback_executable->rollback();
/** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
$vocabulary = Vocabulary::load(1);
$this->assertEmpty($vocabulary);
$map_row = $vocabulary_id_map->getRowBySource(['id' => 1]);
$this->assertEmpty($map_row);
/** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
$vocabulary = Vocabulary::load(2);
$this->assertInstanceOf(VocabularyInterface::class, $vocabulary);
$map_row = $vocabulary_id_map->getRowBySource(['id' => 2]);
$this->assertEquals($map_row['destid1'], $vocabulary->id());
}
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\migrate\Plugin\MigrationInterface;
/**
* Tests merging shared configuration.
*
* @group migrate_tools
*/
final class MigrateSharedConfigTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'migrate_tools',
'migrate_shared_config_test',
'migrate',
];
/**
* Tests including shared configuration.
*/
public function testInclude(): void {
$plugin_manager = $this->container->get('plugin.manager.migration');
// Validate a single include with not conflicts.
$migration = $plugin_manager->createInstance('test_stub_migration');
$this->assertInstanceOf(MigrationInterface::class, $migration);
$expected_source_configuration = [
'batch_size' => 2,
'plugin' => 'embedded_data',
'data_rows' => [
['label' => 'foo'],
['label' => 'bar'],
['label' => 'baz'],
],
'ids' => ['label' => ['type' => 'string']],
];
$this->assertEquals($expected_source_configuration, $migration->getSourceConfiguration());
// Validate multiple includes.
$migration = $plugin_manager->createInstance('test_stub_multiple_includes_migration');
$this->assertInstanceOf(MigrationInterface::class, $migration);
$expected_destination_configuration = [
'batch_size' => 2,
'plugin' => 'entity:entity_test',
'my_single_file_default_configuration' => 'value',
];
$this->assertEquals($expected_source_configuration, $migration->getSourceConfiguration());
$this->assertEquals($expected_destination_configuration, $migration->getDestinationConfiguration());
// Validate with conflicts.
$migration = $plugin_manager->createInstance('test_stub_conflicts_migration');
$this->assertInstanceOf(MigrationInterface::class, $migration);
$expected_source_configuration['batch_size'] = 1000;
$this->assertEquals($expected_source_configuration, $migration->getSourceConfiguration());
}
}
@@ -0,0 +1,87 @@
<?php
declare(strict_types = 1);
namespace Drupal\Tests\migrate_tools\Unit;
use Drupal\migrate_tools\MigrateTools;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\migrate_tools\MigrateTools
* @group migrate_tools
*/
final class MigrateToolsTest extends UnitTestCase {
/**
* @covers ::buildIdList
*
* @dataProvider dataProviderIdList
*/
public function testBuildIdList(array $options, array $expected): void {
$results = MigrateTools::buildIdList($options);
$this->assertEquals($results, $expected);
}
/**
* Data provider for testBuildIdList.
*/
public static function dataProviderIdList(): array {
$cases = [];
$cases[] = [
'options' => [],
'expected' => [],
];
$cases['single id'] = [
'options' => [
'idlist' => 123,
],
'expected' => [[123]],
];
$cases['multiple ids'] = [
'options' => [
'idlist' => '123, 456',
],
'expected' => [
[123], [456],
],
];
$cases['default delimiter, composite key'] = [
'options' => [
'idlist' => '123:456',
],
'expected' => [
[123, 456],
],
];
$cases['special delimiter, single'] = [
'options' => [
'idlist' => '123:456',
'idlist-delimiter' => '~',
],
'expected' => [
['123:456'],
],
];
$cases['special delimiter, multiple'] = [
'options' => [
'idlist' => '123:456~987:654',
'idlist-delimiter' => '~',
],
'expected' => [
['123:456', '987:654'],
],
];
$cases['space delimiter, multiple'] = [
'options' => [
'idlist' => '123:456 987:654',
'idlist-delimiter' => ' ',
],
'expected' => [
['123:456', '987:654'],
],
];
return $cases;
}
}