<?php

namespace Repositories;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * UsrListOwnerRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class UsrListOwnerRepository extends EntityRepository
{

    /**
     *
     *
     * @param  \Entities\UsrList $list
     * @param  type              $owner_id
     * @return \Entities\UsrList
     */
    public function findByListAndOwner(\Entities\UsrList $list, $owner_id)
    {
        $owner = $this->find($owner_id);

        /* @var $owner \Entities\UsrListOwner */
        if (null === $owner) {
            throw new NotFoundHttpException(_('Owner is not found'));
        }

        if ( ! $owner->getList()->getid() != $list->getId()) {
            throw new AccessDeniedHttpException(_('Owner and list mismatch'));
        }

        return $owner;
    }

    /**
     *
     *
     * @param  \Entities\UsrList $list
     * @param  type              $usr_id
     * @return \Entities\UsrList
     */
    public function findByListAndUsrId(\Entities\UsrList $list, $usr_id)
    {
        $dql = 'SELECT o FROM Entities\UsrListOwner o
              JOIN o.list l
            WHERE l.id = :list_id AND o.usr_id = :usr_id';

        $params = array(
            'usr_id'  => $usr_id,
            'list_id' => $list->getId()
        );

        $query = $this->_em->createQuery($dql);
        $query->setParameters($params);

        $owner = $query->getSingleResult();

        /* @var $owner \Entities\UsrListOwner */
        if (null === $owner) {
            throw new NotFoundHttpException(_('Owner is not found'));
        }

        return $owner;
    }
}
