RefererRedirectComponent.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Tools\Controller\Component;
  3. use Cake\Controller\Component;
  4. use Cake\Event\Event;
  5. use Cake\Http\Response;
  6. /**
  7. * Uses a referer key in query string to redirect to given referer.
  8. * Useful for passing to edit forms if you want a different target as redirect than the default.
  9. * The neat thing here is that it doesn't require changes to existing actions. This can just be
  10. * added on top, for one or all controllers.
  11. */
  12. class RefererRedirectComponent extends Component {
  13. const QUERY_REFERER = 'ref';
  14. /**
  15. * @var array
  16. */
  17. protected $_defaultConfig = [
  18. 'actions' => [],
  19. ];
  20. /**
  21. * @param \Cake\Event\Event $event
  22. * @param string|array $url A string or array containing the redirect location
  23. * @param \Cake\Http\Response $response The response object.
  24. *
  25. * @return \Cake\Http\Response|null
  26. */
  27. public function beforeRedirect(Event $event, $url, Response $response) {
  28. $actions = $this->getConfig('actions');
  29. $currentAction = $this->getController()->getRequest()->getParam('action');
  30. if ($actions && !in_array($currentAction, $actions, true)) {
  31. return null;
  32. }
  33. $referer = $this->referer();
  34. if (!$referer) {
  35. return null;
  36. }
  37. return $response->withLocation($referer);
  38. }
  39. /**
  40. * Only accept relative URLs.
  41. *
  42. * @see \Cake\Http\ServerRequest::referer()
  43. *
  44. * @return string|null
  45. */
  46. protected function referer() {
  47. $referer = $this->getController()->getRequest()->getQuery(static::QUERY_REFERER);
  48. if (!$referer) {
  49. return null;
  50. }
  51. if (strpos($referer, '/') !== 0) {
  52. return null;
  53. }
  54. return $referer;
  55. }
  56. }