<?php
namespace Cms\TenantBundle\Doctrine;
use Cms\CoreBundle\Model\Search\SearchableTrait;
use Cms\CoreBundle\Util\Doctrine\EntityRepository;
use Cms\DomainBundle\Entity\Domain;
use Cms\TenantBundle\Entity\Tenant;
use Cms\TenantBundle\Model\ProductsBitwise;
use Common\Util\Strings;
/**
* Class TenantRepository
* @package Cms\TenantBundle\Doctrine
*
* @method Tenant findExact($id)
* @method array|Tenant[] findAll()
*/
final class TenantRepository extends EntityRepository
{
use SearchableTrait;
/**
* @param ProductsBitwise $products
* @return array|Tenant[]
*/
public function findAllWithProducts(ProductsBitwise $products)
{
return $this->queryMany(
$this->createQueryBuilder('tenants')
->andWhere('BIT_AND(tenants.products, :products) > 0')
->setParameter('products', $products->getMask())
->addOrderBy('tenants.name', 'ASC')
);
}
/**
* @param string|int $value
* @return Tenant
*/
public function findExactByIdOrSlug($value)
{
$value = strval($value);
if (preg_match('/^[1-9]\d*$/', $value) === 1) {
return $this->findExact(intval($value));
}
return $this->findExactBySlug($value);
}
/**
* @param string $slug
* @return Tenant
* @throws \Exception
*/
public function findExactBySlug($slug)
{
$tenant = $this->findOneBySlug($slug);
if ($tenant === null) {
throw new \Exception();
}
return $tenant;
}
/**
* @param string $host
* @return Tenant
* @throws \Exception
*/
public function findOneByHost($host)
{
if (preg_match('/^(.+?)\.([^.]+?\.[^.]+?)$/', $host, $matches) !== 1) {
throw new \Exception();
}
$qb = $this->_em->createQueryBuilder();
$qb
->select('domain')
->from(Domain::class, 'domain')
->leftJoin('domain.apex', 'apex')
->andWhere('apex.host = :host')
->setParameter('host', $matches[2])
->andWhere('domain.name = :name')
->setParameter('name', $matches[1]);
$domain = $this->queryOne($qb);/** @var Domain $domain */
if ($domain === null) {
return null;
}
return $domain->getTenant();
}
/**
* @param string $slug
* @return Tenant
*/
public function findOneBySlug($slug)
{
return $this->findOneBy(array(
'slug' => $slug,
));
}
/**
* @param string $uid
* @return Tenant
*/
public function findOneByUid($uid)
{
return $this->findOneBy(array(
'uid' => $uid,
));
}
/**
* @param string $slug
* @return bool
*/
public function isSlugTaken($slug)
{
$result = $this
->getEntityManager()
->createQuery("
SELECT
1
FROM
SharedTenantBundle:Tenant t
WHERE
t.slug = :slug
")
->setParameter('slug', $slug)
->getScalarResult();
return (count($result) != 0);
}
/**
* @param string $name
* @return bool
*/
public function isNameTaken($name)
{
$result = $this
->getEntityManager()
->createQuery("
SELECT
1
FROM
SharedTenantBundle:Tenant t
WHERE
t.name = :name
")
->setParameter('name', $name)
->getScalarResult();
return (count($result) != 0);
}
/**
* @param string $slug
* @return Tenant[]
*/
public function findTenantForView($slug)
{
return $this->findOneBy(array(
'slug' => $slug,
));
}
}