Skip to content

Instantly share code, notes, and snippets.

@nikathone
Last active October 26, 2017 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikathone/3c8afd5d768ba07d7edab50a52cd0323 to your computer and use it in GitHub Desktop.
Save nikathone/3c8afd5d768ba07d7edab50a52cd0323 to your computer and use it in GitHub Desktop.
Current store context.
<?php
namespace Drupal\customize_commerce\ContextProvider;
use Drupal\commerce_store\CurrentStoreInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Sets the current store as a context.
*/
class CurrentStoreContext implements ContextProviderInterface {
use StringTranslationTrait;
/**
* The current store service.
*
* @var \Drupal\commerce_store\CurrentStoreInterface
*/
protected $currentStore;
/**
* Construct a new CurrentStoreContext.
*
* @param \Drupal\commerce_store\CurrentStoreInterface $current_store
* The current store service.
*/
public function __construct(CurrentStoreInterface $current_store) {
$this->currentStore = $current_store;
}
/**
* {@inheritdoc}
*/
public function getRuntimeContexts(array $unqualified_context_ids) {
$current_store = $this->currentStore->getStore();
$context = new Context(new ContextDefinition('entity:commerce_store', $this->t('Current store')), $current_store);
$cacheability = new CacheableMetadata();
$cacheability->setCacheContexts(['store']);
$context->addCacheableDependency($cacheability);
$result = [
'current_store' => $context,
];
return $result;
}
/**
* {@inheritdoc}
*/
public function getAvailableContexts() {
return $this->getRuntimeContexts([]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment