<?php

/**
 * Model request 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\Request;

use Sso\WebserviceBundle\Model\Base as ModelBase;
use Sso\WebserviceBundle\Model\Type\Factory as TypeFactory;
use Sso\WebserviceBundle\Model\Request\Error;
use Sso\WebserviceBundle\Api\Validator\Xml as XmlValidator;

/**
 * Model request base class
 */
abstract class Base extends ModelBase
{

    /**
     * @var TypeFactory
     */
    protected $typeF;

    /**
     * Constructor
     * @param TypeFactory $typeF
     */
    public function __construct(TypeFactory $typeF)
    {
        $this->typeF = $typeF;
    }

    /**
     * Init model
     * @param \SimpleXMLElement $simpleXML
     */
    public function init($simpleXML)
    {
        $validator = new XmlValidator();
        if (!$validator->validate($simpleXML, $validator->strToXml($this->_xmlAllowedElements()))) {
            $this->errors()->addErrors($validator->errors()->getErrors());
            $this->_exception();
        }
    }

    /**
     * Get validation groups to identify an user
     * @param \SimpleXMLElement $xml
     * @return array
     */
    protected function userIdentifyValdiationGroups($xml)
    {
        // Validate for show
        if (property_exists($xml, 'Identifier')) {
            // This value is used, if you don't know if it is a guid, username or email
            return array('Identify_By_Identifier');
        } elseif (property_exists($xml, 'Guid')) {
            // Validate guid
            return array('Identify_By_Guid');
        } elseif (property_exists($xml, 'Username')) {
            // Validate username
            return array('Identify_By_Username');
        } elseif (property_exists($xml, 'Email')) {
            // Validate email
            return array('Identify_By_Email');
        }

        // Use a pseudo validation rule, to force an error
        return array('Identify_Error');
    }

    /**
     * Returns a xml-string with allowed structure
     * @return string
     */
    abstract protected function _xmlAllowedElements();
}
