clean install

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

View File

@@ -0,0 +1,15 @@
/vendor/
/web/
/node_modules/
.env
composer.lock
yarn.lock
/.editorconfig
/.gitattributes
/composer.spoons.json
/composer.spoons.lock
#PHPUnit output
junit.xml
.phpunit.result.cache

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,20 @@
Migrate Source CSV is the contrib functionality for migrating CSV files.
Example
=======
The migrate_source_csv_test module in the tests/modules folder provides a
fully functional and runnable example migration scenario demonstrating the
basic concepts and most common techniques for CSV-based migrations.
To enable test modules, add $settings['extension_discovery_scan_tests'] = TRUE;
to your settings.php, or enable the default local.settings.php file that comes
with Drupal 8.
See https://cgit.drupalcode.org/drupal/tree/sites/example.settings.local.php
Installing the demo/test module
-------------------------------
Enable the module, check status and run a migration:
drush en migrate_source_csv_test -y
drush migrate-status
drush migrate-import migrate_csv_test

View File

@@ -0,0 +1,31 @@
{
"name": "drupal/migrate_source_csv",
"description": "CSV source migration.",
"type": "drupal-module",
"license": "GPL-2.0-or-later",
"homepage": "https://www.drupal.org/project/migrate_source_csv",
"authors": [
{
"name": "Lucas Hedding",
"homepage":"https://www.drupal.org/u/heddn",
"role": "Maintainer"
}
],
"support": {
"issues": "https://www.drupal.org/project/issues/migrate_source_csv",
"source": "https://cgit.drupalcode.org/migrate_source_csv"
},
"minimum-stability": "stable",
"prefer-stable": true,
"config": {
"preferred-install": "dist"
},
"require": {
"php": ">=7.1",
"drupal/core": ">=9.1",
"league/csv": "^9.1"
},
"require-dev": {
"drupal/migrate_plus": ">=5.0"
}
}

View File

@@ -0,0 +1,40 @@
migrate_plus.source.csv:
type: migrate_source
label: 'CSV'
mapping:
path:
type: string
label: 'Path to the source CSV file'
header_row_count:
type: integer
label: 'Signifies the number of rows of data in a file until the header row'
keys:
type: sequence
label: 'Column name(s) which represent the key uniquely identifying each record'
sequence:
type: string
label: 'Key field'
column_names:
type: ignore
label: 'Numeric key 0-based index of the columns in source CSV file'
file_class:
type: string
label: 'Full class name that includes namespace for an alternative CSV reader'
delimiter:
type: string
label: 'The field delimiter (one character only)'
enclosure:
type: string
label: 'The field enclosure character (one character only)'
escape:
type: string
label: 'The field escape character (one character only)'
file_flags:
type: integer
label: 'Bitmask flags for the SplFileObject'
create_record_num:
type: boolean
label: 'Specifies whether to create an incremented value for each record in the file'
record_num_field:
type: string
label: 'Field name for record number field'

View File

@@ -0,0 +1,14 @@
type: module
name: Migrate Source CSV
description: 'CSV source migration.'
package: Migration
core_version_requirement: '>=9.1'
dependencies:
- drupal:migrate
test_dependencies:
- migrate_plus:migrate_plus
# Information added by Drupal.org packaging script on 2023-12-19
version: '8.x-3.6'
project: 'migrate_source_csv'
datestamp: 1702995932

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="Module">
<file>.</file>
<arg name="extensions" value="php,module,inc,install,test,profile,theme,css,info,txt,md,yml"/>
<!-- Initially include all Drupal and DrupalPractice sniffs. -->
<rule ref="vendor/drupal/coder/coder_sniffer/Drupal"/>
<rule ref="vendor/drupal/coder/coder_sniffer/DrupalPractice"/>
<!-- Use 's' to print the full sniff name in the report. -->
<!-- A '-' is prefixed to each of these, so s becomes -s, etc. -->
<arg value="s"/>
<arg value="-colors"/>
<arg name='report-width' value='120'/>
<!-- Ignore all files that match these patterns. They are matched against -->
<!-- the full file path and there is an implied wildcard at each end. -->
<!-- Periods must be escaped using \. -->
<!-- The first two are key to isolating just this project's files. -->
<exclude-pattern>web/</exclude-pattern>
<exclude-pattern>vendor/</exclude-pattern>
<exclude-pattern>\.patch</exclude-pattern>
<exclude-pattern>interdiff</exclude-pattern>
</ruleset>

