<?php

namespace Cadoles\PortalBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\ArrayCollection;

class FluxRepository extends EntityRepository
{
    public function getUserFluxs($user) {
        // Profilage
        $roles=($user?$user->getRoles():["ROLE_ANONYME"]);
        $groups=($user?$user->getGroups():[]);

        // Initialisation du calcul des alerts
        $fluxs=new ArrayCollection();

        // Récupération des fluxs par rôles
        foreach($roles as $role) {
            $qb = $this->createQueryBuilder('a');
            $qb->select('flux')
                ->from("CadolesPortalBundle:Flux", 'flux')
                ->where($qb->expr()->like('flux.roles', $qb->expr()->literal("%$role%")));
            
            $fluxsroles=$qb->getQuery()->getResult();
            foreach($fluxsroles as $fluxrole) {
                if(!$fluxs->contains($fluxrole)) $fluxs->add($fluxrole);
            }
        }

        // Récupération des fluxs par group
        foreach($groups as $group) {
            $qb = $this->createQueryBuilder('a');
            $qb->select('flux')
                ->from("CadolesPortalBundle:Flux", 'flux')
                ->where(":group MEMBER OF flux.groups")
                ->setParameter("group",$group->getGroup());
            
            $fluxsgroups=$qb->getQuery()->getResult();
            foreach($fluxsgroups as $fluxgroup) {
                if(!$fluxs->contains($fluxgroup)) $fluxs->add($fluxgroup);
            }
        }

        return $fluxs;
    }
}
