Fault.php 11.5 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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
<?php
/**
 * Magento-specific SOAP fault.
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Webapi\Model\Soap;

use Magento\Framework\App\State;

class Fault
{
    const FAULT_REASON_INTERNAL = 'Internal Error.';

    /**#@+
     * Fault codes that are used in SOAP faults.
     */
    const FAULT_CODE_SENDER = 'Sender';
    const FAULT_CODE_RECEIVER = 'Receiver';

    /**#@+
     * Nodes that can appear in Detail node of SOAP fault.
     */
    const NODE_DETAIL_PARAMETERS = 'Parameters';
    const NODE_DETAIL_WRAPPED_ERRORS = 'WrappedErrors';
    const NODE_DETAIL_WRAPPED_EXCEPTION = 'WrappedException';
    /* Note that parameter node must be unique in scope of all complex types declared in WSDL */
    const NODE_DETAIL_PARAMETER = 'GenericFaultParameter';
    const NODE_DETAIL_PARAMETER_KEY = 'key';
    const NODE_DETAIL_PARAMETER_VALUE = 'value';
    const NODE_DETAIL_WRAPPED_ERROR = 'WrappedError';
    const NODE_DETAIL_WRAPPED_ERROR_MESSAGE = 'message';
    const NODE_DETAIL_WRAPPED_ERROR_PARAMETERS = 'parameters';
    const NODE_DETAIL_WRAPPED_ERROR_PARAMETER = 'parameter';
    const NODE_DETAIL_WRAPPED_ERROR_KEY = 'key';
    const NODE_DETAIL_WRAPPED_ERROR_VALUE = 'value';
    const NODE_DETAIL_TRACE = 'Trace';
    const NODE_DETAIL_WRAPPER = 'GenericFault';
    /**#@-*/

    /**
     * @var string
     */
    protected $_soapFaultCode;

    /**
     * Parameters are extracted from exception and can be inserted into 'Detail' node as 'Parameters'.
     *
     * @var array
     */
    protected $_parameters = [];

    /**
     * Wrapped errors are extracted from exception and can be inserted into 'Detail' node as 'WrappedErrors'.
     *
     * @var array
     */
    protected $_wrappedErrors = [];

    /**
     * Fault name is used for details wrapper node name generation.
     *
     * @var string
     */
    protected $_faultName = '';

    /**
     * Details that are used to generate 'Detail' node of SoapFault.
     *
     * @var array
     */
    protected $_details = [];

    /**
     * @var \Magento\Framework\App\RequestInterface
     */
    protected $_request;

    /**
     * @var Server
     */
    protected $_soapServer;

    /**
     * @var \Magento\Framework\Locale\ResolverInterface
     */
    protected $_localeResolver;

    /**
     * @var \Magento\Framework\App\State
     */
    protected $appState;

    /**
     * @var null|string
     */
    protected $stackTrace;

    /**
     * @var string
     */
    protected $message;

    /**
     * @param \Magento\Framework\App\RequestInterface $request
     * @param Server $soapServer
     * @param \Magento\Framework\Webapi\Exception $exception
     * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
     * @param State $appState
     */
    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
        Server $soapServer,
        \Magento\Framework\Webapi\Exception $exception,
        \Magento\Framework\Locale\ResolverInterface $localeResolver,
        State $appState
    ) {
        $this->_soapFaultCode = $exception->getOriginator();
        $this->_parameters = $exception->getDetails();
        $this->_wrappedErrors = $exception->getErrors();
        $this->stackTrace = $exception->getStackTrace() ?: $exception->getTraceAsString();
        $this->message = $exception->getMessage();
        $this->_request = $request;
        $this->_soapServer = $soapServer;
        $this->_localeResolver = $localeResolver;
        $this->appState = $appState;
    }

    /**
     * Render exception as XML.
     *
     * @return string
     */
    public function toXml()
    {
        if ($this->appState->getMode() == State::MODE_DEVELOPER) {
            $this->addDetails([self::NODE_DETAIL_TRACE => "<![CDATA[{$this->stackTrace}]]>"]);
        }
        if ($this->getParameters()) {
            $this->addDetails([self::NODE_DETAIL_PARAMETERS => $this->getParameters()]);
        }
        if ($this->getWrappedErrors()) {
            $this->addDetails([self::NODE_DETAIL_WRAPPED_ERRORS => $this->getWrappedErrors()]);
        }

        return $this->getSoapFaultMessage($this->getMessage(), $this->getSoapCode(), $this->getDetails());
    }

    /**
     * Retrieve additional details about current fault.
     *
     * @return array
     */
    public function getParameters()
    {
        return $this->_parameters;
    }

    /**
     * Retrieve wrapped errors about current fault.
     *
     * @return array
     */
    public function getWrappedErrors()
    {
        return $this->_wrappedErrors;
    }

    /**
     * Add details about current fault.
     *
     * @param array $details Associative array containing details about current fault
     * @return $this
     */
    public function addDetails($details)
    {
        $this->_details = array_merge($this->_details, $details);
        return $this;
    }

    /**
     * Retrieve additional details about current fault.
     *
     * @return array
     */
    public function getDetails()
    {
        return $this->_details;
    }

    /**
     * Retrieve SOAP fault code.
     *
     * @return string
     */
    public function getSoapCode()
    {
        return $this->_soapFaultCode;
    }

    /**
     * Retrieve SOAP fault language.
     *
     * @return string
     */
    public function getLanguage()
    {
        return \Locale::getPrimaryLanguage($this->_localeResolver->getLocale());
    }

    /**
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Generate SOAP fault message in XML format.
     *
     * @param string $reason Human-readable explanation of the fault
     * @param string $code SOAP fault code
     * @param array|null $details Detailed reason message(s)
     * @return string
     */
    public function getSoapFaultMessage($reason, $code, $details = null)
    {
        $detailXml = $this->_generateDetailXml($details);
        $language = $this->getLanguage();
        $detailsNamespace = !empty($detailXml)
            ? 'xmlns:m="' . urlencode($this->_soapServer->generateUri(true)) . '"'
            : '';
        $reason = htmlentities($reason);
        $message = <<<FAULT_MESSAGE
<?xml version="1.0" encoding="utf-8" ?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" $detailsNamespace>
   <env:Body>
      <env:Fault>
         <env:Code>
            <env:Value>env:$code</env:Value>
         </env:Code>
         <env:Reason>
            <env:Text xml:lang="$language">$reason</env:Text>
         </env:Reason>
         $detailXml
      </env:Fault>
   </env:Body>
</env:Envelope>
FAULT_MESSAGE;
        return $message;
    }

    /**
     * Generate 'Detail' node content.
     *
     * In case when fault name is undefined, no 'Detail' node is generated.
     *
     * @param array $details
     * @return string
     */
    protected function _generateDetailXml($details)
    {
        $detailsXml = '';
        if (is_array($details) && !empty($details)) {
            $detailsXml = $this->_convertDetailsToXml($details);
            if ($detailsXml) {
                $errorDetailsNode = self::NODE_DETAIL_WRAPPER;
                $detailsXml = "<env:Detail><m:{$errorDetailsNode}>"
                    . $detailsXml . "</m:{$errorDetailsNode}></env:Detail>";
            } else {
                $detailsXml = '';
            }
        }
        return $detailsXml;
    }

    /**
     * Recursively convert details array into XML structure.
     *
     * @param array $details
     * @return string
     */
    protected function _convertDetailsToXml($details)
    {
        $detailsXml = '';
        foreach ($details as $detailNode => $detailValue) {
            $detailNode = htmlspecialchars($detailNode);
            if (is_numeric($detailNode)) {
                continue;
            }
            switch ($detailNode) {
                case self::NODE_DETAIL_TRACE:
                    if (is_string($detailValue) || is_numeric($detailValue)) {
                        $detailsXml .= "<m:{$detailNode}>" . htmlspecialchars($detailValue) . "</m:{$detailNode}>";
                    }
                    break;
                case self::NODE_DETAIL_PARAMETERS:
                    $detailsXml .= $this->_getParametersXml($detailValue);
                    break;
                case self::NODE_DETAIL_WRAPPED_ERRORS:
                    $detailsXml .= $this->_getWrappedErrorsXml($detailValue);
                    break;
            }
        }
        return $detailsXml;
    }

    /**
     * Generate XML for parameters.
     *
     * @param array $parameters
     * @return string
     */
    protected function _getParametersXml($parameters)
    {
        $result = '';
        if (!is_array($parameters)) {
            return $result;
        }
        $paramsXml = '';
        foreach ($parameters as $parameterName => $parameterValue) {
            if ((is_string($parameterName) || is_numeric($parameterName))
                && (is_string($parameterValue) || is_numeric($parameterValue))
            ) {
                $keyNode = self::NODE_DETAIL_PARAMETER_KEY;
                $valueNode = self::NODE_DETAIL_PARAMETER_VALUE;
                $parameterNode = self::NODE_DETAIL_PARAMETER;
                if (is_numeric($parameterName)) {
                    $parameterName++;
                }
                $paramsXml .= "<m:$parameterNode><m:$keyNode>$parameterName</m:$keyNode><m:$valueNode>"
                    . htmlspecialchars($parameterValue) . "</m:$valueNode></m:$parameterNode>";
            }
        }
        if (!empty($paramsXml)) {
            $parametersNode = self::NODE_DETAIL_PARAMETERS;
            $result = "<m:$parametersNode>" . $paramsXml . "</m:$parametersNode>";
        }

        return $result;
    }

    /**
     * Generate XML for wrapped errors.
     *
     * @param array $wrappedErrors
     * @return string
     */
    protected function _getWrappedErrorsXml($wrappedErrors)
    {
        $result = '';
        if (!is_array($wrappedErrors)) {
            return $result;
        }

        $errorsXml = '';
        foreach ($wrappedErrors as $error) {
            $errorsXml .= $this->_generateErrorNodeXML($error);
        }
        if (!empty($errorsXml)) {
            $wrappedErrorsNode = self::NODE_DETAIL_WRAPPED_ERRORS;
            $result = "<m:$wrappedErrorsNode>" . $errorsXml . "</m:$wrappedErrorsNode>";
        }

        return $result;
    }

    /**
     * Generate XML for a particular error node.
     *
     * @param array $error
     * @return string
     */
    protected function _generateErrorNodeXML($error)
    {
        $wrappedErrorNode = self::NODE_DETAIL_WRAPPED_ERROR;
        $messageNode = self::NODE_DETAIL_WRAPPED_ERROR_MESSAGE;

        $parameters = $error->getParameters();
        $rawMessage = $error->getRawMessage();
        $xml = "<m:$wrappedErrorNode><m:$messageNode>$rawMessage</m:$messageNode>";

        if (!empty($parameters)) {
            $parametersNode = self::NODE_DETAIL_WRAPPED_ERROR_PARAMETERS;
            $xml .= "<m:$parametersNode>";
            foreach ($parameters as $key => $value) {
                $parameterNode = self::NODE_DETAIL_WRAPPED_ERROR_PARAMETER;
                $keyNode = self::NODE_DETAIL_PARAMETER_KEY;
                $valueNode = self::NODE_DETAIL_WRAPPED_ERROR_VALUE;
                $xml .= "<m:$parameterNode>" .
                    "<m:$keyNode>$key</m:$keyNode><m:$valueNode>$value</m:$valueNode>" .
                    "</m:$parameterNode>";
            }
            $xml .= "</m:$parametersNode>";
        }
        $xml .= "</m:$wrappedErrorNode>";

        return $xml;
    }
}