GeoFieldConfigurator.php 2.17 KB
Newer Older
Mike Ryan's avatar
Mike Ryan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
<?php

namespace Drupal\acme_migrate\EventSubscriber;

use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateImportEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Handle disabling automatic geocoding during location migration.
 */
class GeoFieldConfigurator implements EventSubscriberInterface {

  /**
   * The geocoder settings before we changed them.
   *
   * @var array
   */
  protected $originalSettings;

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[MigrateEvents::PRE_IMPORT] = 'onMigrationPreImport';
    $events[MigrateEvents::POST_IMPORT] = 'onMigrationPostImport';
    return $events;
  }

  /**
   * Disable automatic geocoding for field_geofield.
   *
   * @param \Drupal\migrate\Event\MigrateImportEvent $event
   *   The import event.
   */
  public function onMigrationPreImport(MigrateImportEvent $event) {
    if ($event->getMigration()->id() == 'location') {
      $fields = \Drupal::entityTypeManager()->getStorage('field_config')->loadByProperties(['field_name' => 'field_geofield']);
      if ($fields) {
        /** @var \Drupal\field\Entity\FieldConfig $field */
        if ($field = $fields['node.location.field_geofield']) {
          $this->originalSettings = $field->getThirdPartySettings('geocoder_field');
          $field->setThirdPartySetting('geocoder_field', 'method', 'none');
          $field->save();
        }
      }
    }
  }

  /**
   * Re-enable automatic geocoding for field_geofield.
   *
   * @param \Drupal\migrate\Event\MigrateImportEvent $event
   *   The import event.
   */
  public function onMigrationPostImport(MigrateImportEvent $event) {
    if ($event->getMigration()->id() == 'location') {
      $fields = \Drupal::entityTypeManager()->getStorage('field_config')->loadByProperties(['field_name' => 'field_geofield']);
      if ($fields) {
        /** @var \Drupal\field\Entity\FieldConfig $field */
        if ($field = $fields['node.location.field_geofield']) {
          foreach ($this->originalSettings as $key => $value) {
            $field->setThirdPartySetting('geocoder_field', $key, $value);
          }
          $field->save();
        }
      }
    }
  }

}