Pull merge.
[yaffs-website] / web / core / modules / file / src / Plugin / migrate / destination / EntityFile.php
1 <?php
2
3 namespace Drupal\file\Plugin\migrate\destination;
4
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;
9
10 /**
11  * @MigrateDestination(
12  *   id = "entity:file"
13  * )
14  */
15 class EntityFile extends EntityContentBase {
16
17   /**
18    * {@inheritdoc}
19    */
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.
23     if ($row->isStub()) {
24       return parent::getEntity($row, $old_destination_id_values);
25     }
26
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');
32     }
33     $entity = $this->storage->loadByProperties(['uri' => $destination]);
34     if ($entity) {
35       return reset($entity);
36     }
37     else {
38       return parent::getEntity($row, $old_destination_id_values);
39     }
40   }
41
42   /**
43    * {@inheritdoc}
44    */
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']);
52       if (empty($value)) {
53         throw new MigrateException('Stubbing failed, unable to generate value for field uri');
54       }
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
58       // scheme if present.
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.
62       touch($value);
63       $row->setDestinationProperty('uri', $value);
64     }
65     parent::processStubRow($row);
66   }
67
68 }