Skip to content

Commit

Permalink
Automatically register Currency DBAL type
Browse files Browse the repository at this point in the history
  • Loading branch information
benr77 committed Aug 13, 2022
1 parent 59ff565 commit b0cb373
Showing 1 changed file with 45 additions and 28 deletions.
73 changes: 45 additions & 28 deletions src/HeadsnetMoneyBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/*
* This file is part of the Symfony HeadsnetMoneyBundle.
*
* (c) Headstrong Internet Services Ltd 2021
* (c) Headstrong Internet Services Ltd 2022
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
Expand All @@ -11,38 +11,55 @@
namespace Headsnet\MoneyBundle;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use Doctrine\DBAL\Types\Type;
use Doctrine\Persistence\ManagerRegistry;
use Headsnet\MoneyBundle\Doctrine\DBAL\Types\CurrencyType;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
* Bundle configuration
*/
class HeadsnetMoneyBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);

$this->addDoctrineMapping($container);
}

public function boot(): void
{
$this->addCurrencyColumnType();
}

private function addDoctrineMapping(ContainerBuilder $container): void
{
$modelDir = realpath(__DIR__ . '/Doctrine/Mapping');
$mappings = [
$modelDir => 'Money',
];

if (class_exists(DoctrineOrmMappingsPass::class)) {
$container->addCompilerPass(
DoctrineOrmMappingsPass::createXmlMappingDriver(
$mappings,
['doctrine.orm.entity_manager'],
false
)
);
}
}

private function addCurrencyColumnType(): void
{
if (!Type::hasType('currency')) {
Type::addType('currency', CurrencyType::class);
}

/**
* Here we add a compiler pass to add a Doctrine Mapping for the Money embeddable model
*
* @param ContainerBuilder $container
*/
public function build(ContainerBuilder $container)
{
parent::build($container);

$modelDir = realpath(__DIR__.'/Doctrine/Mapping');
$mappings = [
$modelDir => 'Money',
];

if (class_exists(DoctrineOrmMappingsPass::class))
{
$container->addCompilerPass(
DoctrineOrmMappingsPass::createXmlMappingDriver(
$mappings,
['doctrine.orm.entity_manager'],
false
));
}
}
/** @var ManagerRegistry $registry */
$registry = $this->container->get('doctrine');

foreach ($registry->getConnections() as $connection) {
$connection->getDatabasePlatform()->registerDoctrineTypeMapping('currency', 'currency');
}
}
}

0 comments on commit b0cb373

Please sign in to comment.