Skip to content

Instantly share code, notes, and snippets.

@drubb
Last active June 7, 2024 09:42
Show Gist options
  • Select an option

  • Save drubb/5090a7845e0cc4fe7330effd57e1af3e to your computer and use it in GitHub Desktop.

Select an option

Save drubb/5090a7845e0cc4fe7330effd57e1af3e to your computer and use it in GitHub Desktop.
Using a php generator to parse and process Drupal media entities. Executable using drush scr
<?php
use Drupal\media\Entity\Media;
// Get the ids of all media entities.
$media_ids = \Drupal::entityQuery('media')
->accessCheck(FALSE)
->execute();
// Load and process each media entity.
foreach (getMediaEntities($media_ids) as $media) {
echo $media->id() . PHP_EOL;
}
/**
* Get media entities one by one by their ids.
*
* @param int[] $media_ids
* The media entity ids.
*
* @return Generator
* The media entities, one by one.
*/
function getMediaEntities(array $media_ids): Generator {
foreach ($media_ids as $id) {
$media = Media::load($id);
if ($media !== NULL) {
yield $media;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment