<?php
// {{{ICINGA_LICENSE_CODE}}}
// -----------------------------------------------------------------------------
// This file is part of icinga-web.
// 
// Copyright (c) 2009-2013 Icinga Developer Team.
// All rights reserved.
// 
// icinga-web is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// icinga-web is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with icinga-web.  If not, see <http://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------------
// {{{ICINGA_LICENSE_CODE}}}


/**
 * NsmPrincipal
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    IcingaWeb
 * @subpackage AppKit
 * @author     Icinga Development Team <info@icinga.org>
 * @version    SVN: $Id: Builder.php 6401 2009-09-24 16:12:04Z guilhermeblanco $
 */
class NsmPrincipal extends BaseNsmPrincipal {
    const TYPE_ROLE = 'role';
    const TYPE_USER = 'user';

    public function setUp() {
        parent::setUp();

        $this->hasMany('Cronk', array(
                           'local'      => 'cpc_principal_id',
                           'foreign'    => 'cpc_cronk_id',
                           'refClass'   => 'CronkPrincipalCronk'
                       ));
    }

    /**
     * (non-PHPdoc)
     * @see Doctrine_Record::preUpdate()
     */
    public function preUpdate($event) {
        $this->updatePrincipalType();
    }

    /**
     * (non-PHPdoc)
     * @see Doctrine_Record::preInsert()
     */
    public function preInsert($event) {
        $this->updatePrincipalType();
    }

    /**
     * Checks for existing principal type and change
     * id needed
     * @throws AppKitDoctrineException2
     * @return true if no exception
     */
    private function updatePrincipalType() {

        if (in_array($this->principal_type, array(self::TYPE_ROLE, self::TYPE_USER)) === true) {
            return true;
        }

        if ($this->principal_role_id && $this->principal_user_id) {
            throw new AppKitDoctrineException('Unexpected principal condition, please check the object');
        }

        if ($this->principal_role_id) {
            $this->principal_type = self::TYPE_ROLE;
        }

        elseif($this->principal_user_id) {
            $this->principal_type = self::TYPE_USER;
        }

        return true;
    }
}
