3 namespace Drupal\video_embed_media;
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;
11 * Upgrades existing media_entity_embedded_video bundles.
13 class UpgradeManager implements UpgradeManagerInterface {
16 * The entity query factory.
18 * @var \Drupal\Core\Entity\Query\QueryFactory
20 protected $entityQuery;
23 * UpgradeManager constructor.
25 * @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
26 * The entity query service.
28 public function __construct(QueryFactory $entity_query) {
29 $this->entityQuery = $entity_query;
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);
44 * Upgrade a whole bundle to use video_embed_field.
46 * @param \Drupal\media_entity\Entity\MediaBundle $bundle
47 * The media bundle object.
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());
58 // Update the media bundle type.
59 $bundle->type = 'video_embed_field';
64 * Upgrade an individual media entity.
66 * @param \Drupal\media_entity\Entity\Media $media_entity
68 * @param array $type_configuration
69 * The media type configuration.
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();