<?php
namespace App\Controller;
use App\Entity\SocialLink;
use App\Form\SocialLinkType;
use Kunstmaan\AdminListBundle\Controller\AdminListController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Exception\ValidatorException;
class SocialLinkController extends AdminListController
{
/**
* Set urls
*
* @Route("/set-urls", methods={"GET"}, name="gcs_admin_social_set_urls")
*
*/
public function setUrl()
{
return $this->render(
'SocialLinks/settingsView.html.twig',
[
'instagram' => $this->prepareForm('instagram')->createView(),
'facebook' => $this->prepareForm('facebook')->createView(),
'youtube' => $this->prepareForm('youtube')->createView(),
'twitter' => $this->prepareForm('twitter')->createView(),
'rss' => $this->prepareForm('rss')->createView(),
'bip' => $this->prepareForm('bip')->createView()
]
);
}
/**
* Save setting
*
* @Route("/set-urls/{type}", methods={"POST"}, name="gcs_admin_social_set_urls_post")
*/
public function postAction(Request $request, $type)
{
$form = $this->prepareForm($type);
$form->handleRequest($request);
if (!$form->isSubmitted() || !$form->isValid()) {
throw new ValidatorException('form is invalid');
}
/** @var SocialLink $socialLink */
$socialLink = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($socialLink);
$em->flush();
return $this->redirectToRoute('gcs_admin_social_set_urls');
}
private function prepareForm($type)
{
/** @var SocialLink $setting */
$setting = $this->getDoctrine()->getRepository(SocialLink::class)->findOneByType($type);
if (!$setting) {
$setting = new SocialLink();
$setting->setType($type);
}
return $this->createForm(
SocialLinkType::class,
$setting,
[
'method' => 'POST',
'action' => $this->generateUrl('gcs_admin_social_set_urls_post', ['type' => $type]),
]
);
}
public function feedAction($type)
{
$repository = $this->getDoctrine()->getRepository(SocialLink::class);
/** @var SocialLink $settings */
$settings = $repository->findOneByType($type);
$url = $settings ? $settings->getLinkUrl() : null;
return new Response($url);
}
}