View File

@@ -0,0 +1,297 @@
<?php
namespace Drupal\migrate_source_csv\Plugin\migrate\source;
use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Component\Utility\NestedArray;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
use League\Csv\Reader;
/**
* Source for CSV files.
*
* Available configuration options:
* - path: Path to the CSV file. File streams are supported.
* - ids: Array of column names that uniquely identify each record. Column
* names used as IDs can only contain letters (uppercase and lowercase),
* numbers (0-9), and underscores. No spaces or other special characters
* are allowed.
* - header_offset: (optional) The record to be used as the CSV header and the
* thereby each record's field name. Defaults to 0 and because records are
* zero indexed. Can be set to null to indicate no header record.
* - fields: (optional) nested array of names and labels to use instead of a
* header record. Will overwrite values provided by header record. If used,
* name is required. If no label is provided, name is used instead for the
* field description.
* - delimiter: (optional) The field delimiter (one character only). Defaults to
* a comma (,).
* - enclosure: (optional) The field enclosure character (one character only).
* Defaults to double quote marks.
* - escape: (optional) The field escape character (one character only).
* Defaults to a backslash (\).
* - create_record_number: (optional) Boolean value specifying whether to create
* an incremented value for each record in the file. Defaults to FALSE.
* - record_number_field: (optional) The name of a field that holds an
* incremented value for each record in the file. Defaults to record_number.
*
* @codingStandardsIgnoreStart
*
* Example with minimal options:
* @code
* source:
* plugin: csv
* path: /tmp/countries.csv
* ids: [id]
*
* # countries.csv
* id,country
* 1,Nicaragua
* 2,Spain
* 3,United States
* @endcode
*
* In this example above, the migration source will use a single-column id using the
* value from the 'id' column of the CSV file.
*
* Example with most options configured:
* @code
* source:
* plugin: csv
* path: /tmp/countries.csv
* ids: [id]
* delimiter: '|'
* enclosure: "'"
* escape: '`'
* header_offset: null
* fields:
* -
* name: id
* label: ID
* -
* name: country
* label: Country
*
* # countries.csv
* 'really long string that makes this unique'|'United States'
* 'even longer really long string that makes this unique'|'Nicaragua'
* 'even more longer really long string that makes this unique'|'Spain'
* 'escaped data'|'one`'s country'
* @endcode
*
* In this example above, we override the default character controls for delimiter,
* enclosure and escape. We also set a null header offset to indicate no header.
*
* @codingStandardsIgnoreEnd
*
* @see http://php.net/manual/en/splfileobject.setcsvcontrol.php
*
* @MigrateSource(
* id = "csv",
* source_module = "migrate_source_csv"
* )
*/
class CSV extends SourcePluginBase implements ConfigurableInterface {
/**
* {@inheritdoc}
*
* @throws \InvalidArgumentException
* @throws \Drupal\migrate\MigrateException
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
$this->setConfiguration($configuration);
// Path is required.
if (empty($this->configuration['path'])) {
throw new \InvalidArgumentException('You must declare the "path" to the source CSV file in your source settings.');
}
// IDs are required.
if (empty($this->configuration['ids']) || !is_array($this->configuration['ids'])) {
throw new \InvalidArgumentException('You must declare "ids" as a unique array of fields in your source settings.');
}
// IDs must be an array of strings.
if ($this->configuration['ids'] !== array_unique(array_filter($this->configuration['ids'], 'is_string'))) {
throw new \InvalidArgumentException('The ids must a flat array with unique string values.');
}
foreach ($this->configuration['ids'] as $id) {
if (!preg_match('/^\w+$/', $id)) {
throw new \InvalidArgumentException(sprintf('The id (%s) must only include word characters a-z, A-Z, 0-9, including _ (underscore).', $id));
}
}
// CSV character control characters must be exactly 1 character.
foreach (['delimiter', 'enclosure', 'escape'] as $character) {
if (1 !== strlen($this->configuration[$character])) {
throw new \InvalidArgumentException(sprintf('%s must be a single character; %s given', $character, $this->configuration[$character]));
}
}
// The configuration "header_offset" must be null or an integer.
if (!(NULL === $this->configuration['header_offset'] || is_int($this->configuration['header_offset']))) {
throw new \InvalidArgumentException('The configuration "header_offset" must be null or an integer.');
}
// The configuration "header_offset" must be greater or equal to 0.
if (NULL !== $this->configuration['header_offset'] && 0 > $this->configuration['header_offset']) {
throw new \InvalidArgumentException('The configuration "header_offset" must be greater or equal to 0.');
}
// If set, all fields must have a least a defined "name" property.
if ($this->configuration['fields']) {
foreach ($this->configuration['fields'] as $delta => $field) {
if (!isset($field['name'])) {
throw new \InvalidArgumentException(sprintf('The "name" configuration for "fields" in index position %s is not defined.', $delta));
}
}
}
// If "create_record_number" is specified, "record_number_field" must be a
// non-empty string.
if ($this->configuration['create_record_number'] && (!is_scalar($this->configuration['record_number_field']) || (empty($this->configuration['record_number_field'])))) {
throw new \InvalidArgumentException('The configuration "record_number_field" must be a non-empty string.');
}
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'path' => '',
'ids' => [],
'header_offset' => 0,
'fields' => [],
'delimiter' => ",",
'enclosure' => "\"",
'escape' => "\\",
'create_record_number' => FALSE,
'record_number_field' => 'record_number',
];
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return $this->configuration;
}
/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration) {
// We must preserve integer keys for column_name mapping.
$this->configuration = NestedArray::mergeDeepArray([$this->defaultConfiguration(), $configuration], TRUE);
}
/**
* Return a string representing the source file path.
*
* @return string
* The file path.
*/
public function __toString() {
return $this->configuration['path'];
}
/**
* {@inheritdoc}
*
* @throws \Drupal\migrate\MigrateException
* @throws \League\Csv\Exception
*/
public function initializeIterator() {
$header = $this->getReader()->getHeader();
if ($this->configuration['fields']) {
// If there is no header record, we need to flip description and name so
// the name becomes the header record. League/csv requires the header keys
// to be integers >= 0.
$header = array_keys($this->fields());
}
return $this->getGenerator($this->getReader()->getRecords($header));
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids = [];
foreach ($this->configuration['ids'] as $value) {
$ids[$value]['type'] = 'string';
}
return $ids;
}
/**
* {@inheritdoc}
*/
public function fields() {
// If fields are not defined, use the header record.
if (empty($this->configuration['fields'])) {
$header = $this->getReader()->getHeader();
return array_combine($header, $header);
}
$fields = [];
foreach ($this->configuration['fields'] as $field) {
$fields[$field['name']] = isset($field['label']) ? $field['label'] : $field['name'];
}
return $fields;
}
/**
* Get the generator.
*
* @param \Iterator $records
* The CSV records.
*
* @codingStandardsIgnoreStart
*
* @return \Generator
* The records generator.
*
* @codingStandardsIgnoreEnd
*/
protected function getGenerator(\Iterator $records) {
$record_num = $this->configuration['header_offset'] ?? 0;
foreach ($records as $record) {
if ($this->configuration['create_record_number']) {
$record[$this->configuration['record_number_field']] = ++$record_num;
}
yield $record;
}
}
/**
* Get the CSV reader.
*
* @return \League\Csv\Reader
* The reader.
*
* @throws \Drupal\migrate\MigrateException
* @throws \League\Csv\Exception
*/
protected function getReader() {
$reader = $this->createReader();
$reader->setDelimiter($this->configuration['delimiter']);
$reader->setEnclosure($this->configuration['enclosure']);
$reader->setEscape($this->configuration['escape']);
$reader->setHeaderOffset($this->configuration['header_offset']);
return $reader;
}
/**
* Construct a new CSV reader.
*
* @return \League\Csv\Reader
* The reader.
*/
protected function createReader() {
if (!file_exists($this->configuration['path'])) {
throw new \RuntimeException(sprintf('File "%s" was not found.', $this->configuration['path']));
}
$csv = fopen($this->configuration['path'], 'r');
if (!$csv) {
throw new \RuntimeException(sprintf('File "%s" could not be opened.', $this->configuration['path']));
}
return Reader::createFromStream($csv);
}
}

View File

@@ -0,0 +1,10 @@
name: Source plugin using yield
type: module
package: Testing
dependencies:
- drupal:migrate
# Information added by Drupal.org packaging script on 2023-12-19
version: '8.x-3.6'
project: 'migrate_source_csv'
datestamp: 1702995932

View File

@@ -0,0 +1,45 @@
<?php
namespace Drupal\csv_source_yield_test\Plugin\migrate\source;
use Drupal\migrate_source_csv\Plugin\migrate\source\CSV;
use League\Csv\Reader;
/**
* Yields each image and sku.
*
* @MigrateSource(
* id = "yield_rows"
* )
*/
class YieldRows extends CSV {
/**
* {@inheritdoc}
*/
public function initializeIterator() {
return $this->getYield(parent::initializeIterator());
}
/**
* Prepare a test row using yield.
*
* @param \League\Csv\Reader $reader
* The CSV reader.
*
* @codingStandardsIgnoreStart
*
* @return \Generator
* A generator with only the id value.
*
* @codingStandardsIgnoreEnd
*/
public function getYield(Reader $reader) {
foreach ($reader as $row) {
$new_row = [];
$new_row['id'] = $row['id'];
yield($new_row);
}
}
}

View File

@@ -0,0 +1,16 @@
id,first_name,last_name,email,ip_address,date_of_birth
1,Justin,Dean,jdean0@example.com,60.242.130.40,01/05/1955
2,Joan,Jordan,jjordan1@example.com,137.230.209.171,10/14/1958
3,William,Ray,wray2@example.com,4.75.251.71,08/13/1962
4,Jack,Collins,jcollins3@example.com,118.241.243.64,08/16/1977
5,Jean,Moreno,jmoreno4@example.com,12.24.215.20,10/18/1940
6,Dennis,Mitchell,dmitchell5@example.com,185.24.131.116,08/21/1999
7,Harry,West,hwest6@example.com,101.74.110.171,10/05/1987
8,Rebecca,Hunt,rhunt7@example.com,253.107.6.23,04/21/1922
9,Rose,Rogers,rrogers8@example.com,21.2.126.228,08/14/2005
10,Juan,Walker,jwalker9@example.com,192.118.77.225,03/09/1958
11,Lois,Price,lpricea@example.com,231.185.100.19,04/08/1944
12,Patricia,Bell,pbellb@example.com,226.2.254.94,02/26/1950
13,Gerald,Kelly,gkellyc@example.com,31.204.2.163,09/25/1948
14,Kimberly,Jackson,kjacksond@example.com,19.187.65.116,06/21/1926
15,Jason,Mason,jmasone@example.com,225.129.68.203,10/01/1950
1 id first_name last_name email ip_address date_of_birth
2 1 Justin Dean jdean0@example.com 60.242.130.40 01/05/1955
3 2 Joan Jordan jjordan1@example.com 137.230.209.171 10/14/1958
4 3 William Ray wray2@example.com 4.75.251.71 08/13/1962
5 4 Jack Collins jcollins3@example.com 118.241.243.64 08/16/1977
6 5 Jean Moreno jmoreno4@example.com 12.24.215.20 10/18/1940
7 6 Dennis Mitchell dmitchell5@example.com 185.24.131.116 08/21/1999
8 7 Harry West hwest6@example.com 101.74.110.171 10/05/1987
9 8 Rebecca Hunt rhunt7@example.com 253.107.6.23 04/21/1922
10 9 Rose Rogers rrogers8@example.com 21.2.126.228 08/14/2005
11 10 Juan Walker jwalker9@example.com 192.118.77.225 03/09/1958
12 11 Lois Price lpricea@example.com 231.185.100.19 04/08/1944
13 12 Patricia Bell pbellb@example.com 226.2.254.94 02/26/1950
14 13 Gerald Kelly gkellyc@example.com 31.204.2.163 09/25/1948
15 14 Kimberly Jackson kjacksond@example.com 19.187.65.116 06/21/1926
16 15 Jason Mason jmasone@example.com 225.129.68.203 10/01/1950

