|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Lamoda\EnumBundle\DBAL; |
| 4 | + |
| 5 | +use Doctrine\DBAL\Platforms\AbstractPlatform; |
| 6 | +use Doctrine\DBAL\Types\ConversionException; |
| 7 | +use Doctrine\DBAL\Types\Type; |
| 8 | +use Lamoda\EnumBundle\Naming\IdenticalNamingStrategy; |
| 9 | +use Lamoda\EnumBundle\Naming\NamingStrategyInterface; |
| 10 | +use Paillechat\Enum\Enum; |
| 11 | +use Paillechat\Enum\Exception\EnumException; |
| 12 | + |
| 13 | +final class EnumType extends Type |
| 14 | +{ |
| 15 | + /** @var string */ |
| 16 | + private $fqcn; |
| 17 | + /** @var string */ |
| 18 | + private $name; |
| 19 | + /** @var NamingStrategyInterface */ |
| 20 | + private $strategy; |
| 21 | + |
| 22 | + public function setName(string $name): void |
| 23 | + { |
| 24 | + $this->name = $name; |
| 25 | + } |
| 26 | + |
| 27 | + public function setFqcn(string $fqcn): void |
| 28 | + { |
| 29 | + $this->fqcn = $fqcn; |
| 30 | + } |
| 31 | + |
| 32 | + public function setStrategy(NamingStrategyInterface $strategy): void |
| 33 | + { |
| 34 | + $this->strategy = $strategy; |
| 35 | + } |
| 36 | + |
| 37 | + private function getStrategy(): NamingStrategyInterface |
| 38 | + { |
| 39 | + if (!$this->strategy) { |
| 40 | + $this->strategy = new IdenticalNamingStrategy(); |
| 41 | + } |
| 42 | + |
| 43 | + return $this->strategy; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * {@inheritdoc} |
| 48 | + */ |
| 49 | + public function convertToPHPValue($value, AbstractPlatform $platform) |
| 50 | + { |
| 51 | + /** @var Enum $fqcn */ |
| 52 | + $fqcn = $this->fqcn; |
| 53 | + |
| 54 | + try { |
| 55 | + return $fqcn::createByName($this->getStrategy()->toEnumName($value)); |
| 56 | + } catch (EnumException $e) { |
| 57 | + throw ConversionException::conversionFailed($value, $this->getName()); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * {@inheritdoc} |
| 63 | + */ |
| 64 | + public function convertToDatabaseValue($value, AbstractPlatform $platform) |
| 65 | + { |
| 66 | + if (!is_a($value, $this->fqcn)) { |
| 67 | + throw ConversionException::conversionFailed($value, $this->getName()); |
| 68 | + } |
| 69 | + |
| 70 | + return $this->getStrategy()->fromEnumName((string) $value); |
| 71 | + } |
| 72 | + |
| 73 | + /** {@inheritdoc} */ |
| 74 | + public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) |
| 75 | + { |
| 76 | + return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); |
| 77 | + } |
| 78 | + |
| 79 | + /** {@inheritdoc} */ |
| 80 | + public function getName(): string |
| 81 | + { |
| 82 | + return $this->name; |
| 83 | + } |
| 84 | +} |
0 commit comments