Config.php 5.99 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
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

declare(strict_types=1);

namespace Magento\WebapiAsync\Model;

use Magento\Webapi\Model\Cache\Type\Webapi as WebapiCache;
use Magento\Webapi\Model\Config as WebapiConfig;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Webapi\Model\Config\Converter;

/**
 * Class for accessing to Webapi_Async configuration.
 */
class Config implements \Magento\AsynchronousOperations\Model\ConfigInterface
{
    /**
     * @var \Magento\Webapi\Model\Cache\Type\Webapi
     */
    private $cache;

    /**
     * @var \Magento\Webapi\Model\Config
     */
    private $webApiConfig;

    /**
     * @var \Magento\Framework\Serialize\SerializerInterface
     */
    private $serializer;

    /**
     * @var array
     */
    private $asyncServices;

    /**
     * Initialize dependencies.
     *
     * @param \Magento\Webapi\Model\Cache\Type\Webapi $cache
     * @param \Magento\Webapi\Model\Config $webApiConfig
     * @param \Magento\Framework\Serialize\SerializerInterface|null $serializer
     */
    public function __construct(
        WebapiCache $cache,
        WebapiConfig $webApiConfig,
        SerializerInterface $serializer = null
    ) {
        $this->cache = $cache;
        $this->webApiConfig = $webApiConfig;
        $this->serializer = $serializer ? : ObjectManager::getInstance()->get(SerializerInterface::class);
    }

    /**
     * @inheritdoc
     */
    public function getServices()
    {
        if (null === $this->asyncServices) {
            $services = $this->cache->load(self::CACHE_ID);
            if ($services && is_string($services)) {
                $this->asyncServices = $this->serializer->unserialize($services);
            } else {
                $this->asyncServices = $this->generateTopicsDataFromWebapiConfig();
                $this->cache->save($this->serializer->serialize($this->asyncServices), self::CACHE_ID);
            }
        }

        return $this->asyncServices;
    }

    /**
     * @inheritdoc
     */
    public function getTopicName($routeUrl, $httpMethod)
    {
        $services = $this->getServices();
        $lookupKey = $this->generateLookupKeyByRouteData(
            $routeUrl,
            $httpMethod
        );

        if (array_key_exists($lookupKey, $services) === false) {
            throw new LocalizedException(
                __('WebapiAsync config for "%lookupKey" does not exist.', ['lookupKey' => $lookupKey])
            );
        }

        return $services[$lookupKey][self::SERVICE_PARAM_KEY_TOPIC];
    }

    /**
     * Generate topic data for all defined services
     *
     * Topic data is indexed by a lookup key that is derived from route data
     *
     * @return array
     */
    private function generateTopicsDataFromWebapiConfig()
    {
        $webApiConfig = $this->webApiConfig->getServices();
        $services = [];
        foreach ($webApiConfig[Converter::KEY_ROUTES] as $routeUrl => $routeData) {
            foreach ($routeData as $httpMethod => $httpMethodData) {
                if ($httpMethod !== \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET) {
                    $serviceInterface = $httpMethodData[Converter::KEY_SERVICE][Converter::KEY_SERVICE_CLASS];
                    $serviceMethod = $httpMethodData[Converter::KEY_SERVICE][Converter::KEY_SERVICE_METHOD];

                    $lookupKey = $this->generateLookupKeyByRouteData(
                        $routeUrl,
                        $httpMethod
                    );

                    $topicName = $this->generateTopicNameFromService(
                        $serviceInterface,
                        $serviceMethod,
                        $httpMethod
                    );

                    $services[$lookupKey] = [
                        self::SERVICE_PARAM_KEY_INTERFACE => $serviceInterface,
                        self::SERVICE_PARAM_KEY_METHOD    => $serviceMethod,
                        self::SERVICE_PARAM_KEY_TOPIC     => $topicName,
                    ];
                }
            }
        }

        return $services;
    }

    /**
     * Generate lookup key name based on route and method
     *
     * Perform the following conversion:
     * self::TOPIC_PREFIX + /V1/products + POST => async.V1.products.POST
     *
     * @param string $routeUrl
     * @param string $httpMethod
     * @return string
     */
    private function generateLookupKeyByRouteData($routeUrl, $httpMethod)
    {
        return self::TOPIC_PREFIX . $this->generateKey($routeUrl, $httpMethod, '/', false);
    }

    /**
     * Generate topic name based on service type and method name.
     *
     * Perform the following conversion:
     * self::TOPIC_PREFIX + Magento\Catalog\Api\ProductRepositoryInterface + save + POST
     *   => async.magento.catalog.api.productrepositoryinterface.save.POST
     *
     * @param string $serviceInterface
     * @param string $serviceMethod
     * @param string $httpMethod
     * @return string
     */
    private function generateTopicNameFromService($serviceInterface, $serviceMethod, $httpMethod)
    {
        $typeName = strtolower(sprintf('%s.%s', $serviceInterface, $serviceMethod));
        return strtolower(self::TOPIC_PREFIX . $this->generateKey($typeName, $httpMethod, '\\', false));
    }

    /**
     * Join and simplify input type and method into a string that can be used as an array key
     *
     * @param string $typeName
     * @param string $methodName
     * @param string $delimiter
     * @param bool $lcfirst
     * @return string
     */
    private function generateKey($typeName, $methodName, $delimiter = '\\', $lcfirst = true)
    {
        $parts = explode($delimiter, ltrim($typeName, $delimiter));
        foreach ($parts as &$part) {
            $part = ltrim($part, ':');
            if ($lcfirst === true) {
                $part = lcfirst($part);
            }
        }

        return implode('.', $parts) . '.' . $methodName;
    }
}