<?php
/**
 * Plain Text deserializer of REST request content.
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Sibs\Sibs\Webapi\Rest\Request\Deserializer;

use InvalidArgumentException;
use Magento\Framework\App\State;
use Magento\Framework\Phrase;
use Magento\Framework\Webapi\Exception as WebapiException;
use Magento\Framework\Webapi\Rest\Request\DeserializerInterface;
use RuntimeException;
use Sibs\Sibs\Serialize\Serializer\Text;

class PlainText implements DeserializerInterface
{
    /**
     * @var State
     */
    protected $_appState;

    /**
     * @param Decoder $decoder
     * @param State $appState
     * @param Text|null $serializer
     * @throws RuntimeException
     */
    public function __construct(
        State $appState
    ) {
        $this->_appState = $appState;
    }

    /**
     * Parse Request body into array of params.
     *
     * @param string $encodedBody Posted content from request.
     * @return array|null Return NULL if content is invalid.
     * @throws InvalidArgumentException
     * @throws Exception If decoding error was encountered.
     */
    public function deserialize($encodedBody)
    {
        if (! is_string($encodedBody)) {
            throw new InvalidArgumentException(
                sprintf('"%s" data type is invalid. String is expected.', gettype($encodedBody))
            );
        }

        try {
            $decodedBody = $encodedBody;
        } catch (InvalidArgumentException $e) {
            if ($this->_appState->getMode() !== State::MODE_DEVELOPER) {
                throw new WebapiException(new Phrase('Decoding error.'));
            } else {
                throw new WebapiException(
                    new Phrase(
                        'Decoding error: %1%2%3%4',
                        [PHP_EOL, $e->getMessage(), PHP_EOL, $e->getTraceAsString()]
                    )
                );
            }
        }

        return $decodedBody;
    }
}
