setDestinationProperty example



  /** * Tests setting and getting the destination. */
  public function testDestination() {
    $row = new Row($this->testValues, $this->testSourceIds);
    $this->assertEmpty($row->getDestination());
    $this->assertFalse($row->hasDestinationProperty('nid'));

    // Set a destination.     $row->setDestinationProperty('nid', 2);
    $this->assertTrue($row->hasDestinationProperty('nid'));
    $this->assertEquals(['nid' => 2]$row->getDestination());
  }

  /** * Tests setting/getting multiple destination IDs. */
  public function testMultipleDestination() {
    $row = new Row($this->testValues, $this->testSourceIds);
    // Set some deep nested values.     $row->setDestinationProperty('image/alt', 'alt text');
    
if (empty($value)) {
        throw new MigrateException('Stubbing failed, unable to generate value for field uri');
      }
      // generateSampleValue() wraps the value in an array.       $value = reset($value);
      // Make it into a proper public file uri, stripping off the existing       // scheme if present.       $value = 'public://' . preg_replace('|^[a-z]+://|i', '', $value);
      $value = mb_substr($value, 0, $field_definitions['uri']->getSetting('max_length'));
      // Create a real file, so File::preSave() can do filesize() on it.       touch($value);
      $row->setDestinationProperty('uri', $value);
    }
    parent::processStubRow($row);
  }

}

  public function testImport() {
    $values = [
      'entity_type' => 'entity_type_test',
      'bundle' => 'bundle_test',
      'form_mode' => 'form_mode_test',
      'field_name' => 'field_name_test',
      'options' => ['test setting'],
    ];
    $row = new Row();
    foreach ($values as $key => $value) {
      $row->setDestinationProperty($key$value);
    }
    $entity = $this->getMockBuilder('Drupal\Core\Entity\Entity\EntityFormDisplay')
      ->disableOriginalConstructor()
      ->getMock();
    $entity->expects($this->once())
      ->method('setComponent')
      ->with('field_name_test', ['test setting'])
      ->will($this->returnSelf());
    $entity->expects($this->once())
      ->method('save')
      ->with();
    
$entity = $entity->getTranslation($language);
      }
    }

    // If the migration has specified a list of properties to be overwritten,     // clone the row with an empty set of destination values, and re-add only     // the specified properties.     if (isset($this->configuration['overwrite_properties'])) {
      $empty_destinations = array_intersect($empty_destinations$this->configuration['overwrite_properties']);
      $clone = $row->cloneWithoutDestination();
      foreach ($this->configuration['overwrite_properties'] as $property) {
        $clone->setDestinationProperty($property$row->getDestinationProperty($property));
      }
      $row = $clone;
    }

    foreach ($row->getDestination() as $field_name => $values) {
      $field = $entity->$field_name;
      if ($field instanceof TypedDataInterface) {
        $field->setValue($values);
      }
    }
    foreach ($empty_destinations as $field_name) {
      
// We want to create a new entity. Set enforceIsNew() FALSE is necessary       // to properly save a new entity while setting the ID. Without it, the       // system would see that the ID is already set and assume it is an update.       $entity->enforceIsNew(FALSE);
      // Intentionally create a new revision. Setting new revision TRUE here may       // not be necessary, it is done for clarity.       $entity->setNewRevision(TRUE);
    }
    else {
      // Attempt to set the bundle.       if ($bundle = $this->getBundle($row)) {
        $row->setDestinationProperty($this->getKey('bundle')$bundle);
      }

      // Stubs might need some required fields filled in.       if ($row->isStub()) {
        $this->processStubRow($row);
      }
      $entity = $this->storage->create($row->getDestination());
      $entity->enforceIsNew();
    }

    // We need to update the entity, so that the destination row IDs are
