webinarium/php-dictionary

PHP的静态字典实现

1.2.1 2021-07-03 11:25 UTC

This package is auto-updated.

Last update: 2024-08-29 04:03:37 UTC


README

PHP Latest Stable Version Build Status Code Coverage Scrutinizer Code Quality

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