View File

@@ -0,0 +1,18 @@
dependencies:
config:
- field.storage.node.field_dob
- node.type.people
module:
- datetime
id: node.people.field_dob
field_name: field_dob
entity_type: node
bundle: people
label: 'Date of Birth'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: datetime

View File

@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_email
- node.type.people
id: node.people.field_email
field_name: field_email
entity_type: node
bundle: people
label: Email
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: email

View File

@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_first_name
- node.type.people
id: node.people.field_first_name
field_name: field_first_name
entity_type: node
bundle: people
label: 'First Name'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string

View File

@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_ip_address
- node.type.people
id: node.people.field_ip_address
field_name: field_ip_address
entity_type: node
bundle: people
label: 'IP Address'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string

View File

@@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_last_name
- node.type.people
id: node.people.field_last_name
field_name: field_last_name
entity_type: node
bundle: people
label: 'Last Name'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string

View File

@@ -0,0 +1,19 @@
langcode: en
status: true
dependencies:
module:
- datetime
- node
id: node.field_dob
field_name: field_dob
entity_type: node
type: datetime
settings:
datetime_type: date
module: datetime
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@@ -0,0 +1,17 @@
langcode: en
status: true
dependencies:
module:
- node
id: node.field_email
field_name: field_email
entity_type: node
type: email
settings: { }
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
module:
- node
id: node.field_first_name
field_name: field_first_name
entity_type: node
type: string
settings:
max_length: 255
is_ascii: false
case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
module:
- node
id: node.field_ip_address
field_name: field_ip_address
entity_type: node
type: string
settings:
max_length: 255
is_ascii: false
case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
module:
- node
id: node.field_last_name
field_name: field_last_name
entity_type: node
type: string
settings:
max_length: 255
is_ascii: false
case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@@ -0,0 +1,11 @@
langcode: en
status: true
dependencies: {}
third_party_settings: {}
name: People
type: people
description: ''
help: ''
new_revision: true
preview_mode: 1
display_submitted: true

