Skip to content

Commit

Permalink
Routes can be added to the event entity
Browse files Browse the repository at this point in the history
  • Loading branch information
manuxi committed Mar 27, 2021
1 parent abd4fe1 commit 436b681
Show file tree
Hide file tree
Showing 11 changed files with 185 additions and 96 deletions.
12 changes: 1 addition & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,6 @@ Please add the following to your `routes_admin.yaml`:
SuluEventBundle:
resource: '@SuluEventBundle/Resources/config/routes_admin.yml'
```
...and the following to your `routes_website.yaml`:
```yaml
SuluEventBundle:
resource: "@SuluEventBundle/Resources/config/routes.yml"
```
Last but not least the entity tables must be created in the database.
The tables which will be created are
```
Expand Down Expand Up @@ -96,18 +91,13 @@ Example of the corresponding twig template for the event list:
{{ event.teaser|raw }}
</p>
<p>
<a class="btn btn-primary" href="{{ path('event', {id: event.id, slug: event.title|slugify}) }}" role="button">
<a class="btn btn-primary" href="{{ event.routePath }}" role="button">
{{ "Read more..."|trans }} <i class="fa fa-angle-double-right"></i>
</a>
</p>
</div>
{% endfor %}
```
The route to the single event follows the scheme:
```
"en": "/events/{id}/{slug}",
"de": "/veranstaltungen/{id}/{slug}"
```
At the moment the template for the single event is located here
`templates/pages/event.html.twig`

Expand Down
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
}
],
"require": {
"cocur/slugify": "^4.0",
"dantleech/phpcr-migrations-bundle": "^1.2",
"php": "^7.2 | ^8.0",
"sulu/sulu": "^2.2",
Expand Down
43 changes: 38 additions & 5 deletions src/Controller/Admin/EventController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
//use HandcraftedInTheAlps\RestRoutingBundle\Controller\Annotations\RouteResource;
//use HandcraftedInTheAlps\RestRoutingBundle\Routing\ClassResourceInterface;
use Sulu\Bundle\MediaBundle\Entity\MediaRepositoryInterface;
use Sulu\Bundle\RouteBundle\Entity\RouteRepositoryInterface;
use Sulu\Bundle\RouteBundle\Manager\RouteManagerInterface;
use Sulu\Component\Rest\AbstractRestController;
use Sulu\Component\Security\SecuredControllerInterface;
use Symfony\Component\HttpFoundation\Request;
Expand All @@ -33,21 +35,20 @@
class EventController extends AbstractRestController implements ClassResourceInterface, SecuredControllerInterface
{
private $locationRepository;

private $eventRepository;

private $eventSeoRepository;

private $mediaRepository;

private $doctrineListRepresentationFactory;

private $entityManager;
private $routeManager;
private $routeRepository;

public function __construct(
EventRepository $eventRepository,
EventSeoRepository $eventSeoRepository,
MediaRepositoryInterface $mediaRepository,
RouteManagerInterface $routeManager,
RouteRepositoryInterface $routeRepository,
LocationRepository $locationRepository,
DoctrineListRepresentationFactory $doctrineListRepresentationFactory,
EntityManagerInterface $entityManager,
Expand All @@ -62,6 +63,8 @@ public function __construct(
$this->locationRepository = $locationRepository;

parent::__construct($viewHandler, $tokenStorage);
$this->routeManager = $routeManager;
$this->routeRepository = $routeRepository;
}

public function cgetAction(Request $request): Response
Expand Down Expand Up @@ -94,6 +97,7 @@ public function postAction(Request $request): Response
//event
$eventEntity = $this->createEvent($request);
$this->mapDataToEntity($request->request->all(), $eventEntity);
$this->updateRoutesForEntity($eventEntity);
$this->saveEvent($eventEntity);

//in the first step we'll _only_ create a Event object (no Seo, Taxonomy, etc.)
Expand Down Expand Up @@ -139,6 +143,7 @@ public function putAction(int $id, Request $request): Response
}

$this->mapDataToEntity($request->request->all(), $eventEntity);
$this->updateRoutesForEntity($eventEntity);
$this->saveEvent($eventEntity);

//do we have an EventSeo?
Expand Down Expand Up @@ -171,6 +176,7 @@ public function getSecurityContext(): string
protected function mapDataToEntity(array $data, Event $entity): void
{
$entity->setTitle($data['title']);
$entity->setRoutePath($data['routePath']);

$teaser = $data['teaser'] ?? null;
if ($teaser) {
Expand Down Expand Up @@ -259,6 +265,10 @@ protected function saveEvent(Event $entity): void
*/
protected function removeEvent(int $id): void
{
/** @var Event $event */
$event = $this->eventRepository->findById($id);
$this->removeRoutesForEntity($event);

$this->eventRepository->remove($id);
}

Expand Down Expand Up @@ -290,4 +300,27 @@ protected function removeEventSeo(int $id): void
{
$this->eventSeoRepository->remove($id);
}

protected function updateRoutesForEntity(Event $entity): void
{
$this->routeManager->createOrUpdateByAttributes(
Event::class,
(string) $entity->getId(),
$entity->getLocale(),
$entity->getRoutePath()
);
}

protected function removeRoutesForEntity(Event $entity): void
{
$routes = $this->routeRepository->findAllByEntity(
Event::class,
(string) $entity->getId(),
$entity->getLocale()
);

foreach ($routes as $route) {
$this->routeRepository->remove($route);
}
}
}
87 changes: 28 additions & 59 deletions src/Controller/Website/EventController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,63 +6,50 @@

use Manuxi\SuluEventBundle\Entity\Event;
use Manuxi\SuluEventBundle\Repository\EventRepository;
use Cocur\Slugify\SlugifyInterface;
use JMS\Serializer\SerializerBuilder;
use Sulu\Bundle\MediaBundle\Media\Manager\MediaManagerInterface;
use Sulu\Bundle\RouteBundle\Entity\RouteRepositoryInterface;
use Sulu\Bundle\WebsiteBundle\Resolver\TemplateAttributeResolverInterface;
use Sulu\Component\Webspace\Manager\WebspaceManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;

class EventController extends AbstractController
{
private $translator;

private $slugify;

private $eventRepository;

private $webspaceManager;

private $templateAttributeResolver;
private $routeRepository;

public function __construct(
RequestStack $requestStack,
MediaManagerInterface $mediaManager,
EventRepository $eventRepository,
WebspaceManagerInterface $webspaceManager,
SlugifyInterface $slugify,
TranslatorInterface $translator,
TemplateAttributeResolverInterface $templateAttributeResolver
TemplateAttributeResolverInterface $templateAttributeResolver,
RouteRepositoryInterface $routeRepository
) {
parent::__construct($requestStack, $mediaManager);

$this->eventRepository = $eventRepository;
$this->webspaceManager = $webspaceManager;
$this->slugify = $slugify;
$this->translator = $translator;
$this->templateAttributeResolver = $templateAttributeResolver;
$this->routeRepository = $routeRepository;
}

/**
* @Route({
* "en": "/events/{id}/{slug}",
* "de": "/veranstaltungen/{id}/{slug}"
* }, name="event")
*/
public function indexAction(int $id, string $slug): Response
public function indexAction(Event $event): Response
{
$event = $this->eventRepository->findById($id, $this->request->getLocale());
$parameters = $this->templateAttributeResolver->resolve([
'event' => $event,
'content' => [
'title' => $this->translator->trans('pages.events'),
'subtitle' => $event->getTitle(),
// 'banners' => $this->getBannerMedia(self::BANNER_IDS) //lets unittests fail
],
'path' => $this->generateUrl('event', ['id' => $id, 'slug' => $slug]),
'path' => $event->getRoutePath(),
'extension' => $this->extractExtension($event),
'localizations' => $this->getLocalizationsArrayForEntity($event),
'created' => $event->getCreated(),
Expand All @@ -72,43 +59,25 @@ public function indexAction(int $id, string $slug): Response
}

/**
* With the help of this method the corresponding localisations for the
* current event are found e.g. to be linked in the language switcher.
* @return array<string, array>
*/
protected function getLocalizationsArrayForEntity(Event $event): array
{
$locales = $this->webspaceManager->getAllLocales();
$routes = $this->routeRepository->findAllByEntity(Event::class, (string)$event->getId());

$localizations = [];
foreach ($locales as $locale) {
$event->setLocale($locale);

//we don't have a translation
if (null === $event->getTitle()) {
$url = null;
} else {
$urlParams = [
'id' => $event->getId(),
'slug' => $this->slugify->slugify($event->getTitle()),
'_locale' => $locale,
];
$routePath = $this->generateUrl('event', $urlParams);
$url = $this->webspaceManager->findUrlByResourceLocator(
$routePath,
null,
$locale
);
}

$localizations[$locale] = [
'locale' => $locale,
'url' => $url,
];
foreach ($routes as $route) {
$url = $this->webspaceManager->findUrlByResourceLocator(
$route->getPath(),
null,
$route->getLocale()
);

$localizations[$route->getLocale()] = ['locale' => $route->getLocale(), 'url' => $url];
}

//we have to set back the locale of the event, because $event is passed by reference.
//We don't want to clone here so just reset the $event's locale...
$event->setLocale($this->request->getLocale());

return $localizations;
}

Expand All @@ -122,16 +91,16 @@ private function extractExtension(Event $event): array
/**
* @return string[]
*/
// public static function getSubscribedServices()
// {
// $subscribedServices = parent::getSubscribedServices();
//
//// $subscribedServices['sulu_core.webspace.webspace_manager'] = WebspaceManagerInterface::class;
//// $subscribedServices['sulu.repository.route'] = RouteRepositoryInterface::class;
// $subscribedServices['sulu_website.resolver.template_attribute'] = TemplateAttributeResolverInterface::class;
//
// return $subscribedServices;
// }
public static function getSubscribedServices()
{
$subscribedServices = parent::getSubscribedServices();

$subscribedServices['sulu_core.webspace.webspace_manager'] = WebspaceManagerInterface::class;
$subscribedServices['sulu.repository.route'] = RouteRepositoryInterface::class;
$subscribedServices['sulu_website.resolver.template_attribute'] = TemplateAttributeResolverInterface::class;

return $subscribedServices;
}

/**
* "seo" => array:7 [▼
Expand Down
31 changes: 17 additions & 14 deletions src/DependencyInjection/SuluEventExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,23 @@ public function prepend(ContainerBuilder $container)
// );
// }

// if ($container->hasExtension('sulu_route')) {
// $container->prependExtensionConfig(
// 'sulu_route',
// [
// 'mappings' => [
// Event::class => [
// 'generator' => 'schema',
// 'options' => ['route_schema' => '/event/{object.getId()}'],
// 'resource_key' => Event::RESOURCE_KEY,
// ],
// ],
// ]
// );
// }
if ($container->hasExtension('sulu_route')) {
$container->prependExtensionConfig(
'sulu_route',
[
'mappings' => [
Event::class => [
'generator' => 'schema',
'options' => [
'route_schema' => '/event/{object.getId()}'
],
// 'options' => ['route_schema' => '/event/{implode("-", object)}'],
'resource_key' => Event::RESOURCE_KEY,
],
],
]
);
}

if ($container->hasExtension('sulu_admin')) {
$container->prependExtensionConfig(
Expand Down
25 changes: 25 additions & 0 deletions src/Entity/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,31 @@ public function setTeaser(string $teaser): self
return $this;
}

/**
* @Serializer\VirtualProperty(name="route_path")
*/
public function getRoutePath(): ?string
{
$translation = $this->getTranslation($this->locale);
if (!$translation) {
return null;
}

return $translation->getRoutePath();
}

public function setRoutePath(string $routePath): self
{
$translation = $this->getTranslation($this->locale);
if (!$translation) {
$translation = $this->createTranslation($this->locale);
}

$translation->setRoutePath($routePath);

return $this;
}

/**
* @Serializer\VirtualProperty(name="description")
*/
Expand Down
17 changes: 17 additions & 0 deletions src/Entity/EventTranslation.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ class EventTranslation implements AuditableInterface
*/
private $description = null;

/**
* @ORM\Column(type="string", length=255)
*/
private $routePath;

public function __construct(Event $event, string $locale)
{
$this->event = $event;
Expand Down Expand Up @@ -106,4 +111,16 @@ public function setDescription(?string $description): self

return $this;
}

public function getRoutePath(): string
{
return $this->routePath ?? '';
}

public function setRoutePath(string $routePath): self
{
$this->routePath = $routePath;

return $this;
}
}
Loading

0 comments on commit 436b681

Please sign in to comment.