RulesComponentRepository.php in Rules 8.3
File
src/Engine/RulesComponentRepository.php
View source
<?php
namespace Drupal\rules\Engine;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\rules\Exception\InvalidArgumentException;
class RulesComponentRepository implements RulesComponentRepositoryInterface {
protected $resolvers = [];
protected $components = [];
protected $cacheBackend;
protected $languageManager;
protected $langcode;
public function __construct(CacheBackendInterface $cache_backend, LanguageManagerInterface $language_manager) {
$this->cacheBackend = $cache_backend;
$this->languageManager = $language_manager;
$this->langcode = $this->languageManager
->getCurrentLanguage()
->getId();
}
public function addComponentResolver(RulesComponentResolverInterface $resolver, $resolver_name) {
$this->resolvers[$resolver_name] = $resolver;
return $this;
}
public function get($id, $provider = 'rules_component') {
$result = $this
->getMultiple([
$id,
], $provider);
return reset($result) ?: NULL;
}
public function getMultiple(array $ids, $provider = 'rules_component') {
if (!isset($this->resolvers[$provider])) {
throw new InvalidArgumentException("Invalid component provider {$provider} given.");
}
$cids = [];
foreach ($ids as $id) {
$cids[$id] = "{$provider}:{$id}:{$this->langcode}";
}
$results = array_intersect_key($this->components, array_flip($cids));
$cids_missing = array_diff_assoc($cids, array_keys($results));
if ($cids_missing) {
$cache_results = $this->cacheBackend
->getMultiple($cids_missing);
foreach ($cache_results as $cid => $cache_result) {
$this->components[$cid] = $cache_result->data;
$results[$cid] = $cache_result->data;
}
if ($cids_missing) {
$resolved_results = $this->resolvers[$provider]
->getMultiple(array_keys($cids_missing));
if ($resolved_results) {
$cache_items = [];
foreach ($resolved_results as $id => $component) {
$cid = $cids[$id];
$this->components[$cid] = $component;
$results[$cid] = $component;
$cache_items[$cid]['data'] = $component;
$cache_items[$cid]['tags'] = [
$id,
];
}
$this->cacheBackend
->setMultiple($cache_items);
}
}
}
return $results;
}
}