<?php
namespace App\Infrastructure\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\RouterInterface;
class GoogleHelper
{
private \Google_Client $client;
private RouterInterface $router;
private string $credentialsPath;
private string $appHostAddress;
public function __construct(ContainerInterface $container, RouterInterface $router)
{
$this->appHostAddress = $_ENV['APP_HOST'];
$credentialsPath = $container->getParameter('kernel.project_dir') . '/var/resources/google_credentials.json';
if (!file_exists($credentialsPath)) {
throw new NotFoundHttpException('Google credentials were not found');
}
$this->credentialsPath = $credentialsPath;
$this->client = new \Google_Client();
$this->router = $router;
}
public function login(): string
{
return $this->getInstance()->createAuthUrl();
}
public function getInstance(): \Google_Client
{
$this->client->setAuthConfig($this->credentialsPath);
$this->client->setAccessType('offline');
$this->client->setRedirectUri($this->appHostAddress . $this->router->generate('google_login_handle'));
$this->client->setIncludeGrantedScopes(true);
$this->client->addScope([
\Google\Service\Oauth2::USERINFO_EMAIL,
\Google\Service\Oauth2::USERINFO_PROFILE
]);
return $this->client;
}
}