Created
September 30, 2015 08:26
-
-
Save damiankloip/0c8f28006a2d979c43d3 to your computer and use it in GitHub Desktop.
Entity iterator with generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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