<?php
namespace Cms\DomainBundle\Doctrine;
use Cms\CoreBundle\Util\Doctrine\EntityRepository;
use Cms\DomainBundle\Entity\Domain;
use Cms\DomainBundle\Entity\SslCertificate;
use Cms\DomainBundle\Entity\SslCertificates\CustomSslCertificate;
use Cms\DomainBundle\Entity\SslCertificates\LetsEncryptSslCertificate;
/**
* Class DomainRepository
* @package Cms\DomainBundle\Doctrine
*
* @method Domain|null find($id, $lockMode = null, $lockVersion = null);
* @method Domain findExact($id);
* @method Domain[] findAll();
*/
final class DomainRepository extends EntityRepository
{
/**
* @param int|string $value
* @return Domain
* @throws \Exception
*/
public function findExactByIdOrHost($value)
{
$domain = $this->findByIdOrHost($value);
if (empty($domain)) {
throw new \Exception();
}
return $domain;
}
/**
* @param int|string $value
* @return Domain|null
* @throws \Exception
*/
public function findByIdOrHost($value)
{
if (preg_match('/^[1-9]\d*$/', $value) === 1) {
$domain = $this->find($value);
} else {
$domain = $this->findOneByHost($value);
}
return $domain;
}
/**
* @param string $host
* @return Domain
* @throws \Exception
*/
public function findOneByHost($host)
{
// need to break the hostname apart
if (preg_match('/^(.+?)\.(.+)$/', $host, $matches) !== 1) {
throw new \Exception(sprintf(
'Unsupported hostname lookup for: %s',
$host
));
}
// create builder
$qb = $this->createQueryBuilder('domain');
$qb
// need to join on apexes
->leftJoin('domain.apex', 'apex')
// check case of empty subdomain with full apex
->orWhere($qb->expr()->andX(
'domain.name = :fullDomain',
'apex.host = :fullApex'
))
// check for when first piece is a subdomain and rest is apex
->orWhere($qb->expr()->andX(
'domain.name = :shortDomain',
'apex.host = :shortApex'
))
// parameters for everything
->setParameters(array(
'fullDomain' => '',
'fullApex' => $host,
'shortDomain' => $matches[1],
'shortApex' => $matches[2],
))
;
// done
return $this->queryOne($qb);
}
public function findWithSorting()
{
$qb = $this->createQueryBuilder('domain');
$qb
->leftJoin('domain.apex', 'apex')
->leftJoin('domain.certificate', 'certificate')
->leftJoin('domain.tenant', 'tenant')
->addOrderBy('tenant.name', 'ASC')
->addOrderBy('apex.host', 'ASC')
->addOrderBy('domain.name', 'ASC')
;
return $this->queryMany($qb);
}
}