protected function processStubRow(Row $row) {
    parent::processStubRow($row);

    $field_definitions = $this->entityFieldManager
      ->getFieldDefinitions($this->storage->getEntityTypeId(),
        $this->getKey('bundle'));

    // Name is generated using a dedicated sample value generator to ensure     // uniqueness and a valid length.     // @todo Remove this as part of https://www.drupal.org/node/3352288.     $name = UserNameItem::generateSampleValue($field_definitions['name']);
    $row->setDestinationProperty('name', reset($name));

    // Email address is not defined as required in the base field definition but     // is effectively required by the UserMailRequired constraint. This means     // that Entity::processStubRow() did not populate it - we do it here.     $mail = EmailItem::generateSampleValue($field_definitions['mail']);
    $row->setDestinationProperty('mail', reset($mail));
  }

  /** * {@inheritdoc} */
  

  protected function doCreateStub(MigrationInterface $migration, array $source_ids, array $default_values = []) {
    $destination = $migration->getDestinationPlugin(TRUE);
    $process = $migration->getProcess();
    $id_map = $migration->getIdMap();
    $migrate_executable = new MigrateExecutable($migration);
    $row = new Row($source_ids + $migration->getSourceConfiguration()$migration->getSourcePlugin()->getIds(), TRUE);
    $migrate_executable->processRow($row$process);
    foreach ($default_values as $key => $value) {
      $row->setDestinationProperty($key$value);
    }
    $destination_ids = [];
    try {
      $destination_ids = $destination->import($row);
    }
    catch (\Exception $e) {
      $id_map->saveMessage($row->getSourceIdValues()$e->getMessage());
    }
    if ($destination_ids) {
      $id_map->saveIdMapping($row$destination_ids, MigrateIdMapInterface::STATUS_NEEDS_UPDATE);
      return $destination_ids;
    }
// Get permissions that do not exist on the destination.     $invalid_permissions = array_diff($permissions$this->destinationPermissions);
    if ($invalid_permissions) {
      sort($invalid_permissions);
      // Log the message in the migration message table.       $message = "Permission(s) '" . implode("', '", $invalid_permissions) . "' not found.";
      $this->migration->getIdMap()
        ->saveMessage($row->getSourceIdValues()$message, MigrationInterface::MESSAGE_WARNING);
    }

    $valid_permissions = array_intersect($permissions$this->destinationPermissions);
    $row->setDestinationProperty('permissions', $valid_permissions);
    return parent::import($row$old_destination_id_values);
  }

}
/** * {@inheritdoc} */
  public function import(Row $row, array $old_destination_id_values = []) {
    $effects = [];

    // Need to set the effects property to null on the row before the ImageStyle     // is created, this prevents improper effect plugin initialization.     if ($row->getDestinationProperty('effects')) {
      $effects = $row->getDestinationProperty('effects');
      $row->setDestinationProperty('effects', []);
    }

    /** @var \Drupal\image\Entity\ImageStyle $style */
    $style = $this->getEntity($row$old_destination_id_values);

    // Iterate the effects array so each effect plugin can be initialized.     // Catch any missing plugin exceptions.     foreach ($effects as $effect) {
      try {
        $style->addImageEffect($effect);
      }
      

  protected function getEntity(Row $row, array $old_destination_id_values) {
    $entity_id = reset($old_destination_id_values) ?: $this->getEntityId($row);
    if (!empty($entity_id) && ($entity = $this->storage->load($entity_id))) {
      // Allow updateEntity() to change the entity.       $entity = $this->updateEntity($entity$row) ?: $entity;
    }
    else {
      // Attempt to ensure we always have a bundle.       if ($bundle = $this->getBundle($row)) {
        $row->setDestinationProperty($this->getKey('bundle')$bundle);
      }

      // Stubs might need some required fields filled in.       if ($row->isStub()) {
        $this->processStubRow($row);
      }
      $entity = $this->storage->create($row->getDestination());
      $entity->enforceIsNew();
    }
    return $entity;
  }

  

    return $return;
  }

  /** * {@inheritdoc} */
  protected function processStubRow(Row $row) {
    parent::processStubRow($row);
    // Neither uid nor name is required in itself, but it is required to set one     // of them.     $row->setDestinationProperty('name', 'anonymous_stub');
  }

}
// Prepend the process plugin id to the message.           $message = sprintf("%s: %s", $plugin->getPluginId()$e->getMessage());
          throw new MigrateException($message);
        }

        $multiple = $plugin->multiple();
      }
    }
    // Ensure all values, including nulls, are migrated.     if ($plugins) {
      if (isset($value)) {
        $row->setDestinationProperty($destination$value);
      }
      else {
        $row->setEmptyDestinationProperty($destination);
      }
    }
  }

  /** * Fetches the key array for the current source record. * * @return array * The current source IDs. */

  public function testImport() {
    $values = [
      'entity_type' => 'entity_type_test',
      'bundle' => 'bundle_test',
      'view_mode' => 'view_mode_test',
      'field_name' => 'field_name_test',
      'options' => ['test setting'],
    ];
    $row = new Row();
    foreach ($values as $key => $value) {
      $row->setDestinationProperty($key$value);
    }
    $entity = $this->getMockBuilder('Drupal\Core\Entity\Entity\EntityViewDisplay')
      ->disableOriginalConstructor()
      ->getMock();
    $entity->expects($this->once())
      ->method('setComponent')
      ->with('field_name_test', ['test setting'])
      ->will($this->returnSelf());
    $entity->expects($this->once())
      ->method('save')
      ->with();
    
// Existing non-default translation.       ['id' => 3, 'langcode' => 'fr', 'action' => MigrateIdMapInterface::ROLLBACK_PRESERVE],
      // Brand new row.       ['id' => 4, 'langcode' => 'fr', 'action' => MigrateIdMapInterface::ROLLBACK_DELETE],
    ];
    $rollback_actions = [];

    // Import some rows.     foreach ($destination_rows as $idx => $destination_row) {
      $row = new Row();
      foreach ($destination_row as $key => $value) {
        $row->setDestinationProperty($key$value);
      }
      $this->destination->import($row);

      // Check that the rollback action is correct, and save it.       $this->assertEquals($destination_row['action']$this->destination->rollbackAction());
      $rollback_actions[$idx] = $this->destination->rollbackAction();
    }

    $this->assertTranslations(1, 'en');
    $this->assertTranslations(2, 'fr', ['en']);
    $this->assertTranslations(3, 'en', ['fr']);
    
$this->storage->getEntityType()->willReturn($entity_type->reveal());

    // Assert we load the correct revision.     $this->storage->loadRevision(2)
      ->shouldBeCalled()
      ->willReturn($entity->reveal());
    // Make sure its set as an update and not the default revision.     $entity->setNewRevision(FALSE)->shouldBeCalled();
    $entity->isDefaultRevision(FALSE)->shouldBeCalled();

    $row = new Row(['nid' => 1, 'vid' => 2]['nid' => 1, 'vid' => 2]);
    $row->setDestinationProperty('vid', 2);
    $this->assertEquals($entity->reveal()$destination->getEntity($row[]));
  }

  /** * Tests that new revisions are flagged to be written as new. * * @covers ::getEntity */
  public function testGetEntityNewRevision() {
    $destination = $this->getEntityRevisionDestination([]);
    $entity = $this->prophesize('\Drupal\Core\Entity\RevisionableInterface');

    
Home | Imprint | This part of the site doesn't use cookies.