Last active
August 19, 2016 16:14
-
-
Save remmel/e43bfcc8e1202dc84164f5a36e5568b5 to your computer and use it in GitHub Desktop.
Add YAML type in Doctrine (with Symfony)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace AppBundle; | |
use Doctrine\DBAL\Types\Type; | |
use Symfony\Component\HttpKernel\Bundle\Bundle; | |
class AppBundle extends Bundle | |
{ | |
public function boot() { | |
Type::addType('yaml', 'AppBundle\Extension\YamlType'); | |
$em = $this->container->get('doctrine.orm.default_entity_manager'); | |
$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('YAML', 'yaml'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace AppBundle\Extension; | |
use Doctrine\DBAL\Platforms\AbstractPlatform; | |
use Doctrine\DBAL\Types\Type; | |
use Symfony\Component\Yaml\Parser; | |
use Symfony\Component\Yaml\Yaml; | |
/** | |
* Type that maps a PHP array to a clob SQL type using the YML representation. | |
* | |
* @author Remy Mellet <[email protected]> | |
*/ | |
class YamlType extends Type | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) | |
{ | |
return $platform->getClobTypeDeclarationSQL($fieldDeclaration); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function convertToDatabaseValue($value, AbstractPlatform $platform) | |
{ | |
if (null === $value) { | |
return null; | |
} | |
return Yaml::dump($value); //object to yml as string | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function convertToPHPValue($value, AbstractPlatform $platform) | |
{ | |
if ($value === null || $value === '') { | |
return array(); | |
} | |
return Yaml::parse($value); //yml as string to object | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getName() | |
{ | |
return "yaml"; //Type::YAML; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function requiresSQLCommentHint(AbstractPlatform $platform) | |
{ | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment