RateRegistry.php 2.08 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Tax\Model\Calculation;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Tax\Model\Calculation\Rate as TaxRateModel;
use Magento\Tax\Model\Calculation\RateFactory as TaxRateModelFactory;

class RateRegistry
{
    /**
     * Tax rate model factory
     *
     * @var  TaxRateModelFactory
     */
    private $taxRateModelFactory;

    /**
     * Tax rate models
     *
     * @var TaxRateModel[]
     */
    private $taxRateRegistryById = [];

    /**
     * Constructor
     *
     * @param TaxRateModelFactory $taxModelRateFactory
     */
    public function __construct(
        TaxRateModelFactory $taxModelRateFactory
    ) {
        $this->taxRateModelFactory = $taxModelRateFactory;
    }

    /**
     * Register TaxRate Model to registry
     *
     * @param TaxRateModel $taxRateModel
     * @return void
     */
    public function registerTaxRate(TaxRateModel $taxRateModel)
    {
        $this->taxRateRegistryById[$taxRateModel->getId()] = $taxRateModel;
    }

    /**
     * Retrieve TaxRate Model from registry given an id
     *
     * @param int $taxRateId
     * @return TaxRateModel
     * @throws NoSuchEntityException
     */
    public function retrieveTaxRate($taxRateId)
    {
        if (isset($this->taxRateRegistryById[$taxRateId])) {
            return $this->taxRateRegistryById[$taxRateId];
        }
        /** @var TaxRateModel $taxRateModel */
        $taxRateModel = $this->taxRateModelFactory->create()->load($taxRateId);
        if (!$taxRateModel->getId()) {
            // tax rate does not exist
            throw NoSuchEntityException::singleField('taxRateId', $taxRateId);
        }
        $this->taxRateRegistryById[$taxRateModel->getId()] = $taxRateModel;
        return $taxRateModel;
    }

    /**
     * Remove an instance of the TaxRate Model from the registry
     *
     * @param int $taxRateId
     * @return void
     */
    public function removeTaxRate($taxRateId)
    {
        unset($this->taxRateRegistryById[$taxRateId]);
    }
}