Guest User

Untitled

a guest
Jun 25th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. class NetworkContext extends RequestStackCacheContextBase implements CacheContextInterface {
  2.  
  3. /**
  4. * {@inheritdoc}
  5. */
  6. public static function getLabel() {
  7. return t('Network');
  8. }
  9.  
  10. /**
  11. * {@inheritdoc}
  12. */
  13. public function getContext() {
  14. if (Util::requestFromCampus($this->requestStack->getCurrentRequest()->getClientIp())) {
  15. return 'oncampus';
  16. }
  17. else {
  18. return 'offcampus';
  19. }
  20. }
  21.  
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function getCacheableMetadata() {
  26. return new CacheableMetadata();
  27. }
  28.  
  29. }
  30.  
  31. public function myCustomAction(Request $request) {
  32. $build = [];
  33.  
  34. $build['my_data'] = [
  35. '#theme' => 'my_custom_theme_function',
  36. '#rawdata' => $this->fetchData(Util::requestIsFromCampus($request->getClientIp()));
  37. ];
  38.  
  39. // Add some cache metadata that indicates this render array varies
  40. // based on the user's network. We can't effectively use cache tags
  41. // here since the data is retrieved from an external service and we
  42. // don't know when it's updated. Instead, expire the result after
  43. // one hour.
  44. $build['#cache'] = [
  45. 'max-age' => 60 * 60,
  46. 'contexts' => [
  47. 'network',
  48. ],
  49. ];
  50.  
  51. return $build;
  52. }
  53.  
  54. public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
  55. $ip = $request->getClientIp();
  56. if (Util::requestFromCampus($ip)) {
  57. $request->query->add(['oncampus' => '1']);
  58. }
  59. else {
  60. // remove the query parameter in case an off-campus user sets it incorrectly
  61. $request->query->remove('oncampus');
  62. }
  63. return $this->httpKernel->handle($request, $type, $catch);
  64. }
  65.  
  66. <?php
  67.  
  68. namespace Drupalmy_moduleEventSubscriber;
  69.  
  70. /**
  71. * Class MyCustomSubscriber.
  72. */
  73. class MyCustomSubscriber implements EventSubscriberInterface {
  74.  
  75. public static function getSubscribedEvents() {
  76. $events[KernelEvents::REQUEST] = ['myCustomRedirect', 28];
  77. return $events;
  78. }
  79.  
  80. public function myCustomRedirect(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) {
  81. if (Drupal::service('router.admin_context')->isAdminRoute()) {
  82. return;
  83. }
  84.  
  85. Drupal::service('page_cache_kill_switch')->trigger();
  86.  
  87. // ...
  88.  
  89. }
  90. }
Add Comment
Please, Sign In to add comment