Skip to content

Instantly share code, notes, and snippets.

@damiankloip
Created September 30, 2015 08:26
Show Gist options
  • Save damiankloip/0c8f28006a2d979c43d3 to your computer and use it in GitHub Desktop.
Save damiankloip/0c8f28006a2d979c43d3 to your computer and use it in GitHub Desktop.
Entity iterator with generator
<?php
/**
* @file
* Contains \Drupal\Core\Entity\EntityIterator.
*/
namespace Drupal\Core\Entity;
/**
* Provides an Iterator class for dealing with large amounts of entities
* but not loading them all into memory.
*/
class EntityIterator implements \IteratorAggregate, \Countable {
/**
* The entity storage controller to load entities.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $entityStorage;
/**
* An array of entity IDs to iterate over.
*
* @var array
*/
protected $entityIds;
/**
* The Amount of cached entities to store before clearing the static cache.
*
* @var int
*/
protected $cacheLimit;
/**
* Constructs an entity iterator object.
*
* @param \Drupal\Core\Entity\EntityStorageInterface $entity_controller
* @param array $ids
* @param int $cache_limit
*/
public function __construct(EntityStorageInterface $entity_storage_controller, array $ids, $cache_limit = 50) {
$this->entityStorage = $entity_storage_controller;
// Make sure we don't use a keyed array.
$this->entityIds = array_values($ids);
$this->cacheLimit = (int) $cache_limit;
}
/**
* Implements \Countable::count().
*/
public function count() {
return count($this->entityIds);
}
/**
* Implements \IteratorAggregate::GetIterator()
*/
public function getIterator() {
foreach (array_chunk($this->entityIds, $this->cacheLimit) as $ids_chunk) {
foreach ($this->loadEntities($ids_chunk) as $id => $entity) {
yield $id => $entity;
}
}
}
/**
* Loads a set of entities.
*
* This depends on the cacheLimit property.
*/
protected function loadEntities(array $ids) {
// Reset any previously loaded entities then load the current set of IDs.
$this->entityStorage->resetCache();
return $this->entityStorage->loadMultiple($ids);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment