Skip to content

Commit 685ad5d

Browse files
committed
Enhance output
1 parent 2ce1141 commit 685ad5d

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

code_samples/api/rest_api/src/Rest/Controller/DefaultController.php

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
use Ibexa\Rest\Server\Controller;
1010
use Symfony\Component\HttpFoundation\Request;
1111
use Symfony\Component\HttpFoundation\Response;
12+
use Symfony\Component\Serializer\Encoder\XmlEncoder;
13+
use Symfony\Component\Serializer\SerializerInterface;
1214

1315
#[Get(
1416
uriTemplate: '/greet',
@@ -28,8 +30,31 @@
2830
)]
2931
class DefaultController extends Controller
3032
{
31-
public function greet(Request $request): Greeting
33+
const DEFAULT_FORMAT = 'xml';
34+
35+
const AVAILABLE_FORMATS = ['json', 'xml'];
36+
37+
public function __construct(private SerializerInterface $serializer)
38+
{
39+
}
40+
41+
public function greet(Request $request): Response//Greeting
3242
{
33-
return new Greeting();
43+
//$this->serializer->deserialize($request->getContent())
44+
45+
//return new Greeting();
46+
47+
$accept = $request->headers->get('Accept', 'application/' . self::DEFAULT_FORMAT);
48+
preg_match('@.*[/+](?P<format>[^/+]+)@', $accept, $matches);
49+
$format = empty($matches['format']) ? self::DEFAULT_FORMAT : $matches['format'];
50+
if (!in_array($format, self::AVAILABLE_FORMATS)) {
51+
$format = self::DEFAULT_FORMAT;
52+
}
53+
54+
$serialized = $this->serializer->serialize(new Greeting('Salut', 'Monde'), $format, [
55+
XmlEncoder::ROOT_NODE_NAME => 'Greeting',
56+
]);
57+
58+
return new Response($serialized, Response::HTTP_OK);
3459
}
3560
}

code_samples/api/rest_api/src/Rest/Serializer/GreetingNormalizer.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,15 @@ public function supportsNormalization(mixed $data, ?string $format = null)
2424
*/
2525
public function normalize(mixed $object, ?string $format = null, array $context = []): array
2626
{
27-
return $this->normalizer->normalize(['greeting' => [
27+
$data = [
2828
'salutation' => $object->salutation,
2929
'recipient' => $object->recipient,
3030
'sentence' => "{$object->salutation} {$object->recipient}",
31-
]], $format, $context);
31+
];
32+
if ('json' === $format) {
33+
$data = ['greeting' => $data];
34+
}
35+
36+
return $this->normalizer->normalize($data, $format, $context);
3237
}
3338
}

0 commit comments

Comments
 (0)