mhujer/consistence-bundle

为 consistence/consistence 添加翻译器和枚举表单元素

安装次数: 18,689

依赖项: 0

建议者: 0

安全: 0

星标: 1

关注者: 2

分支: 1

开放问题: 0

类型:symfony-bundle

2.0.1 2023-12-09 15:22 UTC

This package is auto-updated.

Last update: 2024-09-09 16:47:35 UTC


README

Build Status Latest Stable Version Total Downloads License Coverage Status

此Bundle提供consistence/consistence枚举的翻译服务、翻译器Twig过滤器以及表单类型。

安装

使用Symfony Flex的应用程序

打开命令行控制台,进入您的项目目录并执行以下命令

$ composer require mhujer/consistence-bundle

不使用Symfony Flex的应用程序

步骤1:下载Bundle

打开命令行控制台,进入您的项目目录并执行以下命令以下载此bundle的最新稳定版本

$ composer require mhujer/consistence-bundle

此命令需要您全局安装Composer,请参阅Composer文档中的安装章节

步骤2:启用Bundle

然后,通过将其添加到项目config/bundles.php文件中注册的Bundle列表中来启用该bundle。

// config/bundles.php

return [
    // ...
    Mhujer\ConsistenceBundle\MhujerConsistenceBundle::class => ['all' => true],
];

用法

示例考虑以下枚举

<?php declare(strict_types = 1);

namespace App\Card;

final class CardColor extends \Consistence\Enum\Enum
{

    public const BLACK = 'black';
    public const RED = 'red';

}

翻译文件

翻译器自动将枚举实例转换为包含枚举FQCN、冒号及其值的翻译键,例如。

App\Card\CardColor:red

最佳做法是创建一个PHP格式的翻译文件(enums.en.php),允许您使用类名。

<?php declare(strict_types = 1);

use App\Card\CardColor;

return [
    CardColor::class . ':' . CardColor::RED => 'red',
    CardColor::class . ':' . CardColor::BLACK => 'black',
];

如您所注意到的,翻译域设置为enums

Twig

在Twig模板中,您可以使用transEnum过滤器将枚举转换为翻译字符串。

{{ variableContainingEnum | transEnum }}

翻译域

有时为同一枚举提供不同的翻译很有用(例如,当枚举用于管理界面和前端UI时)。这是通过传递给transEnumtranslationDomain参数实现的。

{{ variableContainingEnum | transEnum('enums-frontend') }}

它通过使用Symfony翻译器透明地加载来自另一个域的翻译。

// enums-frontend.en.php
<?php declare(strict_types = 1);

use App\Card\CardColor;

return [
    CardColor::class . ':' . CardColor::RED => 'Red',
    CardColor::class . ':' . CardColor::BLACK => 'Black',
];

表单

在表单中,您可以使用EnumType作为字段类型。您需要设置一个选项enum_class到一个枚举类

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('cardColor', EnumType::class, [
            'enum_class' => CardColor::class,
            'label' => 'Card Color',
        ])
    //...

您的请求对象中的属性应如下所示(它包含一个CardColor实例)

/**
 * @Assert\NotBlank()
 * @var \App\Card\CardColor
 */
public $cardColor;

要求

支持PHP 7.4或更高版本和Symfony 5.4或更高版本。

提交错误和功能请求

错误和功能请求在GitHub上跟踪

作者

Martin Hujer

变更日志

2.0.1 (2023-12-09)

  • 添加Symfony 7和PHP 8.2支持(dfridrich)

2.0.0 (2022-09-20)

  • 要求PHP 8.1
  • 添加对原生枚举的支持以简化迁移

1.4.0 (2021-12-04)

  • 要求Symfony 5.4+
  • 允许PHP 8.1
  • 允许Symfony 6.0

1.3.0 (2021-06-10)

  • BC中断:在transEnum中将可选参数视为翻译域

1.2.0 (2021-06-03)

  • transEnum方法添加可选参数$enumNamespace

1.1.0 (2021-02-28)

  • 允许PHP 8.0
  • 要求PHP 7.4+

1.0.2 (2020-01-13)

  • 修复#3:在services.yaml中未定义"translator"依赖

1.0.1 (2019-11-24)

  • Symfony 5和Twig 3兼容性

1.0.0 (2019-11-06)

  • 首次发布