<?php
/*
* This file is part of the nellapp-core package.
*
* (c) Benjamin Georgeault
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Service\Sync\Routing;
use App\Entity\App\App;
use App\Repository\App\AppRepository;
use Nellapp\Bundle\SDKBundle\Enum\AppEnum;
use Nellapp\Bundle\SDKBundle\Routing\Utils\ChannelMainDomainUtils;
use Nellapp\Bundle\SDKBundle\Routing\Utils\DomainsRoutingUtils;
use Nellapp\Bundle\SDKBundle\Sync\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Class Routing
*
* @author Benjamin Georgeault
*/
class Routing
{
/** @var RouteCollection[] */
private array $routes = [];
public function __construct(
private CacheInterface $nellappSyncRoutesCache,
private HttpClientInterface $client,
private AppRepository $appRepository,
private RouterInterface $router,
private string $superAdminDomain,
private string $commercialDomain,
private string $syncDomain,
private bool $debug = false,
private DomainsRoutingUtils $domainsRoutingUtils,
)
{
}
/**
* @return RouteCollection[]
*/
public function getCollections(?App $ignoreApp = null, bool $cache = true): array
{
$array = [
'core' => RouteCollection::createFromSymfonyCollection($this->router->getRouteCollection(), AppEnum::CORE, $this->domainsRoutingUtils->getDefaultDomain(),
function (Route $route) {
return !in_array($route->getHost(), [
$this->superAdminDomain,
$this->syncDomain,
]);
}),
];
foreach ($this->appRepository->findAllExclude($ignoreApp) as $app) {
if ((null === $url = $app->getUrl()) || !filter_var($url, FILTER_VALIDATE_URL)) {
continue;
}
$routes = $cache ? $this->getRoutes($app) : $this->doGetRoutes($app);
if (null !== $routes) {
$array[$app->getQueueName()] = $routes;
}
}
return $array;
}
private function getRoutes(App $app): ?RouteCollection
{
if (array_key_exists($queue = $app->getQueueName(), $this->routes)) {
return $this->routes[$queue];
}
return $this->routes[$queue] = $this->nellappSyncRoutesCache->get(sprintf('global_routes_%s', $app->getQueueName()), function (ItemInterface $item) use ($app) {
$item->expiresAfter($this->debug ? 300 : 3600);
return $this->doGetRoutes($app);
});
}
private function doGetRoutes(App $app): ?RouteCollection
{
if ((null === $url = $app->getUrl()) || !filter_var($url, FILTER_VALIDATE_URL)) {
return null;
}
try {
$response = $this->client->request('GET', $url . 'routing/routes', [
'timeout' => $this->debug ? 15 : 10,
'headers' => [
'Authorization' => 'Core ' . $app->getSecret(),
],
]);
return RouteCollection::createFromArray([
'app_name' => $app->getQueueName(),
'routes' => $response->toArray(),
'host' => $app->getHost(),
]);
} catch (ExceptionInterface) {
return null;
}
}
}