razonyang/yii-translator-middleware

Yii translator middleware

0.1.1 2022-09-10 14:14 UTC

This package is auto-updated.

Last update: 2024-12-11 12:44:48 UTC


README

Latest Stable Version Total Downloads Build Status Scrutinizer Code Quality Code Coverage

A HTTP middleware for Yii Translator.

How it works?

  1. The TranslatorMiddleware parse the locale from incoming request and store the translator instance into request.
  2. The subsequent middlewares and handlers can retrieves the translator instance by TranslatorMiddleware::getTranslator or TranslatorMiddleware::getTranslatorByAttributes static methods.

Installation

The package could be installed with composer:

composer require razonyang/yii-translator-middleware --prefer-dist

Configurations

<?php

declare(strict_types=1);

use RazonYang\Yii\TranslatorMiddleware\LocaleParser\CompositeParser;
use RazonYang\Yii\TranslatorMiddleware\LocaleParser\HeaderParser;
use RazonYang\Yii\TranslatorMiddleware\LocaleParser\QueryParamsParser;
use RazonYang\Yii\TranslatorMiddleware\LocaleParserInterface;
use RazonYang\Yii\TranslatorMiddleware\TranslatorMiddleware;
use Yiisoft\Definitions\Reference;
use Yiisoft\Translator\TranslatorInterface;

return [
    TranslatorMiddleware::class => [
        'class' => TranslatorMiddleware::class,
        '__construct()' => [
            Reference::to(LocaleParserInterface::class),
            Reference::to(TranslatorInterface::class),
        ],
    ],

    LocaleParserInterface::class => CompositeParser::class,
    CompositeParser::class => [
        'class' => CompositeParser::class,
        '__construct()' => [
            Reference::to(QueryParamsParser::class),
            Reference::to(HeaderParser::class),
        ],
    ],
    QueryParamsParser::class => [
        'class' => QueryParamsParser::class,
        '__construct()' => [
            'lang',
        ],
    ],
];

Locale Parsers

  • CompositeParser: parse locale from multiple parsers, returns immediately if success.
  • HeaderParser: parse locale from the Accept-Language header.
  • QueryParamsParser: parse locale from the specified query parameter, default to lang.