How can I dynamically get the fields on an image media bundle? What’s the correct way to get all of the key/values for a bundle on a media entity? 

I am trying to create a media entity programmatically and I need to get all of the fields on the image bundle. I am not sure how to get the image bundle ID either. 

In other words, I’d like the module I'm working on to be a bit more generic and reusable as I’ve seen the image bundle have different names depending on the installation.

Here’s what I have so far but the two main problems I see are that the image bundle ID can change and the field names on the bundle can be different.

   $entity = $this-&gt;createFile(
      $uri,
      $file[0]['filename'],
      $file[0]['filesize'],
      $this-&gt;currentUser
    );
    $entity-&gt;setPermanent();
    $entity-&gt;save();
    // Save media entity
    $media = [
      'bundle' =&gt; 'image',
      'uid' =&gt; $this-&gt;currentUser-&gt;id(),
      'status' =&gt; 1,
      'image' =&gt; [
        'target_id' =&gt; $entity-&gt;id(),
        'alt' =&gt; t(basename($file[0]['filename'])),
        'title' =&gt; t(basename($file[0]['filename'])),
      ],
    ];
    $image = $this-&gt;entityTypeManager-&gt;getStorage('media')-&gt;create($media);
    $image-&gt;save();


I'd like to be able to get the image bundle and dynamically figure out whichever field has the target_id and then assign the previously created file entity to that. I do not know how to get the image bundle schema, array signature, in order to traverse the key/values to find the target_id
You can traverse the field definitions of the media bundle image and look for a field with the type image:

$fields = \Drupal::service('entity_field.manager')-&gt;getFieldDefinitions('media', 'image');
foreach ($fields as $key =&gt; $field) {
  if ($field-&gt;getType() === 'image') {
    // found image field $key
  }
}


To get all media bundles:

$bundles = \Drupal::service('entity_type.bundle.info')-&gt;getBundleInfo('media');