<?php

/**
 * User: sb
 * Date: 14.11.2014
 * Time: 11:48
 * 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       www.life-style.de
 */

namespace Sso\ApiBundle\Database\Webservice;

use Sso\Webservices\ObjectBundle\Entity\Object as ModelObject;


/**
 * User database handler
 */
class Object extends Base
{

    /**
     * @param ModelObject $typeObject
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function saveObject(ModelObject $typeObject)
    {
        $this->_entityManager->persist($typeObject);
        $this->_entityManager->flush($typeObject);

        return true;
    }

    /**
     * @param ModelObject $typeObject
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteObject(ModelObject $typeObject)
    {
        $this->_entityManager->remove($typeObject);
        $this->_entityManager->flush($typeObject);

        return true;
    }

    /**
     * Find object by primary key
     *
     * @param string $objectGuid
     * @return ModelObject|null
     */
    public function find($objectGuid)
    {
        $entity = $this->getObjectRepository()->find($objectGuid);
        return ($entity instanceof ModelObject) ? $entity : null;
    }

    /**
     * @param string $objectId
     * @return ModelObject|null
     */
    public function getObjectById(string $objectId)
    {
        return $this->find($objectId);
    }

    /**
     *
     * @return \Doctrine\ORM\EntityRepository
     */
    public function getObjectRepository()
    {
        return $this->_entityManager->getRepository(\Sso\Webservices\ObjectBundle\Entity\Object::class);
    }

    /**
     *
     * @return ModelObject
     */
    public function getObjectModel()
    {
        return new ModelObject();
    }

    /**
     * @return ModelObject[]
     */
    public function findInvalidObjects()
    {
        $criteria = [
            'treeId' => ModelObject::INVALID_TREE_ID,
        ];
        return $this->getObjectRepository()->findBy($criteria);
    }
}