View File

@@ -0,0 +1,13 @@
name: Migrate Source CSV Test
type: module
package: Testing
dependencies:
- drupal:migrate
- migrate_source_csv:migrate_source_csv
- drupal:node
- drupal:datetime
# Information added by Drupal.org packaging script on 2023-12-19
version: '8.x-3.6'
project: 'migrate_source_csv'
datestamp: 1702995932

View File

@@ -0,0 +1,14 @@
<?php
/**
* @file
* Contains migrate_source_csv_test.module.
*/
/**
* Implements hook_migration_plugins_alter().
*/
function migrate_source_csv_test_migration_plugins_alter(&$definitions) {
$path = \Drupal::service('extension.list.module')->getPath('migrate_source_csv_test');
$definitions['migrate_csv_test']['source']['path'] = $path . $definitions['migrate_csv_test']['source']['path'];
}

View File

@@ -0,0 +1,32 @@
id: migrate_csv_test
migration_tags:
- CSV
label: 'CSV file migration'
source:
plugin: csv
path: /artifacts/people.csv
ids: [id]
process:
type:
plugin: default_value
default_value: people
title:
plugin: concat
source:
- first_name
- last_name
delimiter: ' '
field_first_name: first_name
field_last_name: last_name
field_email: email
field_ip_address: ip_address
field_dob:
plugin: format_date
from_format: m/d/Y
to_format: Y-m-d
source: date_of_birth
destination:
plugin: 'entity:node'
migration_dependencies:
required: { }
optional: { }

View File

@@ -0,0 +1,50 @@
<?php
namespace Drupal\Tests\migrate_source_csv\Kernel\Plugin\migrate\source;
use Drupal\node\Entity\Node;
use Drupal\Tests\migrate\Kernel\MigrateTestBase;
/**
* @coversDefaultClass \Drupal\migrate_source_csv\Plugin\migrate\source\CSV
*
* @group migrate_source_csv
*/
class CSVTest extends MigrateTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'system',
'field',
'user',
'node',
'datetime',
'migrate',
'migrate_source_csv',
'migrate_source_csv_test',
];
/**
* Tests execution of a migration sourced from CSV.
*/
public function testMigrate(): void {
$this->installEntitySchema('user');
$this->installEntitySchema('node');
$this->installConfig(['migrate_source_csv_test']);
/** @var \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migrationManager */
$migrationManager = $this->container->get('plugin.manager.migration');
$migration = $migrationManager->createInstance('migrate_csv_test');
$this->executeMigration($migration);
$node = Node::load(1);
$this->assertEquals($node->label(), 'Justin Dean');
$this->assertEquals($node->get('field_first_name')->value, 'Justin');
$this->assertEquals($node->get('field_last_name')->value, 'Dean');
$this->assertEquals($node->get('field_email')->value, 'jdean0@example.com');
$this->assertEquals($node->get('field_ip_address')->value, '60.242.130.40');
$this->assertEquals($node->get('field_dob')->value, '1955-01-05');
}
}

View File

