<?php

/**
 * 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  2018 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\WebserviceBundle\Error;

use LifeStyle\Tools\WebserviceBundle\Error\Type;
use LifeStyle\Tools\WebserviceBundle\Response\Builder as ResponseBuilder;

/**
 * Class Storage
 * @package LifeStyle\Tools\WebserviceBundle\Error
 */
class Storage
{

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

    /**
     * @var ResponseBuilder
     */
    protected $responseBuilder;

    /**
     * @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);
            }
        }
    }

    /**
     * Clear error storage
     */
    public function clearErrors()
    {
        $this->errors = array();
    }

    /**
     * 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);
        }
    }
}
