Skip to content

A Symfony bundle with a listener which converts controller returned data into a appropriate JsonResponse.

License

Notifications You must be signed in to change notification settings

chrisyue/auto-json-response-bundle

Repository files navigation

Auto Json Response Bundle

v1.1.1

A Symfony listener which converts controller result to a appropriate JsonResponse.

SensioLabsInsight

Latest Stable Version License Build Status Scrutinizer Code Quality Code Coverage StyleCI

Features

  • Convert null to JsonResponse(null, 204)
  • Convert $array|$object to JsonResponse($array|$normalizedObject)
  • Convert $array|$object to JsonResponse($array|$normalizedObject, 201) if the method is POST

Installation

$ composer require chrisyue/auto-json-response-bundle
// AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Chrisyue\Bundle\AutoJsonResponseBundle\ChrisyueAutoJsonResponseBundle(),
    );
}

Usage

This bundle will take effect if the route _format parameter is set to json.

# in your route file:
api:
    resource: ...
    defaults:
        _format: json

or in your controller file when you use annotation

/**
 * @Route(...)
 */
public function putAction(Response $response, $_format = 'json')
{
    ...

    return $object;
}

or any other ways to set the $_format to json.

This bundle uses Symfony built-in serializer to normalize object, so the serialize feature should be enable if you want to deal with object:

# app/config/config.yml
framework:
    # ...
    serializer:
        enabled: true

with the power of the built-in serializer, we can do more configuration to meet our needs, like convert camalCase property to snake_case:

# app/config/config.yml
framework:
    serializer:
        enable_annotations: true
        name_converter: serializer.name_converter.camel_case_to_snake_case

More information about serialize, just check symfony official documentation

After v1.1.0, this bundle support specify default serialization groups:

#app/config/config.yml
chrisyue_auto_json_response:
    serializer:
        default_groups:
            - 'group1'
            - 'group2'

About

A Symfony bundle with a listener which converts controller returned data into a appropriate JsonResponse.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages