<?php
/**
 * Webservice Error storage
 *
 * 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  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Error;

use Sso\WebserviceBundle\Error\Type;
use Sso\WebserviceBundle\Response\Builder as ResponseBuilder;

/**
 * Webservice Error storage
 */
class Storage
{

    /**
     * List of errors
     * 
     * @var array
     */
    protected $_errors = array();

    /**
     * Xml response builder
     * 
     * @var ResponseBuilder
     */
    protected $responseBuilder;

    /**
     * Constructor
     * 
     * @param ResponseBuilder $responseBuilder
     */
    public function __construct(ResponseBuilder $responseBuilder = null)
    {
        $this->responseBuilder = $responseBuilder;
    }

    /**
     * Add error
     * 
     * @param Type\Base $error
     */
    public function addError(Type\Base $error)
    {
        $key = $error->getIdentifier();
        if (isset($this->_errors[$key])) {
            $this->_errors[$key]->incErrorCount($error->getErrorCount());
        } else {
            $this->_errors[$key] = $error;

            // Add error to xml response
            if (null !== $this->responseBuilder) {
                $this->responseBuilder->addErrorElement($error);
            }
        }
    }

    /**
     * List of errors
     * 
     * @return array
     */
    public function getErrors()
    {
        return array_values($this->_errors);
    }

    /**
     * Has errors
     * 
     * @return bool
     */
    public function hasErrors()
    {
        return 0 < count($this->getErrors());
    }

    /**
     * Copy errors from another error storage
     * 
     * @param array $errors
     */
    public function addErrors($errors)
    {
        foreach ($errors as $error) {
            $this->addError($error);
        }
    }

}
