{"id":14983667,"url":"https://github.com/nilportugues/symfony-hal-json","last_synced_at":"2025-04-10T19:02:37.104Z","repository":{"id":36581924,"uuid":"40887885","full_name":"nilportugues/symfony-hal-json","owner":"nilportugues","description":"HAL+JSON API Transformer Bundle for Symfony 2 and Symfony 3","archived":false,"fork":false,"pushed_at":"2017-03-23T10:32:04.000Z","size":43,"stargazers_count":10,"open_issues_count":1,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-24T16:43:47.310Z","etag":null,"topics":["api","hal","json","json-api","jsonapi","marshaller","microservice","microservices","php","php7","serialization","serializer","symfony","symfony-bundle","symfony2","symfony3","transformer"],"latest_commit_sha":null,"homepage":"http://nilportugues.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nilportugues.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-08-17T11:06:34.000Z","updated_at":"2024-08-23T15:57:35.000Z","dependencies_parsed_at":"2022-08-23T16:20:35.559Z","dependency_job_id":null,"html_url":"https://github.com/nilportugues/symfony-hal-json","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fsymfony-hal-json","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fsymfony-hal-json/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fsymfony-hal-json/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fsymfony-hal-json/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nilportugues","download_url":"https://codeload.github.com/nilportugues/symfony-hal-json/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248278867,"owners_count":21077341,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","hal","json","json-api","jsonapi","marshaller","microservice","microservices","php","php7","serialization","serializer","symfony","symfony-bundle","symfony2","symfony3","transformer"],"created_at":"2024-09-24T14:07:45.325Z","updated_at":"2025-04-10T19:02:37.063Z","avatar_url":"https://github.com/nilportugues.png","language":"PHP","funding_links":["https://paypal.me/nilportugues"],"categories":[],"sub_categories":[],"readme":"Symfony HAL+JSON Transformer Bundle\n=========================================\nFor Symfony 2 and Symfony 3\n\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/nilportugues/symfony2-hal-json-transformer/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/nilportugues/symfony2-hal-json-transformer/?branch=master)\n[![SensioLabsInsight](https://insight.sensiolabs.com/projects/3db88526-561a-4969-a734-cff5cedb5afb/mini.png)](https://insight.sensiolabs.com/projects/3db88526-561a-4969-a734-cff5cedb5afb) \n[![Latest Stable Version](https://poser.pugx.org/nilportugues/haljson-bundle/v/stable)](https://packagist.org/packages/nilportugues/haljson-bundle)\n[![Total Downloads](https://poser.pugx.org/nilportugues/haljson-bundle/downloads)](https://packagist.org/packages/nilportugues/haljson-bundle)\n[![License](https://poser.pugx.org/nilportugues/haljson-bundle/license)](https://packagist.org/packages/nilportugues/haljson-bundle)\n[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://paypal.me/nilportugues)\n\n- [Installation](#installation)\n- [Usage](#usage)\n    - [Creating the mappings](#creating-the-mappings)\n- [Outputing API Responses](#outputing-api-responses)\n    - [HAL+JSON Responses](#response-objects-haljsonresponsetrait)\n- [Integration with NelmioApiDocBundleBundle](#integration-with-nelmioapidocbundlebundle)\n- [Quality](#quality)\n- [Contribute](#contribute)\n- [Support](#support)\n- [Authors](#authors)\n- [License](#license)\n\n\n\n## Installation\n\n**Step 1: Download the Bundle**\n\nOpen a command console, enter your project directory and execute the\nfollowing command to download the latest stable version of this bundle:\n\n```bash\n$ composer require nilportugues/haljson-bundle\n```\n\n\n**Step 2: Enable the Bundle**\n\nThen, enable the bundle by adding it to the list of registered bundles\nin the `app/AppKernel.php` file of your project:\n\n```php\n\u003c?php\n// app/AppKernel.php\n// ...\nclass AppKernel extends Kernel\n{\n    public function registerBundles()\n    {\n        $bundles = array(\n            // ...\n            new NilPortugues\\Symfony\\HalJsonBundle\\NilPortuguesSymfonyHalJsonBundle(),\n        );\n        // ...\n    }\n    // ...\n}\n```\n\n## Usage\n\n### Creating the mappings\n\n**Mapping directory**\n\nMapping files should be located at the `app/config/serializer` directory. This directory must be created.\n\nIt can be also be customized and placed elsewhere by editing the `app/config/config.yml` configuration file:\n\n```yml\n# app/config/config.yml\n\nnilportugues_hal_json:\n    mappings: \n        - \"%kernel.root_dir%/config/serializer/\"\n         - @AppBundle/Product/config/Mappings\n```\n\n**Mapping files**\n\nThe HAL+JSON transformer works by transforming an existing PHP object into its JSON representation. For each object, a mapping file is required. \n\nMapping files **must** be placed in the mappings directory. The expected mapping file format is `.yml` and  will allow you to rename, hide and create links relating all of your data.\n\nFor instance, here's a quite complex `Post` object to demonstrate how it works:\n\n```php\n$post = new Post(\n    new PostId(9),\n    'Hello World',\n    'Your first post',\n    new User(\n        new UserId(1),\n        'Post Author'\n    ),\n    [\n        new Comment(\n            new CommentId(1000),\n            'Have no fear, sers, your king is safe.',\n            new User(new UserId(2), 'Barristan Selmy'),\n            [\n                'created_at' =\u003e (new DateTime('2015/07/18 12:13:00'))-\u003eformat('c'),\n                'accepted_at' =\u003e (new DateTime('2015/07/19 00:00:00'))-\u003eformat('c'),\n            ]\n        ),\n    ]\n);\n```\n\nAnd the series of mapping files required:\n\n```yml\n# app/config/serializer/acme_domain_dummy_post.yml\n\nmapping:\n  class: Acme\\Domain\\Dummy\\Post\n  alias: Message\n  aliased_properties:\n    author: author\n    title: headline\n    content: body\n  hide_properties: []\n  id_properties:\n    - postId\n  urls:\n    self: get_post ## @Route name\n    comments: get_post_comments ## @Route name\n  curies:\n    name: example\n    href: http://example.com/docs/rels/{rel}\n```\n\n```yml\n# app/config/serializer/acme_domain_dummy_value_object_post_id.yml\n\nmapping:\n  class: Acme\\Domain\\Dummy\\ValueObject\\PostId\n  aliased_properties: []\n  hide_properties: []\n  id_properties:\n  - postId\n  urls:\n    self: get_post  ## @Route name\n  curies:\n    name: example\n    href: http://example.com/docs/rels/{rel}\n```\n\n\n```yml\n# app/config/serializer/acme_domain_dummy_comment.yml\n\nmapping:\n  class: Acme\\Domain\\Dummy\\Comment\n  aliased_properties: []\n  hide_properties: []\n  id_properties:\n    - commentId\n  urls:\n    self: get_comment ## @Route name\n  curies:\n    name: example\n    href: http://example.com/docs/rels/{rel}\n```\n\n```yml\n# app/config/serializer/acme_domain_dummy_value_object_comment_id.yml\n\nmapping:\n  class: Acme\\Domain\\Dummy\\ValueObject\\CommentId\n  aliased_properties: []\n  hide_properties: []\n  id_properties:\n    - commentId\n  urls:\n    self: get_comment ## @Route name\n  curies:\n    name: example\n    href: http://example.com/docs/rels/{rel}\n```\n\n\n```yml\n# app/config/serializer/acme_domain_dummy_user.yml\n\nmapping:\n  class: Acme\\Domain\\Dummy\\User\n  aliased_properties: []\n  hide_properties: []\n  id_properties:\n  - userId\n  urls:\n    self: get_user\n    friends: get_user_friends  ## @Route name\n    comments: get_user_comments  ## @Route name\n  curies:\n    name: example\n    href: http://example.com/docs/rels/{rel}    \n```\n\n\n```yml\n# app/config/serializer/acme_domain_dummy_value_object_user_id.yml\n\nmapping:\n  class: Acme\\Domain\\Dummy\\ValueObject\\UserId\n  aliased_properties: []\n  hide_properties: []\n  id_properties:\n  - userId\n  urls:\n    self: get_user  ## @Route name\n    friends: get_user_friends  ## @Route name\n    comments: get_user_comments  ## @Route name\n  curies:\n    name: example\n    href: http://example.com/docs/rels/{rel}    \n```\n\n\n## Outputing API Responses\n\nIt is really easy, just get an instance of the `HalJsonSerializer` from the **Service Container** and pass the object to its `serialize()` method. Output will be valid JSON-API.\n\nHere's an example of a `Post` object being fetched from a Doctrine repository.\n\nFinally, a helper trait, `HalJsonResponseTrait` is provided to write fully compilant responses wrapping the PSR-7 Response objects provided by the original JSON API Transformer library.\n\n```php\n\u003c?php\nnamespace AppBundle\\Controller;\n\nuse NilPortugues\\Symfony\\HalJsonBundle\\Serializer\\HalJsonResponseTrait;\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller;\n\nclass PostController extends Controller\n{\n    use HalJsonResponseTrait;\n\n    /**\n     * @\\Symfony\\Component\\Routing\\Annotation\\Route(\"/post/{postId}\", name=\"get_post\")\n     *\n     * @param $postId\n     * @return \\Symfony\\Component\\HttpFoundation\\Response\n     */\n    public function getPostAction($postId)\n    {\n        $post = $this-\u003eget('doctrine.post_repository')-\u003efind($postId);\n        \n        $serializer = $this-\u003eget('nil_portugues.serializer.hal_json_serializer');\n\n        /** @var \\NilPortugues\\Api\\Hal\\HalTransformer $transformer */\n        $transformer = $serializer-\u003egetTransformer();\n        $transformer-\u003esetSelfUrl($this-\u003egenerateUrl('get_post', ['postId' =\u003e $postId], true));\n        $transformer-\u003esetNextUrl($this-\u003egenerateUrl('get_post', ['postId' =\u003e $postId+1], true));\n\n        return $this-\u003eresponse($serializer-\u003eserialize($post));\n    }\n} \n```\n\n\n**Output:**\n\n```\nHTTP/1.1 200 OK\nCache-Control: private, max-age=0, must-revalidate\nContent-type: application/hal+json\n```\n\n```json\n{\n    \"post_id\": 9,\n    \"headline\": \"Hello World\",\n    \"body\": \"Your first post\",\n    \"_embedded\": {\n        \"author\": {\n            \"user_id\": 1,\n            \"name\": \"Post Author\",\n            \"_links\": {\n                \"self\": {\n                    \"href\": \"http://example.com/users/1\"\n                },\n                \"example:friends\": {\n                    \"href\": \"http://example.com/users/1/friends\"\n                },\n                \"example:comments\": {\n                    \"href\": \"http://example.com/users/1/comments\"\n                }\n            }\n        },\n        \"comments\": [\n            {\n                \"comment_id\": 1000,\n                \"dates\": {\n                    \"created_at\": \"2015-08-13T22:47:45+02:00\",\n                    \"accepted_at\": \"2015-08-13T23:22:45+02:00\"\n                },\n                \"comment\": \"Have no fear, sers, your king is safe.\",\n                \"_embedded\": {\n                    \"user\": {\n                        \"user_id\": 2,\n                        \"name\": \"Barristan Selmy\",\n                        \"_links\": {\n                            \"self\": {\n                                \"href\": \"http://example.com/users/2\"\n                            },\n                            \"example:friends\": {\n                                \"href\": \"http://example.com/users/2/friends\"\n                            },\n                            \"example:comments\": {\n                                \"href\": \"http://example.com/users/2/comments\"\n                            }\n                        }\n                    }\n                },\n                \"_links\": {\n                    \"example:user\": {\n                        \"href\": \"http://example.com/users/2\"\n                    },\n                    \"self\": {\n                        \"href\": \"http://example.com/comments/1000\"\n                    }\n                }\n            }\n        ]\n    },\n    \"_links\": {\n        \"curies\": [\n            {\n                \"name\": \"example\",\n                \"href\": \"http://example.com/docs/rels/{rel}\",\n                \"templated\": true\n            }\n        ],\n        \"self\": {\n            \"href\": \"http://example.com/posts/9\"\n        },\n        \"next\": {\n            \"href\": \"http://example.com/posts/10\"\n        },\n        \"example:author\": {\n            \"href\": \"http://example.com/users/1\"\n        },\n        \"example:comments\": {\n            \"href\": \"http://example.com/posts/9/comments\"\n        }\n    },\n    \"_meta\": {\n        \"author\": [\n            {\n                \"name\": \"Nil Portugués Calderó\",\n                \"email\": \"contact@nilportugues.com\"\n            }\n        ]\n    }\n}\n```\n\n#### Response objects (HalJsonResponseTrait)\n\nThe following `HalJsonResponseTrait` methods are provided to return the right headers and HTTP status codes are available:\n\n```php\n    private function errorResponse($json);\n    private function resourceCreatedResponse($json);\n    private function resourceDeletedResponse($json);\n    private function resourceNotFoundResponse($json);\n    private function resourcePatchErrorResponse($json);\n    private function resourcePostErrorResponse($json);\n    private function resourceProcessingResponse($json);\n    private function resourceUpdatedResponse($json);\n    private function response($json);\n    private function unsupportedActionResponse($json);\n```    \n\n## Integration with NelmioApiDocBundleBundle\n\nThe [NelmioApiDocBundle](https://github.com/nelmio/NelmioApiDocBundle/blob/master/Resources/doc/index.md) is a very well known bundle used to document APIs. Integration with the current bundle is terrible easy. \n\nHere's an example following the `PostContoller::getPostAction()` provided before:\n\n```php\n\u003c?php\nnamespace AppBundle\\Controller;\n\nuse NilPortugues\\Symfony\\HalJsonBundle\\Serializer\\HalJsonResponseTrait;\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller;\n\nclass PostController extends Controller\n{\n    use HalJsonResponseTrait;\n\n    /**\n     * Get a Post by its identifier. Will return Post, Comments and User data.\n     *\n     * @Nelmio\\ApiDocBundle\\Annotation\\ApiDoc(\n     *  resource=true,\n     *  description=\"Get a Post by its unique id\",\n     * )\n     *\n     * @Symfony\\Component\\Routing\\Annotation\\Route(\"/post/{postId}\", name=\"get_post\")\n     * @Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Method({\"GET\"})\n     *\n     * @param $postId\n     * @return \\Symfony\\Component\\HttpFoundation\\Response\n     */\n    public function getPostAction($postId)\n    {\n        $post = $this-\u003eget('doctrine.post_repository')-\u003efind($postId);\n        \n        $serializer = $this-\u003eget('nil_portugues.serializer.hal_json_serializer');\n\n        /** @var \\NilPortugues\\Api\\Hal\\JsonTransformer $transformer */\n        $transformer = $serializer-\u003egetTransformer();\n        $transformer-\u003esetSelfUrl($this-\u003egenerateUrl('get_post', ['postId' =\u003e $postId], true));\n        $transformer-\u003esetNextUrl($this-\u003egenerateUrl('get_post', ['postId' =\u003e $postId+1], true));\n\n        return $this-\u003eresponse($serializer-\u003eserialize($post));\n    }\n} \n```\n\n\nAnd the recommended configuration to be added in `app/config/config.yml`\n\n```yml\n#app/config/config.yml\n\nnelmio_api_doc:\n  sandbox:\n        authentication:\n          name: access_token\n          delivery: http\n          type:     basic\n          custom_endpoint: false\n        enabled:  true\n        endpoint: ~\n        accept_type: ~\n        body_format:\n            formats: []\n            default_format: form\n        request_format:\n            formats:\n                json: application/hal+json\n            method: accept_header\n            default_format: json\n        entity_to_choice: false\n```        \n\n\n## Quality\n\nTo run the PHPUnit tests at the command line, go to the tests directory and issue phpunit.\n\nThis library attempts to comply with [PSR-1](http://www.php-fig.org/psr/psr-1/), [PSR-2](http://www.php-fig.org/psr/psr-2/), [PSR-4](http://www.php-fig.org/psr/psr-4/) and [PSR-7](http://www.php-fig.org/psr/psr-7/).\n\nIf you notice compliance oversights, please send a patch via [Pull Request](https://github.com/nilportugues/symfony-hal-json-transformer/pulls).\n\n\n## Contribute\n\nContributions to the package are always welcome!\n\n* Report any bugs or issues you find on the [issue tracker](https://github.com/nilportugues/symfony-hal-json-transformer/issues/new).\n* You can grab the source code at the package's [Git repository](https://github.com/nilportugues/symfony-hal-json-transformer).\n\n\n## Support\n\nGet in touch with me using one of the following means:\n\n - Emailing me at \u003ccontact@nilportugues.com\u003e\n - Opening an [Issue](https://github.com/nilportugues/symfony-hal-json-transformer/issues/new)\n\n\n## Authors\n\n* [Nil Portugués Calderó](http://nilportugues.com)\n* [The Community Contributors](https://github.com/nilportugues/symfony-hal-json-transformer/graphs/contributors)\n\n\n## License\nThe code base is licensed under the [MIT license](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Fsymfony-hal-json","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnilportugues%2Fsymfony-hal-json","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Fsymfony-hal-json/lists"}