3 namespace Drupal\file\Plugin\migrate\destination;
5 use Drupal\Core\Field\Plugin\Field\FieldType\UriItem;
6 use Drupal\migrate\Row;
7 use Drupal\migrate\MigrateException;
8 use Drupal\migrate\Plugin\migrate\destination\EntityContentBase;
11 * @MigrateDestination(
15 class EntityFile extends EntityContentBase {
20 protected function getEntity(Row $row, array $old_destination_id_values) {
21 // For stub rows, there is no real file to deal with, let the stubbing
22 // process take its default path.
24 return parent::getEntity($row, $old_destination_id_values);
27 // By default the entity key (fid) would be used, but we want to make sure
28 // we're loading the matching URI.
29 $destination = $row->getDestinationProperty('uri');
30 if (empty($destination)) {
31 throw new MigrateException('Destination property uri not provided');
33 $entity = $this->storage->loadByProperties(['uri' => $destination]);
35 return reset($entity);
38 return parent::getEntity($row, $old_destination_id_values);
45 protected function processStubRow(Row $row) {
46 // We stub the uri value ourselves so we can create a real stub file for it.
47 if (!$row->getDestinationProperty('uri')) {
48 $field_definitions = $this->entityManager
49 ->getFieldDefinitions($this->storage->getEntityTypeId(),
50 $this->getKey('bundle'));
51 $value = UriItem::generateSampleValue($field_definitions['uri']);
53 throw new MigrateException('Stubbing failed, unable to generate value for field uri');
55 // generateSampleValue() wraps the value in an array.
56 $value = reset($value);
57 // Make it into a proper public file uri, stripping off the existing
59 $value = 'public://' . preg_replace('|^[a-z]+://|i', '', $value);
60 $value = mb_substr($value, 0, $field_definitions['uri']->getSetting('max_length'));
61 // Create a real file, so File::preSave() can do filesize() on it.
63 $row->setDestinationProperty('uri', $value);
65 parent::processStubRow($row);