LazyContextRepository.php in Drupal 8
File
core/lib/Drupal/Core/Plugin/Context/LazyContextRepository.php
View source
<?php
namespace Drupal\Core\Plugin\Context;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LazyContextRepository implements ContextRepositoryInterface {
protected $contextProviderServiceIDs = [];
protected $container;
protected $contexts = [];
public function __construct(ContainerInterface $container, array $context_provider_service_ids) {
$this->container = $container;
$this->contextProviderServiceIDs = $context_provider_service_ids;
}
public function getRuntimeContexts(array $context_ids) {
$contexts = [];
$context_ids_by_service = [];
foreach ($context_ids as $id) {
if (isset($this->contexts[$id])) {
$contexts[$id] = $this->contexts[$id];
continue;
}
if ($id[0] === '@' && strpos($id, ':') !== FALSE) {
list($service_id, $unqualified_context_id) = explode(':', $id, 2);
$service_id = substr($service_id, 1);
}
else {
throw new \InvalidArgumentException('You must provide the context IDs in the @{service_id}:{unqualified_context_id} format.');
}
$context_ids_by_service[$service_id][] = $unqualified_context_id;
}
foreach ($context_ids_by_service as $service_id => $unqualified_context_ids) {
$contexts_by_service = $this->container
->get($service_id)
->getRuntimeContexts($unqualified_context_ids);
$wanted_contexts = array_intersect_key($contexts_by_service, array_flip($unqualified_context_ids));
foreach ($wanted_contexts as $unqualified_context_id => $context) {
$context_id = '@' . $service_id . ':' . $unqualified_context_id;
$this->contexts[$context_id] = $contexts[$context_id] = $context;
}
}
return $contexts;
}
public function getAvailableContexts() {
$contexts = [];
foreach ($this->contextProviderServiceIDs as $service_id) {
$contexts_by_service = $this->container
->get($service_id)
->getAvailableContexts();
foreach ($contexts_by_service as $unqualified_context_id => $context) {
$context_id = '@' . $service_id . ':' . $unqualified_context_id;
$contexts[$context_id] = $context;
}
}
return $contexts;
}
}