<?php
namespace Backend\BaseBundle\Service;


use Backend\BaseBundle\Model\Site;
use Backend\BaseBundle\Model\SiteQuery;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * @DI\Service("request_site_finder")
 */
class RequestSiteFinder
{
    /** @var  RequestStack */
    protected $requestStack;

    /** @var  Site */
    protected $site;

    protected $slug;

    /**
     * @DI\InjectParams()
     */
    public function injectRequestStack(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    /**
     * @return Site
     */
    public function getSite($slug = null)
    {
        if($slug == null || $slug == $this->slug) {
            $this->findSite();
            return $this->site;
        }
        return SiteQuery::create()->findOneBySlug($slug);
    }

    protected function findSite()
    {
        if($request = $this->requestStack->getMasterRequest()) {
            $this->slug = $request->attributes->get('slug');
            $this->site = SiteQuery::create()->findOneBySlug($this->slug);
        }
    }

}