Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
897 views
in Technique[技术] by (71.8m points)

annotations - Using array in the columnDefinition for ENUM in Symfony

When I use the columnDefinition in Symfony to define an ENUM column I need to write the possible values as pain text:

columnDefinition="ENUM('red', 'blue', 'green')"

Because this can cause errors in later stages I want to be able to put an array there:

columnDefinition="ENUM(static::COLORS)"

How can I solve this?

question from:https://stackoverflow.com/questions/65829909/using-array-in-the-columndefinition-for-enum-in-symfony

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a Enum as a type and use it

<?php
namespace AppDBAL;



use DoctrineDBALTypesType;
use DoctrineDBALPlatformsAbstractPlatform;

class EnumColorsType extends Type
{

    const ENUM_COLORS = 'enum_colors';
    const COLOR_RED = 'red';
    const COLOR_BLUE = 'blue';
    const COLOR_GREEN= 'green';

    publkic static $AVAILBLE_COLORS = ['blue','red','green']; 

    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {

        return sprintf("ENUM(%s)",implode(',', static::$AVAILBLE_COLORS));
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return $value;
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if (!in_array($value, static::$AVAILBLE_COLORS)) {
            throw new InvalidArgumentException("Invalid Colors");
        }
        return $value;
    }

    public function getName()
    {
        return self::ENUM_COLORS;
    }


    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
}

Then use it

<?php
...
/** 
 * @ORMEntity
 */
class YourEntity
{
    /** 
     * @Column(type="enum_colors") 
     */
    private $color;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...