<?php

/**
 * Model base class
 *
 * 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;

use Sso\WebserviceBundle\Api\Error\Type\Base as BaseError;
use Sso\WebserviceBundle\Api\Error\Storage as ErrorStorage;
use Sso\WebserviceBundle\Model\Exception;

/**
 * Model base class
 */
class Base
{

    /**
     * Errors
     * @var Error\Storage
     */
    private $_errors;

    /**
     * Return with error
     * @param BaseError $error
     * @throws Exception
     */
    protected function _exception(BaseError $error = null)
    {
        if (null !== $error) {
            $this->addError($error);
        }
        $exception = new Exception();
        $exception->setErrors($this->errors()->getErrors());
        throw $exception;
    }

    /**
     * Add error
     * @param BaseError $error
     */
    public function addError(BaseError $error)
    {
        $this->errors()->addError($error);
    }

    /**
     * Add list of errors
     * @param array $errors
     */
    public function addErrors(array $errors)
    {
        foreach ($errors as $error) {
            $this->addError($error);
        }
    }

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

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

    /**
     * Get error storage
     * @return ErrorStorage
     */
    public function errors()
    {
        return $this->_errors ? $this->_errors : ($this->_errors = new ErrorStorage());
    }
}
