File: /var/www/vhosts/creativefellows.nl/fvr.creativefellows.nl/src/Middleware/LanguageMiddleware.php
<?php
namespace App\Middleware;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;
use Slim\Exception\HttpNotFoundException;
use App\Domain\Language\LanguageData;
final class LanguageMiddleware implements MiddlewareInterface
{
protected $settings;
public function __construct(
ContainerInterface $container,
ResponseFactoryInterface $responseFactory,
LanguageData $language
){
$this->container = $container;
$this->responseFactory = $responseFactory;
$this->language = $language;
}
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
) : ResponseInterface {
// Set localization
$this->localization = $this->container->get('settings')['localization'];
$uri = $request->getUri();
$path = $uri->getPath();
//Split path into chunks
$pathChunks = explode("/", $path);
if ( count($pathChunks) > 1 && in_array($pathChunks[1], $this->localization['available_languages']) ) {
// override default settings with language variables
$this->language->setLanguage($pathChunks[1]);
//Produce new URI without language reference
unset($pathChunks[1]);
$newPath = implode('/', $pathChunks);
$newUri = $uri->withPath($newPath);
return $handler->handle($request->withUri($newUri));
}
return $handler->handle($request);
}
}