Version 1
[yaffs-website] / web / modules / contrib / video_embed_field / modules / video_embed_media / src / UpgradeManager.php
1 <?php
2
3 namespace Drupal\video_embed_media;
4
5 use Drupal\Core\Entity\Query\QueryFactory;
6 use Drupal\media_entity\Entity\Media;
7 use Drupal\media_entity\Entity\MediaBundle;
8 use Drupal\video_embed_media\Plugin\MediaEntity\Type\VideoEmbedField;
9
10 /**
11  * Upgrades existing media_entity_embedded_video bundles.
12  */
13 class UpgradeManager implements UpgradeManagerInterface {
14
15   /**
16    * The entity query factory.
17    *
18    * @var \Drupal\Core\Entity\Query\QueryFactory
19    */
20   protected $entityQuery;
21
22   /**
23    * UpgradeManager constructor.
24    *
25    * @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
26    *   The entity query service.
27    */
28   public function __construct(QueryFactory $entity_query) {
29     $this->entityQuery = $entity_query;
30   }
31
32   /**
33    * {@inheritdoc}
34    */
35   public function upgrade() {
36     $entities = $this->entityQuery->get('media_bundle')->condition('type', 'embeddable_video')->execute();
37     foreach ($entities as $entity) {
38       $bundle = MediaBundle::load($entity);
39       $this->upgradeBundle($bundle);
40     }
41   }
42
43   /**
44    * Upgrade a whole bundle to use video_embed_field.
45    *
46    * @param \Drupal\media_entity\Entity\MediaBundle $bundle
47    *   The media bundle object.
48    */
49   protected function upgradeBundle(MediaBundle $bundle) {
50     // Create a video embed field on the media bundle.
51     VideoEmbedField::createVideoEmbedField($bundle->id());
52     // Load and update all of the existing media entities.
53     $media_entities = $this->entityQuery->get('media')->condition('bundle', $bundle->id())->execute();
54     foreach ($media_entities as $media_entity) {
55       $media_entity = Media::load($media_entity);
56       $this->upgradeEntity($media_entity, $bundle->getTypeConfiguration());
57     }
58     // Update the media bundle type.
59     $bundle->type = 'video_embed_field';
60     $bundle->save();
61   }
62
63   /**
64    * Upgrade an individual media entity.
65    *
66    * @param \Drupal\media_entity\Entity\Media $media_entity
67    *   The media entity.
68    * @param array $type_configuration
69    *   The media type configuration.
70    */
71   protected function upgradeEntity(Media $media_entity, $type_configuration) {
72     // Copy the existing media bundle field value to the new field value.
73     $existing_url_field = $media_entity->{$type_configuration['source_field']}->getValue();
74     $existing_url = isset($existing_url_field[0]['uri']) ? $existing_url_field[0]['uri'] : $existing_url_field[0]['value'];
75     $media_entity->{VideoEmbedField::VIDEO_EMBED_FIELD_DEFAULT_NAME} = [['value' => $existing_url]];
76     $media_entity->save();
77   }
78
79 }