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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
<?php
namespace App\Provider;
use Gedcomx\GedcomxFile\DefaultJsonSerialization;
use Gedcomx\GedcomxFile\DefaultXMLSerialization;
use GeniBase\Common\GeniBaseClass;
use Silex\Application;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
class ResponsibleListener implements EventSubscriberInterface
{
protected $app;
protected $encoder;
public function __construct(Application $app, EncoderInterface $encoder)
{
$this->app = $app;
$this->encoder = $encoder;
}
public function onKernelView(GetResponseForControllerResultEvent $event)
{
$request = $event->getRequest();
$result = $event->getControllerResult();
if (! is_array($result) && ! ($result instanceof \Gedcomx\Gedcomx)
&& ! ($result instanceof GeniBaseClass)
) {
return;
}
$supported = array('json', 'xml');
$default = reset($supported);
$accepted = $request->getAcceptableContentTypes() ?: array($request->getMimeType($default));
if (count($accepted) === 1 && $accepted[0] === '*/*') {
$accepted[0] = $request->headers->get('Content-Type');
}
foreach ($accepted as $type) {
if (in_array($format = $request->getFormat($type), $supported)) {
if ($result instanceof \Gedcomx\Gedcomx || $result instanceof GeniBaseClass) {
$serializer = ('json' == $format
? new DefaultJsonSerialization() : new DefaultXMLSerialization() );
$response = new Response(
$serializer->serialize($result),
200,
array('Content-Type' => $type)
);
$event->setResponse($response);
} else {
$event->setResponse(
new Response(
$this->encoder->encode($result, $format),
200,
array('Content-Type' => $type)
)
);
}
return;
}
}
if ('HTTP/1.1' === $request->server->get('SERVER_PROTOCOL')) {
$event->setResponse(
new Response(
$this->encoder->encode($result, $default),
200,
array('Content-Type' => $request->getMimeType($default))
)
);
return;
}
$event->setResponse(
new Response(
'Not Acceptable',
406,
array('Content-Type' => 'text/plain')
)
);
}
public static function getSubscribedEvents()
{
return array(KernelEvents::VIEW => array('onKernelView', -10));
}
}