Skip to content

Instantly share code, notes, and snippets.

@remmel
Last active August 19, 2016 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remmel/e43bfcc8e1202dc84164f5a36e5568b5 to your computer and use it in GitHub Desktop.
Save remmel/e43bfcc8e1202dc84164f5a36e5568b5 to your computer and use it in GitHub Desktop.
Add YAML type in Doctrine (with Symfony)
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');
}
}
<?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 <remy.mellet@gmail.com>
*/
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