Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class NetworkContext extends RequestStackCacheContextBase implements CacheContextInterface {
- /**
- * {@inheritdoc}
- */
- public static function getLabel() {
- return t('Network');
- }
- /**
- * {@inheritdoc}
- */
- public function getContext() {
- if (Util::requestFromCampus($this->requestStack->getCurrentRequest()->getClientIp())) {
- return 'oncampus';
- }
- else {
- return 'offcampus';
- }
- }
- /**
- * {@inheritdoc}
- */
- public function getCacheableMetadata() {
- return new CacheableMetadata();
- }
- }
- public function myCustomAction(Request $request) {
- $build = [];
- $build['my_data'] = [
- '#theme' => 'my_custom_theme_function',
- '#rawdata' => $this->fetchData(Util::requestIsFromCampus($request->getClientIp()));
- ];
- // Add some cache metadata that indicates this render array varies
- // based on the user's network. We can't effectively use cache tags
- // here since the data is retrieved from an external service and we
- // don't know when it's updated. Instead, expire the result after
- // one hour.
- $build['#cache'] = [
- 'max-age' => 60 * 60,
- 'contexts' => [
- 'network',
- ],
- ];
- return $build;
- }
- public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
- $ip = $request->getClientIp();
- if (Util::requestFromCampus($ip)) {
- $request->query->add(['oncampus' => '1']);
- }
- else {
- // remove the query parameter in case an off-campus user sets it incorrectly
- $request->query->remove('oncampus');
- }
- return $this->httpKernel->handle($request, $type, $catch);
- }
- <?php
- namespace Drupalmy_moduleEventSubscriber;
- /**
- * Class MyCustomSubscriber.
- */
- class MyCustomSubscriber implements EventSubscriberInterface {
- public static function getSubscribedEvents() {
- $events[KernelEvents::REQUEST] = ['myCustomRedirect', 28];
- return $events;
- }
- public function myCustomRedirect(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) {
- if (Drupal::service('router.admin_context')->isAdminRoute()) {
- return;
- }
- Drupal::service('page_cache_kill_switch')->trigger();
- // ...
- }
- }
Add Comment
Please, Sign In to add comment