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

declare(strict_types=1);

namespace Magento\WebapiAsync\Plugin;

use Magento\Webapi\Model\Config\Converter as WebapiConverter;
use Magento\AsynchronousOperations\Api\Data\AsyncResponseInterface;
use Magento\WebapiAsync\Controller\Rest\AsynchronousSchemaRequestProcessor;
use Magento\WebapiAsync\Model\ServiceConfig\Converter;

class ServiceMetadata
{
    /**
     * @var \Magento\Webapi\Model\Config
     */
    private $webapiConfig;
    /**
     * @var \Magento\WebapiAsync\Model\ServiceConfig
     */
    private $serviceConfig;
    /**
     * @var AsynchronousSchemaRequestProcessor
     */
    private $asynchronousSchemaRequestProcessor;
    /**
     * @var \Magento\Framework\Webapi\Rest\Request
     */
    private $request;
    /**
     * @var \Magento\Framework\Reflection\TypeProcessor
     */
    private $typeProcessor;
    /**
     * @var array
     */
    private $responseDefinitionReplacement;
    /**
     * @var array
     */
    private $synchronousOnlyHttpMethods = [
        'GET'
    ];

    /**
     * ServiceMetadata constructor.
     *
     * @param \Magento\Webapi\Model\Config $webapiConfig
     * @param \Magento\WebapiAsync\Model\ServiceConfig $serviceConfig
     * @param AsynchronousSchemaRequestProcessor $asynchronousSchemaRequestProcessor
     */
    public function __construct(
        \Magento\Webapi\Model\Config $webapiConfig,
        \Magento\WebapiAsync\Model\ServiceConfig $serviceConfig,
        \Magento\Framework\Webapi\Rest\Request $request,
        AsynchronousSchemaRequestProcessor $asynchronousSchemaRequestProcessor,
        \Magento\Framework\Reflection\TypeProcessor $typeProcessor
    ) {
        $this->webapiConfig = $webapiConfig;
        $this->serviceConfig = $serviceConfig;
        $this->request = $request;
        $this->asynchronousSchemaRequestProcessor = $asynchronousSchemaRequestProcessor;
        $this->typeProcessor = $typeProcessor;
    }

    /**
     * @param \Magento\Webapi\Model\ServiceMetadata $subject
     * @param array $result
     * @return array
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    public function afterGetServicesConfig(\Magento\Webapi\Model\ServiceMetadata $subject, array $result)
    {
        if ($this->asynchronousSchemaRequestProcessor->canProcess($this->request)) {
            $synchronousOnlyServiceMethods = $this->getSynchronousOnlyServiceMethods($subject);
            // Replace all results with the async response schema
            foreach ($result as $serviceName => $serviceData) {
                // Check all of the methods on the service
                foreach ($serviceData[WebapiConverter::KEY_METHODS] as $methodName => $methodData) {
                    // Exclude service methods that are marked as synchronous only
                    if ($this->isServiceMethodSynchronousOnly(
                        $serviceName,
                        $methodName,
                        $synchronousOnlyServiceMethods
                    )) {
                        $this->removeServiceMethodDefinition($result, $serviceName, $methodName);
                    } else {
                        $this->replaceResponseDefinition($result, $serviceName, $methodName);
                    }
                }
            }
        }

        return $result;
    }

    /**
     * @param $serviceName
     * @param $methodName
     * @param array $synchronousOnlyServiceMethods
     * @return bool
     */
    private function isServiceMethodSynchronousOnly($serviceName, $methodName, array $synchronousOnlyServiceMethods)
    {
        return isset($synchronousOnlyServiceMethods[$serviceName][$methodName]);
    }

    /**
     * @param string $serviceName
     * @return array
     */
    private function getServiceVersions(string $serviceName)
    {
        $services = $this->webapiConfig->getServices();

        return array_keys($services[WebapiConverter::KEY_SERVICES][$serviceName]);
    }

    /**
     * Get a list of all service methods that cannot be executed asynchronously.
     *
     * @param \Magento\Webapi\Model\ServiceMetadata $serviceMetadata
     * @return array
     */
    private function getSynchronousOnlyServiceMethods(\Magento\Webapi\Model\ServiceMetadata $serviceMetadata)
    {
        $synchronousOnlyServiceMethods = [];
        $services = $this->serviceConfig->getServices()[Converter::KEY_SERVICES] ?? [];
        foreach ($services as $service => $serviceData) {
            if (!isset($serviceData[Converter::KEY_METHODS])) {
                continue;
            }

            foreach ($serviceData[Converter::KEY_METHODS] as $method => $methodData) {
                if ($this->isMethodDataSynchronousOnly($methodData)) {
                    $this->appendSynchronousOnlyServiceMethodsWithInterface(
                        $serviceMetadata,
                        $synchronousOnlyServiceMethods,
                        $service,
                        $method
                    );
                }
            }
        }

        return array_merge_recursive(
            $synchronousOnlyServiceMethods,
            $this->getSynchronousOnlyRoutesAsServiceMethods($serviceMetadata)
        );
    }

