-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathHeadlessWebsiteController.php
83 lines (69 loc) · 2.5 KB
/
HeadlessWebsiteController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
/*
* This file is part of Sulu.
*
* (c) Sulu GmbH
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Sulu\Bundle\HeadlessBundle\Controller;
use Sulu\Bundle\HeadlessBundle\Content\StructureResolverInterface;
use Sulu\Bundle\WebsiteBundle\Controller\WebsiteController;
use Sulu\Component\Content\Compat\PageInterface;
use Sulu\Component\Content\Compat\StructureInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class HeadlessWebsiteController extends WebsiteController
{
/**
* We cannot set the typehint of the $structure parameter to PageInterface because the ArticleBundle does not
* implement that interface. Therefore we need to define the type via phpdoc to satisfy phpstan.
*
* @param PageInterface $structure
*/
public function indexAction(
Request $request,
StructureInterface $structure,
bool $preview = false,
bool $partial = false
): Response {
$headlessData = $this->resolveStructure($structure);
if ('json' !== $request->getRequestFormat()) {
return $this->renderStructure($structure, ['headless' => $headlessData], $preview, $partial);
}
$response = new Response($this->serializeData($headlessData));
$response->headers->set('Content-Type', 'application/json');
$cacheLifetimeEnhancer = $this->getCacheTimeLifeEnhancer();
if (!$preview && $cacheLifetimeEnhancer) {
$cacheLifetimeEnhancer->enhance($response, $structure);
}
return $response;
}
/**
* @return mixed[]
*/
protected function resolveStructure(StructureInterface $structure): array
{
/** @var StructureResolverInterface $structureResolver */
$structureResolver = $this->container->get('sulu_headless.structure_resolver');
return $structureResolver->resolve($structure, $structure->getLanguageCode());
}
/**
* @param mixed[] $data
*/
protected function serializeData(array $data): string
{
return \json_encode($data, \JSON_THROW_ON_ERROR);
}
/**
* @return mixed[]
*/
public static function getSubscribedServices(): array
{
$subscribedServices = parent::getSubscribedServices();
$subscribedServices['sulu_headless.structure_resolver'] = StructureResolverInterface::class;
return $subscribedServices;
}
}