amberovsky/currency-doctrine

Allow the use of amberovsky/currency as a Doctrine field type.

v0.3 2020-07-20 08:19 UTC

This package is auto-updated.

Last update: 2024-04-20 16:42:13 UTC


README

The amberovsky/currency-doctrine package provides the ability to use amberovsky/currency as a Doctrine field type.

Examples

Configuration

It requires CurrencyFactory to be injected in via CurrencyType::setCurrencyFactory method. Use your current DI mechanism to do that.

To configure Doctrine to use amberovsky/currency as a field type, you'll need to set up the following in your bootstrap:

use Doctrine\DBAL\Types\Type;
use Amberovsky\Money\Currency\Doctrine\CurrencyType;
use Amberovsky\Money\Currency\CurrencyFactory;

$currencyFactory = ...; // Get CurrencyFactory instance somehow

if (!Type::hasType(CurrencyType::NAME)) {
    Type::addType(CurrencyType::NAME, CurrencyType::class);
    /** @var CurrencyType $currencyType */
    $currencyType = Type::getType(CurrencyType::NAME);
    $currencyType->setCurrencyFactory($currencyFactory);
}

Symfony

Add this to your Kernel.php:

    /**
     * @inheritDoc
     */
    protected function initializeContainer() {
        parent::initializeContainer();

        if (!Type::hasType(CurrencyType::NAME)) {
            Type::addType(CurrencyType::NAME, CurrencyType::class);
            /** @var CurrencyType $currencyType */
            $currencyType = Type::getType(CurrencyType::NAME);
            $currencyType->setCurrencyFactory($this->container->get(CurrencyFactory::class));
        }
    }

Usage

Then, in your models, you may annotate properties by setting the @Column type to Currency. Doctrine will handle the rest.

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="invoices")
 */
class Invoice
{
    /**
     * @ORM\Column(type="Currency")
     */
    private Currency $currency;

    public function getCurrency(): Currency {
        return $this->currency;
    }
}

How to contribute

Please fork this repo and create a PR. Make sure you run tests before submitting yout PR:

make phpstan
make psalm
make phpspec

License

Copyright (C) 2020 Anton Zagorskii, BSD-3-Clause license, See license file for details