<?php
namespace App\Controller;
use App\Entity\Connection;
use App\Form\ConnectionType;
use App\Service\CrmApi\ClientFacade;
use Doctrine\ORM\EntityManagerInterface;
use RetailCrm\Api\Factory\SimpleClientFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
use Throwable;
/**
* Class ConnectionController
*
* @package App\Controller
*/
class ConnectionController extends AbstractController
{
/**
* @var EntityManagerInterface $manager
*/
private EntityManagerInterface $manager;
/**
* @var ClientFacade
*/
private ClientFacade $clientFacade;
/**
* ConnectionController constructor.
*
* @param EntityManagerInterface $manager
* @param ClientFacade $clientFacade
*/
public function __construct(
EntityManagerInterface $manager,
ClientFacade $clientFacade
) {
$this->clientFacade = $clientFacade;
$this->manager = $manager;
}
/**
* @Route("/", name="connect", methods={"GET", "POST"})
* @param Request $request
*
* @return RedirectResponse|Response
* @throws Throwable
*/
public function connect(Request $request): RedirectResponse|Response
{
/* @var Connection $connection */
$connection = $this->getUser();
if ($connection) {
return $this->redirectToRoute('connection_settings');
}
$account = $request->get('account');
$connection = new Connection();
$form = $this->createFormBuilder($connection)
->setAction($this->generateUrl('connect'))
->setMethod('POST')
->add('apiUrl', TextType::class, ['label' => false, 'data' => $account ?? ''])
->add('apiKey', TextType::class, ['label' => false])
->add('clientId', HiddenType::class, ['data' => hash('ripemd160', (string)time())])
->getForm()
->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$searchExist = $this->manager->getRepository(Connection::class)->findOneBy(
['apiUrl' => $connection->getApiUrl(), 'apiKey' => $connection->getApiKey()]
);
if (null === $searchExist) {
// сейчас может быть только одно подключение
$searchExist = $this->manager->getRepository(Connection::class)->findOneBy([]);
if ($searchExist !== null) {
return new Response('Wrong credentials', 400);
}
$client = SimpleClientFactory::createClient($connection->getApiUrl(), $connection->getApiKey());
$this->clientFacade->setApiClient($client);
$resp = $this->clientFacade->editConfiguration($request->getHttpHost(), $connection->getClientId());
if ($resp['error'] == true) {
return new Response($resp['message'], 400);
}
$this->manager->persist($connection);
$this->manager->flush();
$request->getSession()->set('clientId', $connection->getClientId());
} else {
$request->getSession()->set('clientId', $searchExist->getClientId());
}
return $this->redirectToRoute('connection_settings');
}
return $this->render(
'index.html.twig',
[
'form' => $form->createView(),
'account' => $account
]
);
}
/**
* @Route("/settings", name="connection_settings", methods={"GET", "POST"})
*
* @return Response
*/
public function connectionSettings(): Response
{
/* @var Connection $connection */
$connection = $this->getUser();
if (is_null($connection)) {
return $this->redirectToRoute('connect');
}
$render = [];
$render['formConnection'] = $this->createForm(
ConnectionType::class,
$connection,
[
'action' => $this->generateUrl('save_connection'),
]
)->createView();
return $this->render('settings.html.twig', $render);
}
/**
* @Route("/settings/save/connection", name="save_connection", methods={"POST"})
* @param Request $request
* @param TranslatorInterface $translator
*
* @return Response
*/
public function saveConnection(Request $request, TranslatorInterface $translator): Response
{
/* @var Connection $connection */
$connection = $this->getUser();
if (is_null($connection)) {
return new Response('Authentication is not confirmed', Response::HTTP_FORBIDDEN);
}
$form = $request->get('connection');
/** @phpstan-ignore-next-line */
$connection->setApiUrl($form['apiUrl']);
/** @phpstan-ignore-next-line */
$connection->setApiKey($form['apiKey']);
$this->manager->persist($connection);
$this->manager->flush();
return new Response($translator->trans('Connection updated'), Response::HTTP_OK);
}
}