@@ -0,0 +1,449 @@
<?php
namespace Drupal\Tests\migrate_source_csv\Unit\Plugin\migrate\source;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_source_csv\Plugin\migrate\source\CSV;
use Drupal\Tests\UnitTestCase;
use org\bovigo\vfs\vfsStream;
/**
* @coversDefaultClass \Drupal\migrate_source_csv\Plugin\migrate\source\CSV
*
* @group migrate_source_csv
*/
class CSVUnitTest extends UnitTestCase {
/**
* The plugin id.
*
* @var string
*/
protected $pluginId;
/**
* The plugin definition.
*
* @var array
*/
protected $pluginDefinition;
/**
* The migration plugin.
*
* @var \Drupal\migrate\Plugin\MigrationInterface
*/
protected $migration;
/**
* A file path with standard character controls.
*
* @var string
*/
protected $standardCharsPath;
/**
* A file path with non-standard character controls.
*
* @var string
*/
protected $nonStandardCharsPath;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->pluginId = 'test csv migration';
$this->pluginDefinition = [];
$migration = $this->prophesize(MigrationInterface::class);
$migration->getIdMap()
->willReturn(NULL);
$this->migration = $migration->reveal();
$standard_chars = <<<'EOD'
id,first_name,last_name,email,country,ip_address
1,Justin,Dean,jdean0@example.com,Indonesia,60.242.130.40
2,Joan,Jordan,jjordan1@example.com,Thailand,137.230.209.171
EOD;
$non_standard_chars = <<<'EOD'
1|%Justin%|Dean|jdean0@example.com|Indonesia|60.242.130.40
2|Joan|Jordan|jjordan1@example.com|Thailand|137.230.209.171
EOD;
$root_dir = vfsStream::setup('root');
$this->standardCharsPath = vfsStream::newFile('data.csv')
->at($root_dir)
->withContent($standard_chars)
->url();
$this->nonStandardCharsPath = vfsStream::newFile('data_edge_case.csv')
->at($root_dir)
->withContent($non_standard_chars)
->url();
}
/**
* Tests the construction of CSV.
*
* @covers ::__construct
*/
public function testCreate(): void {
$configuration = [
'path' => $this->standardCharsPath,
'ids' => ['id'],
];
$csv = new CSV($configuration, $this->pluginId, $this->pluginDefinition, $this->migration);
$this->assertInstanceOf(CSV::class, $csv);
}
/**
* Tests that a missing path will throw an exception.
*/
public function testMigrateExceptionPathMissing(): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('You must declare the "path" to the source CSV file in your source settings.');
new CSV([], $this->pluginId, $this->pluginDefinition, $this->migration);
}
/**
* Tests that missing ids will throw an exception.
*/
public function testMigrateExceptionKeysMissing(): void {
$configuration = [
'path' => $this->standardCharsPath,
];
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('You must declare "ids" as a unique array of fields in your source settings.');
new CSV($configuration, $this->pluginId, $this->pluginDefinition, $this->migration);
}
/**
* Tests that valid IDs are validated.
*/
public function testValidIds(): void {
$configuration = [
'path' => $this->standardCharsPath,
'ids' => [
'asdfASDF_',
],
];
$csv = new CSV($configuration, $this->pluginId, $this->pluginDefinition, $this->migration);
$this->assertInstanceOf(CSV::class, $csv);
}
/**
* Tests invalid IDs are validated.
*/
public function testInvalidIds(): void {
$configuration = [
'path' => $this->standardCharsPath,
'ids' => [
'asdfASDF_-',
],
];
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The id (asdfASDF_-) must only include word characters a-z, A-Z, 0-9, including _ (underscore).');
new CSV($configuration, $this->pluginId, $this->pluginDefinition, $this->migration);
}
/**
* Tests that toString functions as expected.
*
* @covers ::__toString
*/
public function testToString(): void {
$configuration = [
'path' => $this->standardCharsPath,
'ids' => ['id'],
];
$csv = new CSV($configuration, $this->pluginId, $this->pluginDefinition, $this->migration);
$this->assertEquals($configuration['path'], (string) $csv);
}
/**
* Tests initialization of the iterator.
*
* @param array $configuration
* The plugin configuration.
* @param array $expected
* The expected results.
*
* @covers ::initializeIterator
* @dataProvider iteratorDataProvider
*/
public function testInitializeIterator(array $configuration, array $expected): void {
$file_path = $this->standardCharsPath;
if (isset($configuration['path']) && $configuration['path'] === 'non standard') {
$file_path = $this->nonStandardCharsPath;
}
// Set the file path here so the virtual stream can be created in setUp.
$configuration['path'] = $file_path;
$csv = new CSV($configuration, $this->pluginId, $this->pluginDefinition, $this->migration);
$iterator = $csv->initializeIterator();
$this->assertEquals(count($expected), iterator_count($iterator));
$iterator = $csv->initializeIterator();
foreach ($expected as $record) {
$this->assertSame($record, $iterator->current());
$iterator->next();
}
}
/**
* Data provider for iterator testing.
*
* @return array
* The test case.
*/
public function iteratorDataProvider(): array {
$data['non standard'] = [
'configuration' => [
'ids' => ['ids'],
'path' => 'non standard',
'header_offset' => NULL,
'delimiter' => '|',
'enclosure' => '%',
'escape' => '`',
],
'expected rows' => [
[
'1',
'Justin',
'Dean',
'jdean0@example.com',
'Indonesia',
'60.242.130.40',
],
[
'2',
'Joan',
'Jordan',
'jjordan1@example.com',
'Thailand',
'137.230.209.171',
],
],
];
$data['standard'] = [
'configuration' => [
'ids' => ['ids'],
],
'expected rows' => [
[
'id' => '1',
'first_name' => 'Justin',
'last_name' => 'Dean',
'email' => 'jdean0@example.com',
'country' => 'Indonesia',
'ip_address' => '60.242.130.40',
],
[
'id' => '2',
'first_name' => 'Joan',
'last_name' => 'Jordan',
'email' => 'jjordan1@example.com',
'country' => 'Thailand',
'ip_address' => '137.230.209.171',
],
],
];
$data['with defined fields'] = [
'configuration' => [
'ids' => ['ids'],
'fields' => [
[
'name' => 'id',
],
[
'name' => 'first_name',
'label' => 'First Name',
],
],
],
'expected rows' => [
[
'id' => '1',
'first_name' => 'Justin',
],
[
'id' => '2',
'first_name' => 'Joan',
],
],
];
$data['default record number field name'] = [
'configuration' => [
'ids' => ['id'],
'create_record_number' => TRUE,
],
'expected rows' => [
[
'id' => '1',
'first_name' => 'Justin',
'last_name' => 'Dean',
'email' => 'jdean0@example.com',
'country' => 'Indonesia',
'ip_address' => '60.242.130.40',
'record_number' => 1,
],
[
'id' => '2',
'first_name' => 'Joan',
'last_name' => 'Jordan',
'email' => 'jjordan1@example.com',
'country' => 'Thailand',
'ip_address' => '137.230.209.171',
'record_number' => 2,
],
],
];
$data['custom record number field name'] = [
'configuration' => [
'ids' => ['MyRowNumber'],
'create_record_number' => TRUE,
'record_number_field' => 'MyRowNumber',
'header_offset' => 1,
],
'expected rows' => [
[
'1' => 'id',
'Justin' => 'first_name',
'Dean' => 'last_name',
'jdean0@example.com' => 'email',
'Indonesia' => 'country',
'60.242.130.40' => 'ip_address',
'MyRowNumber' => 2,
],
[
'1' => '2',
'Justin' => 'Joan',
'Dean' => 'Jordan',
'jdean0@example.com' => 'jjordan1@example.com',
'Indonesia' => 'Thailand',
'60.242.130.40' => '137.230.209.171',
'MyRowNumber' => 3,
],
],
];
return $data;
}
/**
* Tests that ids are properly identified.
*
* @param array $configuration
* The plugin configuration.
* @param array $expected
* The expected results.
*
* @covers ::getIds
* @dataProvider idsDataProvider
*/
public function testGetIds(array $configuration, array $expected): void {
$csv = new CSV($configuration + ['path' => $this->standardCharsPath], $this->pluginId, $this->pluginDefinition, $this->migration);
$this->assertSame($expected, $csv->getIds());
}
/**
* Data provider for IDs testing.
*
* @return array
* The test case.
*/
public function idsDataProvider(): array {
$data['ids'] = [
'configuration' => [
'ids' => [
'id',
'paragraph',
],
],
'expected' => [
'id' => [
'type' => 'string',
],
'paragraph' => [
'type' => 'string',
],
],
];
return $data;
}
/**
* Tests that fields have a machine name and description.
*
* @param array $configuration
* The plugin configuration.
* @param array $expected
* The expected results.
*
* @covers ::fields
* @dataProvider fieldsDataProvider
*/
public function testFields(array $configuration, array $expected): void {
$csv = new CSV($configuration + ['path' => $this->standardCharsPath], $this->pluginId, $this->pluginDefinition, $this->migration);
$this->assertSame($expected, $csv->fields());
}
/**
* Data provider for fields testing.
*
* @return array
* The test case.
*/
public function fieldsDataProvider(): array {
$data['no fields'] = [
'configuration' => [
'ids' => ['id'],
],
'expected' => [
'id' => 'id',
'first_name' => 'first_name',
'last_name' => 'last_name',
'email' => 'email',
'country' => 'country',
'ip_address' => 'ip_address',
],
];
$data['with fields override'] = [
'configuration' => [
'ids' => ['id'],
'fields' => [
[
'name' => 'id',
],
[
'name' => 'first_name',
'label' => 'First Name',
],
],
],
'expected' => [
'id' => 'id',
'first_name' => 'First Name',
],
];
return $data;
}
/**
* Tests malformed CSV file path.
*
* @covers ::initializeIterator
*/
public function testMalformedFilePath(): void {
$configuration = [
'path' => 'non-existent-path',
'ids' => ['id'],
];
$csv = new CSV($configuration, $this->pluginId, $this->pluginDefinition, $this->migration);
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('File "non-existent-path" was not found.');
$csv->initializeIterator();
}
}