ReinstallSourceBase.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <?php
  2. namespace Drupal\reinstall\Plugin\migrate\source;
  3. use Drupal\Component\Plugin\ConfigurablePluginInterface;
  4. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  5. use Drupal\migrate\MigrateException;
  6. use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
  7. use Drupal\migrate\Plugin\MigrationInterface;
  8. use Drupal\migrate\Row;
  9. use Drupal\reinstall\ReinstallEvents;
  10. use Drupal\reinstall\SourceEvent;
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. use Symfony\Component\Yaml\Exception\ParseException;
  15. use Symfony\Component\Yaml\Yaml;
  16. /**
  17. * Class SimpleSource provides the basic mechanisms to load a YML entity dump.
  18. *
  19. * @MigrateSource(
  20. * id = "reinstall_base"
  21. * )
  22. */
  23. class ReinstallSourceBase extends SourcePluginBase implements ContainerFactoryPluginInterface, ConfigurablePluginInterface {
  24. use SimpleSourceTrait;
  25. /**
  26. * The event_dispatcher service.
  27. *
  28. * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
  29. */
  30. protected $eventDispatcher;
  31. /**
  32. * The source records.
  33. *
  34. * MAY be altered by subscribing to MigrateEvents::PRE_IMPORT.
  35. *
  36. * @var array
  37. */
  38. public $records;
  39. public function __construct(
  40. array $configuration,
  41. $plugin_id,
  42. $plugin_definition,
  43. \Drupal\migrate\Plugin\MigrationInterface $migration,
  44. EventDispatcherInterface $eventDispatcher
  45. ) {
  46. parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
  47. $this->eventDispatcher = $eventDispatcher;
  48. $this->records = array_map([$this, 'flattenRecord'], $this->initialParse($configuration));
  49. $eventDispatcher->dispatch(ReinstallEvents::POST_SOURCE_PARSE, new SourceEvent($this));
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public static function create(
  55. ContainerInterface $container,
  56. array $configuration,
  57. $pluginId,
  58. $pluginDefinition,
  59. MigrationInterface $migration = NULL
  60. ) {
  61. $importPath = $container->getParameter('reinstall.path');
  62. $configuration['importPath'] = $importPath;
  63. $dispatcher = $container->get('event_dispatcher');
  64. return new static($configuration, $pluginId, $pluginDefinition, $migration, $dispatcher);
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function doCount() {
  70. return count($this->records);
  71. }
  72. /**
  73. * Flatten the field hierarchy. Not correct for all cases.
  74. *
  75. * @param array $record
  76. * The raw source values.
  77. *
  78. * @return array
  79. * The flattened values.
  80. *
  81. * @see \Drupal\reinstall\Plugin\migrate\process\TermParent
  82. */
  83. protected function flattenRecord(array $record) {
  84. $row = new Row($record);
  85. $this->flattenRow($row);
  86. return $row->getSource();
  87. }
  88. /**
  89. * Flatten a typical Drupal 8 field array to a 1-level array.
  90. */
  91. protected function flattenRow(Row $row) {
  92. $source = $row->getSource();
  93. foreach ($source as $key => &$item_list) {
  94. if (is_scalar($item_list)) {
  95. continue;
  96. }
  97. if (count($item_list) > 1) {
  98. $item = $item_list;
  99. }
  100. else {
  101. $item = reset($item_list);
  102. }
  103. if (isset($item['target_id'])) {
  104. $value = $item['target_id'];
  105. }
  106. elseif (is_scalar($item) || (count($item) != 1 && !isset($item['width']) && !isset($item['pid']))) {
  107. $value = $item;
  108. }
  109. elseif (isset($item['value'])) {
  110. $value = $item['value'];
  111. }
  112. // Handle bundle['target_id']
  113. // Exclude image field to keep metadata (alt / title)
  114. elseif (isset($item['target_id']) && !isset($item['alt']) && !isset($item['title'])) {
  115. $value = $item['target_id'];
  116. }
  117. elseif (isset($item['pid'])) {
  118. $value = $item['alias'];
  119. }
  120. else {
  121. $value = $item;
  122. }
  123. if (empty($item)) {
  124. $value = NULL;
  125. }
  126. $row->setSourceProperty($key, $value);
  127. }
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. protected function initializeIterator() {
  133. if (!isset($this->iterator)) {
  134. $this->iterator = new \ArrayIterator($this->records);
  135. }
  136. return $this->iterator;
  137. }
  138. /**
  139. * Load then parse the file requested in configuration and return its records.
  140. *
  141. * @param array $configuration
  142. * The source configuration from the migration source section.
  143. * @param string $key
  144. * Optional. A top-level key for the source document. If empty, items will
  145. * be parsed from the root of the source document.
  146. *
  147. * @return array
  148. * An array of entity descriptions.
  149. *
  150. * @throws \Drupal\migrate\MigrateException
  151. */
  152. protected function initialParse(array $configuration, string $key = NULL) {
  153. $this->sstEntityType = $type = $configuration['type'];
  154. $bundle = $configuration['bundle'];
  155. $baseFilePath = "${type}/${bundle}.yml";
  156. $importPath = $configuration['importPath'] ?? NULL;
  157. $filePath = realpath("$importPath/$baseFilePath");
  158. if (!is_file($filePath) || !is_readable($filePath)) {
  159. throw new MigrateException("${filePath} is not a readable file.");
  160. }
  161. try {
  162. $raw = file_get_contents($filePath);
  163. $data = Yaml::parse($raw);
  164. }
  165. catch (ParseException $e) {
  166. throw new MigrateException("Cannot parse the contents of ${filePath}.");
  167. }
  168. if ($key) {
  169. return $data[$key] ?? [];
  170. }
  171. return $data ?? [];
  172. }
  173. /**
  174. * {@inheritdoc}
  175. */
  176. public function __toString() {
  177. $current = $this->getIterator()->current();
  178. $ret = json_encode($current, JSON_PRETTY_PRINT);
  179. return $ret;
  180. }
  181. /**
  182. * Gets this plugin's configuration.
  183. *
  184. * @return array
  185. * An array of this plugin's configuration.
  186. */
  187. public function getConfiguration() {
  188. return $this->configuration;
  189. }
  190. /**
  191. * Sets the configuration for this plugin instance.
  192. *
  193. * @param array $configuration
  194. * An associative array containing the plugin's configuration.
  195. */
  196. public function setConfiguration(array $configuration) {
  197. $this->configuration = $configuration;
  198. }
  199. /**
  200. * Gets default configuration for this plugin.
  201. *
  202. * @return array
  203. * An associative array with the default configuration.
  204. */
  205. public function defaultConfiguration() {
  206. return [];
  207. }
  208. /**
  209. * Calculates dependencies for the configured plugin.
  210. *
  211. * Dependencies are saved in the plugin's configuration entity and are used to
  212. * determine configuration synchronization order. For example, if the plugin
  213. * integrates with specific user roles, this method should return an array of
  214. * dependencies listing the specified roles.
  215. *
  216. * @return array
  217. * An array of dependencies grouped by type (config, content, module,
  218. * theme). For example:
  219. * @code
  220. * array(
  221. * 'config' => array('user.role.anonymous', 'user.role.authenticated'),
  222. * 'content' => array('node:article:f0a189e6-55fb-47fb-8005-5bef81c44d6d'),
  223. * 'module' => array('node', 'user'),
  224. * 'theme' => array('seven'),
  225. * );
  226. * @endcode
  227. *
  228. * @see \Drupal\Core\Config\Entity\ConfigDependencyManager
  229. * @see \Drupal\Core\Entity\EntityInterface::getConfigDependencyName()
  230. */
  231. public function calculateDependencies() {
  232. return [];
  233. }
  234. }