nilportugues / php-json-api

JSON API transformer outputting valid (PSR-7) API Responses.
http://nilportugues.com
MIT License
71 stars 35 forks source link

Sample code for bundling #19

Closed nilportugues closed 9 years ago

nilportugues commented 9 years ago

Just the concept. Needs work

//To build a bundle we need to automate generating the array with postId => {postId}
$routeNameFromMappingFile = 'nilportugues_application_view_post';

$router = $this->get('router')->getRouteCollection()->get($routeNameFromMappingFile);
preg_match_all('/{(.*?)}/', $router->getPath(), $matches);

$pattern = [];
if(!empty($matches)) {
    $pattern = array_combine($matches[1], $matches[0]);
}

$route = urldecode($this->generateUrl($routeNameFromMappingFile, $pattern, true));

//Mapping declaration
$mapping = new Mapping(ViewPostResponse::class, $route, ['postId']);
$mapping->setClassAlias('post');
$mapping->setPropertyNameAliases(['postTitle' => 'headline', 'postBody' => 'content']);
$mappings = [$mapping->getClassName() => $mapping];

//Serializer into action
$serializer = new Serializer(new JsonApiTransformer($mappings));
$response = $serializer->serialize($commandBus->getResult());

return new Response(
$response, 200, ['Content-type' => 'application/vnd.api+json; charset=utf-8']));
nilportugues commented 9 years ago

But this has been partially address with the laravel bundle already. :)