CustomerRepositoryPlugin.php 10.7 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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
<?php
/**
 * @copyright  Vertex. All rights reserved.  https://www.vertexinc.com/
 * @author     Mediotype                     https://www.mediotype.com/
 */

namespace Vertex\Tax\Model\Plugin;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerExtensionInterface;
use Magento\Customer\Api\Data\CustomerExtensionInterfaceFactory;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Api\Data\CustomerSearchResultsInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Vertex\Tax\Model\Config;
use Vertex\Tax\Model\Data\CustomerCode;
use Vertex\Tax\Model\Data\CustomerCodeFactory;
use Vertex\Tax\Model\ExceptionLogger;
use Vertex\Tax\Model\Repository\CustomerCodeRepository;

/**
 * Adds CustomerCode extension attribute to Customer Repository
 *
 * @see CustomerRepositoryInterface
 */
class CustomerRepositoryPlugin
{
    /** @var CustomerCodeFactory */
    private $codeFactory;

    /** @var Config */
    private $config;

    /** @var CustomerExtensionInterfaceFactory */
    private $extensionFactory;

    /** @var CustomerCodeRepository */
    private $repository;

    /** @var ExceptionLogger */
    private $logger;

    /** @var bool[] */
    private $currentlySaving = [];

    /**
     * @param CustomerCodeRepository $repository
     * @param CustomerExtensionInterfaceFactory $extensionFactory
     * @param CustomerCodeFactory $codeFactory
     * @param ExceptionLogger $logger
     * @param Config $config
     */
    public function __construct(
        CustomerCodeRepository $repository,
        CustomerExtensionInterfaceFactory $extensionFactory,
        CustomerCodeFactory $codeFactory,
        ExceptionLogger $logger,
        Config $config
    ) {
        $this->repository = $repository;
        $this->extensionFactory = $extensionFactory;
        $this->codeFactory = $codeFactory;
        $this->logger = $logger;
        $this->config = $config;
    }

    /**
     * Add the Vertex Customer Code to the Customer extension attribute when customers are retrieved from the repository
     *
     * @param CustomerRepositoryInterface $subject
     * @param CustomerSearchResultsInterface $results
     * @see CustomerRepositoryInterface::getList()
     * @return CustomerSearchResultsInterface
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGetList(CustomerRepositoryInterface $subject, $results)
    {
        if (!$this->config->isVertexActive() || $results->getTotalCount() <= 0) {
            return $results;
        }

        $customerIds = array_map(
            function (CustomerInterface $customer) {
                return $customer->getId();
            },
            $results->getItems()
        );

        $customerCodes = $this->repository->getListByCustomerIds($customerIds);

        foreach ($results->getItems() as $customer) {
            if (!isset($customerCodes[$customer->getId()])) {
                continue;
            }

            $extensionAttributes = $this->getExtensionAttributes($customer);
            $extensionAttributes->setVertexCustomerCode($customerCodes[$customer->getId()]->getCustomerCode());
        }

        return $results;
    }

    /**
     * Add the Vertex Customer Code to the Customer extension attribute when a customer is retrieved from the repository
     *
     * @see CustomerRepositoryInterface::getById()
     *
     * @param CustomerRepositoryInterface $subject
     * @param CustomerInterface $result
     * @return CustomerInterface
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGetById(CustomerRepositoryInterface $subject, CustomerInterface $result)
    {
        if (!$this->config->isVertexActive($result->getStoreId()) || $this->isCurrentlySaving($result)) {
            return $result;
        }

        $extensionAttributes = $this->getExtensionAttributes($result);

        try {
            $customerCode = $this->repository->getByCustomerId($result->getId());
            $extensionAttributes->setVertexCustomerCode($customerCode->getCustomerCode());
        } catch (NoSuchEntityException $exception) {
            $extensionAttributes->setVertexCustomerCode(null);
        } catch (\Exception $exception) {
            $this->logger->critical($exception);
        }

        return $result;
    }

    /**
     * Add the Vertex Customer Code to the Customer extension attribute when a customer is retrieved from the repository
     *
     * @see CustomerRepositoryInterface::get()
     *
     * @param CustomerRepositoryInterface $subject
     * @param CustomerInterface $result
     * @return CustomerInterface
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGet(CustomerRepositoryInterface $subject, CustomerInterface $result)
    {
        return $this->afterGetById($subject, $result);
    }

    /**
     * Save the Vertex Customer Code when the Customer is saved
     *
     * @see CustomerRepositoryInterface::save()
     * @todo Convert to afterSave once we only support Magento 2.2+
     *
     * @param CustomerRepositoryInterface $subject
     * @param callable $proceed {@see CustomerRepositoryInterface::save()}
     * @param CustomerInterface $customer
     * @param string|null $passwordHash
     * @return CustomerInterface
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function aroundSave(
        CustomerRepositoryInterface $subject,
        callable $proceed,
        CustomerInterface $customer,
        $passwordHash = null
    ) {
        if (!$this->config->isVertexActive($customer->getStoreId())) {
            return $proceed($customer, $passwordHash);
        }
        $this->setCurrentlySaving($customer);
        if ($customer->getExtensionAttributes()) {
            $customerCode = $customer->getExtensionAttributes()->getVertexCustomerCode();
            /** @var CustomerInterface $result */
            $result = $proceed($customer, $passwordHash);

            if ($customerCode) {
                $codeModel = $this->getCodeModel($result->getId());
                $codeModel->setCustomerCode($customerCode);
                try {
                    $this->repository->save($codeModel);
                } catch (\Exception $e) {
                    $this->logger->critical($e);
                }
            } else {
                $this->deleteByCustomerId($result->getId());
            }
            $extensionAttributes = $this->getExtensionAttributes($result);
            $extensionAttributes->setVertexCustomerCode($customerCode);
        } else {
            $result = $proceed($customer, $passwordHash);
        }
        $this->unsetCurrentlySaving($result);
        return $result;
    }

    /**
     * Delete the Vertex Customer Code when the customer is deleted
     *
     * @see CustomerRepositoryInterface::delete()
     * @todo Convert to afterDelete once we only support Magento 2.2+
     *
     * @param CustomerRepositoryInterface $subject
     * @param callable $proceed {@see CustomerRepositoryInterface::delete()}
     * @param CustomerInterface $customer
     * @return bool
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function aroundDelete(CustomerRepositoryInterface $subject, callable $proceed, CustomerInterface $customer)
    {
        $customerId = $customer->getId();
        $result = $proceed($customer);

        if (!$this->config->isVertexActive() && $result) {
            $this->deleteByCustomerId($customerId);
        }

        return $result;
    }

    /**
     * Delete the Vertex Customer code when the customer is deleted
     *
     * @see CustomerRepositoryInterface::deleteById()
     * @todo Convert to afterDeleteById once we only support Magento 2.2+
     *
     * @param CustomerRepositoryInterface $subject
     * @param callable $proceed {@see CustomerRepositoryInterface::deleteById()}
     * @param int $customerId
     * @return bool
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function aroundDeleteById(CustomerRepositoryInterface $subject, callable $proceed, $customerId)
    {
        $result = $proceed($customerId);

        if (!$this->config->isVertexActive() && $result) {
            $this->deleteByCustomerId($customerId);
        }

        return $result;
    }

    /**
     * Retrieve the Customer Code by Customer ID
     *
     * @param int $customerId
     * @return \Vertex\Tax\Model\Data\CustomerCode
     */
    private function getCodeModel($customerId)
    {
        try {
            $customerCode = $this->repository->getByCustomerId($customerId);
        } catch (NoSuchEntityException $e) {
            /** @var CustomerCode $customerCode */
            $customerCode = $this->codeFactory->create();
            $customerCode->setCustomerId($customerId);
        }
        return $customerCode;
    }

    /**
     * Delete a Customer Code given a Customer ID
     *
     * @param int $customerId
     * @return void
     */
    private function deleteByCustomerId($customerId)
    {
        try {
            $this->repository->deleteByCustomerId($customerId);
        } catch (\Exception $exception) {
            $this->logger->critical($exception);
        }
    }

    /**
     * Get a CustomerExtensionInterface object, creating it if it is not yet created
     *
     * @param CustomerInterface $customer
     * @return CustomerExtensionInterface
     */
    private function getExtensionAttributes(CustomerInterface $customer)
    {
        $extensionAttributes = $customer->getExtensionAttributes();
        if (!$extensionAttributes) {
            $extensionAttributes = $this->extensionFactory->create();
            $customer->setExtensionAttributes($extensionAttributes);
        }

        return $extensionAttributes;
    }

    /**
     * Set whether or not we are currently saving a specific customer
     *
     * This is used to prevent loading the attribute during a save procedure
     *
     * @param CustomerInterface $customer
     * @return void
     */
    private function setCurrentlySaving(CustomerInterface $customer)
    {
        if ($customer->getId()) {
            $this->currentlySaving[$customer->getId()] = true;
        }
    }

    /**
     * Determine whether or not we are currently saving a specific customer
     *
     * This is used to prevent loading the attribute during a save procedure
     *
     * @param CustomerInterface $customer
     * @return bool
     */
    private function isCurrentlySaving(CustomerInterface $customer)
    {
        return isset($this->currentlySaving[$customer->getId()]);
    }

    /**
     * Declare that we are no longer currently saving a specific customer
     *
     * @param CustomerInterface $customer
     * @return void
     */
    private function unsetCurrentlySaving(CustomerInterface $customer)
    {
        unset($this->currentlySaving[$customer->getId()]);
    }
}