<?php
/**
 * AbstractEnumType
 * 
 * @author Visual Media 
 */
namespace VisualM\TagManagerBundle\Doctrine\FieldType;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

/**
 * AbstractEnumType
 * 
 * Base class that can be used to create ENUM fields with Doctrine
 * 
 * @author Visual Media 
 */
abstract class AbstractEnumType extends Type
{
    /**
     * Get available ENUM options
     * 
     * @return array Enum options
     */
    abstract protected function getEnumOptions();
    
    /**
     * {@inheritDoc}
     */
    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $options = $this->getEnumOptions();
        foreach($options as &$option) {
            $option = "'" . $option . "'";
        }
        $name = $this->getName();
        $def = 'ENUM(' . join(',', $options) . ') COMMENT \'(DC2Type:' . $name . ')\'';
        return $def;
    }

    /**
     * {@inheritDoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return $value;
    }

    /**
     * {@inheritDoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value === null OR $value === "") {
            return null;
        }
        
        if (!in_array($value, $this->getEnumOptions())) {
            throw new \InvalidArgumentException(sprintf(
                'Value "%s" not allowed for %s field',
                $value,
                get_class($this)
            ));
        }
        return $value;
    }

}
