| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentBoards\App\Hooks\Handlers; |
| 4 |
|
| 5 |
/** |
| 6 |
* Keeps authenticated Boards REST callbacks in the user's language without leaking locale changes. |
| 7 |
*/ |
| 8 |
class RestLocaleHandler |
| 9 |
{ |
| 10 |
protected $routePrefix; |
| 11 |
|
| 12 |
protected $localeSwitches = []; |
| 13 |
|
| 14 |
/** |
| 15 |
* Scope locale changes to the configured Boards REST namespace and version. |
| 16 |
*/ |
| 17 |
public function __construct($restNamespace, $restVersion) |
| 18 |
{ |
| 19 |
$this->routePrefix = '/' . trim($restNamespace, '/') . '/' . trim($restVersion, '/') . '/'; |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* Translate authenticated callbacks and policy errors using the user's locale. |
| 24 |
*/ |
| 25 |
public function switchToUserLocale($response, $handler, $request) |
| 26 |
{ |
| 27 |
$route = $request->get_route(); |
| 28 |
if (!is_user_logged_in() || strpos($route, $this->routePrefix) !== 0 |
| 29 |
|| strpos($route, $this->routePrefix . 'public/') === 0) { |
| 30 |
return $response; |
| 31 |
} |
| 32 |
|
| 33 |
// Track each request separately so nested REST calls cannot restore an outer switch. |
| 34 |
$requestId = spl_object_hash($request); |
| 35 |
$this->localeSwitches[$requestId][] = switch_to_locale(get_user_locale()); |
| 36 |
|
| 37 |
return $response; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Restore only the locale switch made for the completed request. |
| 42 |
*/ |
| 43 |
public function restoreLocale($response, $handler, $request) |
| 44 |
{ |
| 45 |
$requestId = spl_object_hash($request); |
| 46 |
if (!empty($this->localeSwitches[$requestId])) { |
| 47 |
if (array_pop($this->localeSwitches[$requestId])) { |
| 48 |
restore_previous_locale(); |
| 49 |
} |
| 50 |
if (!$this->localeSwitches[$requestId]) { |
| 51 |
unset($this->localeSwitches[$requestId]); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
return $response; |
| 56 |
} |
| 57 |
} |
| 58 |
|