    /**
     * Get service methods associated with routes that can't be processed as asynchronous.
     *
     * @param \Magento\Webapi\Model\ServiceMetadata $serviceMetadata
     * @return array
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    private function getSynchronousOnlyRoutesAsServiceMethods(
        \Magento\Webapi\Model\ServiceMetadata $serviceMetadata
    ) {
        $synchronousOnlyServiceMethods = [];
        $serviceRoutes = $this->webapiConfig->getServices()[\Magento\Webapi\Model\Config\Converter::KEY_ROUTES];
        foreach ($serviceRoutes as $serviceRoutePath => $serviceRouteMethods) {
            foreach ($serviceRouteMethods as $serviceRouteMethod => $serviceRouteMethodData) {
                // Check if the HTTP method associated with the route is not able to be async.
                if (in_array(strtoupper($serviceRouteMethod), $this->synchronousOnlyHttpMethods)) {
                    $this->appendSynchronousOnlyServiceMethodsWithInterface(
                        $serviceMetadata,
                        $synchronousOnlyServiceMethods,
                        $serviceRouteMethodData[WebapiConverter::KEY_SERVICE][WebapiConverter::KEY_SERVICE_CLASS],
                        $serviceRouteMethodData[WebapiConverter::KEY_SERVICE][WebapiConverter::KEY_SERVICE_METHOD]
                    );
                }
            }
        }

        return $synchronousOnlyServiceMethods;
    }

    /**
     * @param \Magento\Webapi\Model\ServiceMetadata $serviceMetadata
     * @param array $synchronousOnlyServiceMethods
     * @param $serviceInterface
     * @param $serviceMethod
     */
    private function appendSynchronousOnlyServiceMethodsWithInterface(
        \Magento\Webapi\Model\ServiceMetadata $serviceMetadata,
        array &$synchronousOnlyServiceMethods,
        $serviceInterface,
        $serviceMethod
    ) {
        foreach ($this->getServiceVersions($serviceInterface) as $serviceVersion) {
            $serviceName = $serviceMetadata->getServiceName($serviceInterface, $serviceVersion);
            if (!array_key_exists($serviceName, $synchronousOnlyServiceMethods)) {
                $synchronousOnlyServiceMethods[$serviceName] = [];
            }

            $synchronousOnlyServiceMethods[$serviceName][$serviceMethod] = true;
        }
    }

    /**
     * @param array $result
     * @param $serviceName
     * @param $methodName
     */
    private function removeServiceMethodDefinition(array &$result, $serviceName, $methodName)
    {
        unset($result[$serviceName][WebapiConverter::KEY_METHODS][$methodName]);

        // Remove the service altogether if there is no methods left.
        if (count($result[$serviceName][WebapiConverter::KEY_METHODS]) === 0) {
            unset($result[$serviceName]);
        }
    }

    /**
     * @param array $result
     * @param $serviceName
     * @param $methodName
     */
    private function replaceResponseDefinition(array &$result, $serviceName, $methodName)
    {
        if (isset($result[$serviceName][WebapiConverter::KEY_METHODS][$methodName]['interface']['out'])) {
            $replacement = $this->getResponseDefinitionReplacement();
            $result[$serviceName][WebapiConverter::KEY_METHODS][$methodName]['interface']['out'] = $replacement;
        }
    }

    /**
     * Check if a method on the given service is defined as synchronous only using XML.
     *
     * @param array $methodData
     * @return bool
     */
    private function isMethodDataSynchronousOnly(array $methodData)
    {
        if (!isset($methodData[Converter::KEY_SYNCHRONOUS_INVOCATION_ONLY])) {
            return false;
        }

        return $methodData[Converter::KEY_SYNCHRONOUS_INVOCATION_ONLY];
    }

    /**
     * @return array
     */
    private function getResponseDefinitionReplacement()
    {
        if ($this->responseDefinitionReplacement === null) {
            $this->responseDefinitionReplacement = [
                'parameters' => [
                    'result' => [
                        'type' => $this->typeProcessor->register(AsyncResponseInterface::class),
                        'documentation' => 'Returns response information for the asynchronous request.',
                        'required' => true,
                        'response_codes' => [
                            'success' => [
                                'code' => '202',
                                'description' => '202 Accepted.'
                            ]
                        ]
                    ]
                ]
            ];
        }

        return $this->responseDefinitionReplacement;
    }
}