SetLocaleAction.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Author: Eugine Terentev <eugine@terentev.net>
  4. */
  5. namespace plugins\locale;
  6. use Yii;
  7. use yii\base\Action;
  8. use yii\base\InvalidParamException;
  9. use yii\web\Cookie;
  10. /**
  11. * Class SetLocaleAction
  12. * @package common\actions
  13. *
  14. * Example:
  15. *
  16. * public function actions()
  17. * {
  18. * return [
  19. * 'set-locale'=>[
  20. * 'class'=>'common\actions\SetLocaleAction',
  21. * 'locales'=>[
  22. * 'en-US', 'ru-RU', 'ua-UA'
  23. * ],
  24. * 'localeCookieName'=>'_locale',
  25. * 'callback'=>function($action){
  26. * return $this->controller->redirect(/.. some url ../)
  27. * }
  28. * ]
  29. * ];
  30. * }
  31. */
  32. class SetLocaleAction extends Action
  33. {
  34. /**
  35. * @var array List of available locales
  36. */
  37. public $locales;
  38. /**
  39. * @var string
  40. */
  41. public $localeCookieName = '_locale';
  42. /**
  43. * @var integer
  44. */
  45. public $cookieExpire;
  46. /**
  47. * @var string
  48. */
  49. public $cookieDomain;
  50. /**
  51. * @var \Closure
  52. */
  53. public $callback;
  54. /**
  55. * @param $locale
  56. * @return mixed
  57. */
  58. public function run($locale)
  59. {
  60. if (!is_array($this->locales) || !in_array($locale, $this->locales, true)) {
  61. throw new InvalidParamException('Unacceptable locale');
  62. }
  63. $cookie = new Cookie([
  64. 'name' => $this->localeCookieName,
  65. 'value' => $locale,
  66. 'expire' => $this->cookieExpire ?: time() + 60 * 60 * 24 * 365,
  67. 'domain' => $this->cookieDomain ?: '',
  68. ]);
  69. Yii::$app->getResponse()->getCookies()->add($cookie);
  70. if ($this->callback && $this->callback instanceof \Closure) {
  71. return call_user_func_array($this->callback, [
  72. $this,
  73. $locale
  74. ]);
  75. }
  76. return Yii::$app->response->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
  77. }
  78. }