ReinstallSourceBase.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 = "$importPath/$baseFilePath";
  158. $realPath = realpath($filePath);
  159. if (!is_file($realPath) || !is_readable($realPath)) {
  160. throw new MigrateException("${filePath} is not a readable file.");
  161. }
  162. try {
  163. $raw = file_get_contents($filePath);
  164. $data = Yaml::parse($raw);
  165. }
  166. catch (ParseException $e) {
  167. throw new MigrateException("Cannot parse the contents of ${filePath}.");
  168. }
  169. if ($key) {
  170. return $data[$key] ?? [];
  171. }
  172. return $data ?? [];
  173. }
  174. /**
  175. * {@inheritdoc}
  176. */
  177. public function __toString() {
  178. $current = $this->getIterator()->current();
  179. $ret = json_encode($current, JSON_PRETTY_PRINT);
  180. return $ret;
  181. }
  182. /**
  183. * Gets this plugin's configuration.
  184. *
  185. * @return array
  186. * An array of this plugin's configuration.
  187. */
  188. public function getConfiguration() {
  189. return $this->configuration;
  190. }
  191. /**
  192. * Sets the configuration for this plugin instance.
  193. *
  194. * @param array $configuration
  195. * An associative array containing the plugin's configuration.
  196. */
  197. public function setConfiguration(array $configuration) {
  198. $this->configuration = $configuration;
  199. }
  200. /**
  201. * Gets default configuration for this plugin.
  202. *
  203. * @return array
  204. * An associative array with the default configuration.
  205. */
  206. public function defaultConfiguration() {
  207. return [];
  208. }
  209. /**
  210. * Calculates dependencies for the configured plugin.
  211. *
  212. * Dependencies are saved in the plugin's configuration entity and are used to
  213. * determine configuration synchronization order. For example, if the plugin
  214. * integrates with specific user roles, this method should return an array of
  215. * dependencies listing the specified roles.
  216. *
  217. * @return array
  218. * An array of dependencies grouped by type (config, content, module,
  219. * theme). For example:
  220. * @code
  221. * array(
  222. * 'config' => array('user.role.anonymous', 'user.role.authenticated'),
  223. * 'content' => array('node:article:f0a189e6-55fb-47fb-8005-5bef81c44d6d'),
  224. * 'module' => array('node', 'user'),
  225. * 'theme' => array('seven'),
  226. * );
  227. * @endcode
  228. *
  229. * @see \Drupal\Core\Config\Entity\ConfigDependencyManager
  230. * @see \Drupal\Core\Entity\EntityInterface::getConfigDependencyName()
  231. */
  232. public function calculateDependencies() {
  233. return [];
  234. }
  235. }