arodygin / php-dictionary

此包已被弃用且不再维护。作者建议使用 webinarium/php-dictionary 包代替。

PHP 的静态词典实现

1.2.1 2021-07-03 11:25 UTC

This package is auto-updated.

Last update: 2021-07-03 11:31:18 UTC


README

PHP Latest Stable Version Build Status Code Coverage Scrutinizer Code Quality

PHP 的静态词典实现

需求

PHP 需要至少是 PHP 7.4 版本。

安装

推荐的安装方式是通过 Composer

composer require webinarium/php-dictionary

使用

要创建自定义词典,您需要扩展 StaticDictionary 类并重写静态数组 $dictionary。之后,您可以使用 StaticDictionaryInterface 来处理您的词典。

示例词典

namespace Dictionary;

class Color extends StaticDictionary
{
    public const BLACK   = 'Black';
    public const BLUE    = 'Blue';
    public const GREEN   = 'Green';
    public const CYAN    = 'Cyan';
    public const RED     = 'Red';
    public const MAGENTA = 'Magenta';
    public const YELLOW  = 'Yellow';
    public const WHITE   = 'White';

    protected static array $dictionary = [
        self::BLACK   => '#000000',
        self::BLUE    => '#0000FF',
        self::GREEN   => '#00FF00',
        self::CYAN    => '#00FFFF',
        self::RED     => '#FF0000',
        self::MAGENTA => '#FF00FF',
        self::YELLOW  => '#FFFF00',
        self::WHITE   => '#FFFFFF',
    ];
}

输入清理

public function setColor($color)
{
    if (Dictionary\Color::has($color)) {
        $this->color = $color;
    }
}

Symfony 验证

use Symfony\Component\Validator\Constraints;

class Settings
{
    /**
     * @Constraints\NotNull()
     * @Constraints\Choice(callback = {"Dictionary\Color", "keys"})
     */
    public $color;
}

Symfony 表单

class ColorType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('color', ChoiceType::class, [
            'label'   => 'color',
            'choices' => array_flip(Dictionary\Color::all()),
        ]);
    }
}

请注意,如果您尝试使用不存在的键从您的词典中获取值,您将得到 NULL 而没有任何失败或警告。有时,返回默认回退值而不是 NULL 是有用的。您可以在词典类中定义一个 FALLBACK 常量来实现这一点。

class Shell extends StaticDictionary
{
    public const FALLBACK = self::UNITY;

    public const XFCE  = 1;
    public const KDE   = 2;
    public const GNOME = 3;
    public const LXDE  = 4;
    public const UNITY = 5;
    public const MATE  = 6;

    protected static array $dictionary = [
        self::UNITY => 'Unity',
        self::GNOME => 'Gnome',
        self::KDE   => 'KDE',
        self::LXDE  => 'LXDE',
        self::XFCE  => 'Xfce',
        self::MATE  => 'MATE',
    ];
}

// This returns 'Gnome'
Shell::get(Shell::GNOME);

// This returns 'Unity'
Shell::get(Color::BLACK);

如果您的词典应在运行时构建,则可以跳过静态数组 $dictionary,并改用重载静态函数 dictionary()

class Timezone extends StaticDictionary
{
    const FALLBACK = 'UTC';

    protected static function dictionary(): array
    {
        return timezone_identifiers_list();
    }
}

开发

./bin/php-cs-fixer fix
XDEBUG_MODE=coverage ./bin/phpunit --coverage-text