<?php
/**
 * AbstractEnumType
 * 
 * @author Elze Kool <info@visualmedia.nl>
 */
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 Elze Kool <info@visualmedia.nl>
 */
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;
    }

}
