<?php

/**
 * Base class for response
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected 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  2014 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Model\Response;

use Sso\WebserviceBundle\Model\Base as ModelBase;
use Sso\WebserviceBundle\Model\Request\Base as RequestBase;
use Sso\WebserviceBundle\Api\Exception\Type\Api as ApiException;
use Sso\WebserviceBundle\Api\Response\Builder as XmlResponse;

/**
 * Base class for response
 */
abstract class Base extends ModelBase
{

    /**
     * Xml response document
     * @var XmlResponse
     */
    protected $xmlResponse;

    /**
     * @param XmlResponse $xmlResponse
     */
    public function __construct(XmlResponse $xmlResponse)
    {
        $this->xmlResponse = $xmlResponse;
    }

    /**
     * Returns response message e. g. Application added
     * @return string|bool Set to false, to suppress message element
     */
    abstract protected function getResponseMessage();

    /**
     * Returns response true, false or Success, Failure
     * @return string|bool
     */
    protected function getResponseStatus()
    {
        return true;
    }

    /**
     * Build response body
     * @param \DOMElement $xmlContainer
     */
    protected function buildResponseBody(\DOMElement $xmlContainer)
    {
        if (false !== ($message = $this->getResponseMessage())) {
            $xmlContainer->appendChild($this->xmlResponse->document()->createTextElement('Message', $message));
        }
    }

    /**
     * Generate xml response
     * @param RequestBase $requestModel
     */
    protected function buildResponse(RequestBase $requestModel)
    {

        // An error has occured
        if ($requestModel->hasErrors()) {
            $exception = new ApiException();
            $exception->setErrors($requestModel->getErrors());
            throw $exception;
        }

        $action = $this->xmlResponse->action();
        $this->xmlResponse->status($this->getResponseStatus());
        $this->buildResponseBody($action);
    }
}
