<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\RestBundle\Api\MainValidator;

use Sso\RestBundle\Api\ExceptionCollection\MainValidationException;
use LifeStyle\Tools\RestErrorBundle\Api\Manager as ErrorApi;
use LifeStyle\Tools\RestErrorBundle\Api\Error\Errors\Index as Errors;
use Sso\RestBundle\Api\Helper\Factory as Helper;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class Index
 * @package Sso\RestBundle\Api\MainValidator
 */
class Index
{
    const ERROR_EXTERNAL = "external";

    /**
     * @var ErrorApi
     */
    protected $errorApi;

    /**
     * @var Errors
     */
    private $errors;

    /**
     * @var Helper
     */
    private $helper;

    /**
     * Index constructor.
     * @param ErrorApi $errorApi
     * @param Helper $helper
     */
    public function __construct(ErrorApi $errorApi, Helper $helper)
    {
        $this->errorApi = $errorApi;
        $this->errors = $this->errorApi->error()->errors();
        $this->helper = $helper;
    }

    /**
     * validation rest requests for no content and invalid XML/JSON
     * if the validation fails it is allowed to return the default error response format
     * the response header is 416
     *
     * @param Request $request
     * @throws MainValidationException
     * @return array
     */
    public function validateRestRequest(Request $request)
    {
        // check for content in request body
        $requestContent = $request->getContent();

        if (empty($requestContent)) {
            $this->errors->addError(416, 'No Content found in your request', static::ERROR_EXTERNAL)->setCode(416);
            throw new MainValidationException();
        }

        // get request format XML/JSON
        $format = preg_match('/\.xml/i', $request->getUri()) ? 'xml' : 'json';

        // now validate the content
        if ($format == "xml") {
            $errors = $this->helper->string()->validateXML($requestContent);
        } else {
            $errors = $this->helper->string()->validateJson($requestContent);
        }

        // collect errors
        foreach ($errors as $error) {
            $this->errors->addError(416, $error, static::ERROR_EXTERNAL, 'InvalidRequest')->setCode(416);
        }

        if ($this->errors->hasErrors()) {
            throw new MainValidationException();
        }

        return [$requestContent, $format];
    }
}
