{"id":13752930,"url":"https://github.com/nilportugues/php-hal","last_synced_at":"2025-04-30T14:42:13.492Z","repository":{"id":36350918,"uuid":"40655682","full_name":"nilportugues/php-hal","owner":"nilportugues","description":"HAL+JSON \u0026 HAL+XML API transformer outputting valid (PSR-7) API Responses.","archived":false,"fork":false,"pushed_at":"2018-09-16T00:34:36.000Z","size":78,"stargazers_count":30,"open_issues_count":3,"forks_count":5,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-30T17:05:37.984Z","etag":null,"topics":["api","hal","hal-json","json","microservice","microservices","php","php7","transformer","xml"],"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":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nilportugues.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-08-13T11:41:48.000Z","updated_at":"2022-02-12T06:37:44.000Z","dependencies_parsed_at":"2022-08-23T16:11:13.582Z","dependency_job_id":null,"html_url":"https://github.com/nilportugues/php-hal","commit_stats":null,"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-hal","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-hal/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-hal/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-hal/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nilportugues","download_url":"https://codeload.github.com/nilportugues/php-hal/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251722829,"owners_count":21633025,"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","hal-json","json","microservice","microservices","php","php7","transformer","xml"],"created_at":"2024-08-03T09:01:12.786Z","updated_at":"2025-04-30T14:42:13.464Z","avatar_url":"https://github.com/nilportugues.png","language":"PHP","readme":"# HAL+JSON \u0026 HAL+XML API Transformer\n\n[![Build Status](https://travis-ci.org/nilportugues/php-hal.svg)](https://travis-ci.org/nilportugues/php-hal) \n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/nilportugues/hal-transformer/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/nilportugues/hal-transformer/?branch=master)\n[![SensioLabsInsight](https://insight.sensiolabs.com/projects/e2a5a3b2-7097-4783-9912-0cbaadd0ed0e/mini.png)](https://insight.sensiolabs.com/projects/e2a5a3b2-7097-4783-9912-0cbaadd0ed0e)\n[![Latest Stable Version](https://poser.pugx.org/nilportugues/hal/v/stable)](https://packagist.org/packages/nilportugues/hal) \n[![Total Downloads](https://poser.pugx.org/nilportugues/hal/downloads)](https://packagist.org/packages/nilportugues/hal) \n[![License](https://poser.pugx.org/nilportugues/hal/license)](https://packagist.org/packages/nilportugues/hal) \n[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://paypal.me/nilportugues)\n\n1. [Installation](#1-installation)\n2. [Mapping](#2-mapping)\n    - 2.1 [Mapping with arrays](#21-mapping-with-arrays)\n    - 2.2 [Mapping with Mapping class](#22-mapping-with-mapping-class)\n3. [HAL Serialization](#3-hal-serialization)\n    - 3.1 [HAL+JSON](#31-haljson)\n    - 3.2 [HAL+XML](#32-halxml)\n4. [HAL Paginated Resource](#4-hal-paginated-resource)\n5. [PSR-7 Response objects](#5-response-objects)\n \n## 1. Installation\n\nUse [Composer](https://getcomposer.org) to install the package:\n\n```json\n$ composer require nilportugues/hal\n```\n\n## 2. Mapping\n\nGiven a PHP Object, and a series of mappings, the HAL+JSON and HAL+XML API transformer will represent the given data following the `https://tools.ietf.org/html/draft-kelly-json-hal-07` specification draft.\n\nFor instance, given the following piece of code, defining a Blog Post and some comments:\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\nWe will have to map all the involved classes. This can be done as one single array, or a series of Mapping classes.\n\n### 2.1 Mapping with arrays\n\nMapping involved classes using arrays is done as follows:\n\n\n```php\nuse NilPortugues\\Api\\Mapping\\Mapper;\n\n$mappings = [\n    [\n        'class' =\u003e Post::class,\n        'alias' =\u003e 'Message',\n        'aliased_properties' =\u003e [\n            'author' =\u003e 'author',\n            'title' =\u003e 'headline',\n            'content' =\u003e 'body',\n        ],\n        'hide_properties' =\u003e [\n\n        ],\n        'id_properties' =\u003e [\n            'postId',\n        ],\n        'urls' =\u003e [\n            // Mandatory\n            'self' =\u003e 'http://example.com/posts/{postId}',\n             // Optional\n            'comments' =\u003e 'http://example.com/posts/{postId}/comments'\n        ],\n        'curies' =\u003e [\n            'name' =\u003e 'example',\n            'href' =\u003e \"http://example.com/docs/rels/{rel}\",\n        ]\n    ],\n    [\n        'class' =\u003e User::class,\n        'alias' =\u003e '',\n        'aliased_properties' =\u003e [],\n        'hide_properties' =\u003e [],\n        'id_properties' =\u003e [\n            'userId',\n        ],\n        'urls' =\u003e [\n            'self' =\u003e 'http://example.com/users/{userId}',\n        ],\n        'curies' =\u003e [\n            'name' =\u003e 'example',\n            'href' =\u003e \"http://example.com/docs/rels/{rel}\",\n        ]\n    ],\n    [\n        'class' =\u003e Comment::class,\n        'alias' =\u003e '',\n        'aliased_properties' =\u003e [],\n        'hide_properties' =\u003e [],\n        'id_properties' =\u003e [\n            'commentId',\n        ],\n        'urls' =\u003e [\n            'self' =\u003e 'http://example.com/comments/{commentId}',\n        ],\n        'curies' =\u003e [\n            'name' =\u003e 'example',\n            'href' =\u003e \"http://example.com/docs/rels/{rel}\",\n        ]\n    ]\n];\n\n$mapper = new Mapper($mappings);\n```\n\n### 2.2 Mapping with Mapping class\n\nIn order to map with Mapping class, you need to create a new class for each involved class.\n\nThis mapping fashion scales way better than using an array.\n\nAll Mapping classes will extend the `\\NilPortugues\\Api\\Mappings\\HalMapping` interface. \n\n```php\n\n// PostMapping.php\n\nclass PostMapping implements \\NilPortugues\\Api\\Mappings\\HalMapping \n{\n    public function getClass()\n    {\n        return Post::class;\n    }\n\n    public function getAlias()\n    {\n        return 'Message';\n    }\n\n    public function getAliasedProperties()\n    {\n        return [\n           'author' =\u003e 'author',\n           'title' =\u003e 'headline',\n           'content' =\u003e 'body',\n       ];\n    }\n\n    public function getHideProperties()\n    {\n        return [];\n    }\n\n    public function getIdProperties()\n    {\n        return ['postId'];\n    }\n   \n    public function getUrls()\n    {\n        return [            \n            'self' =\u003e 'http://example.com/posts/{postId}', // Mandatory            \n            'comments' =\u003e 'http://example.com/posts/{postId}/comments' // Optional\n        ];\n    }\n\n    public function getCuries()\n    {\n        return [\n           'name' =\u003e 'example',\n           'href' =\u003e \"http://example.com/docs/rels/{rel}\",\n        ];\n    }\n}\n\n\n// UserMapping.php\n\nclass UserMapping implements \\NilPortugues\\Api\\Mappings\\HalMapping \n{\n    public function getClass()\n    {\n        return User::class;\n    }\n\n    public function getAlias()\n    {\n        return '';\n    }\n\n    public function getAliasedProperties()\n    {\n        return [];\n    }\n\n    public function getHideProperties()\n    {\n        return [];\n    }\n\n    public function getIdProperties()\n    {\n        return ['postId'];\n    }\n   \n    public function getUrls()\n    {\n        return [            \n            'self' =\u003e 'http://example.com/users/{userId}'\n        ];\n    }\n\n    public function getCuries()\n    {\n        return [\n           'name' =\u003e 'example',\n           'href' =\u003e \"http://example.com/docs/rels/{rel}\",\n        ];\n    }\n}\n\n\n// CommentMapping.php\n\nclass CommentMapping implements \\NilPortugues\\Api\\Mappings\\HalMapping \n{\n    public function getClass()\n    {\n        return Comment::class;\n    }\n\n    public function getAlias()\n    {\n        return '';\n    }\n\n    public function getAliasedProperties()\n    {\n        return [];\n    }\n\n    public function getHideProperties()\n    {\n        return [];\n    }\n\n    public function getIdProperties()\n    {\n        return ['commentId'];\n    }\n   \n    public function getUrls()\n    {\n        return [            \n            'self' =\u003e 'http://example.com/comments/{commentId}',\n        ];\n    }\n\n    public function getCuries()\n    {\n        return [\n           'name' =\u003e 'example',\n           'href' =\u003e \"http://example.com/docs/rels/{rel}\",\n        ];\n    }\n} \n\n$mappings = [\n    PostMapping::class,\n    UserMapping::class,\n    CommentMapping::class,\n];\n$mapper = new Mapper($mappings);\n\n```\n\n## 3. HAL Serialization\n\nCalling the transformer will output a **valid HAL response** using the correct formatting:\n\n```php\nuse NilPortugues\\Api\\Hal\\JsonTransformer; \nuse NilPortugues\\Api\\Hal\\HalSerializer;\nuse NilPortugues\\Api\\Hal\\Http\\Message\\Response;\n\n$transformer = new JsonTransformer($mapper);\n//For XML: $transformer = new XmlTransformer($mapper);\n\n//Output transformation\n$serializer = new HalSerializer($transformer);\n$output = $serializer-\u003eserialize($post);\n\n//PSR7 Response with headers and content.\n$response = new Response($output);\n\nheader(\n    sprintf(\n        'HTTP/%s %s %s',\n        $response-\u003egetProtocolVersion(),\n        $response-\u003egetStatusCode(),\n        $response-\u003egetReasonPhrase()\n    )\n);\n\nforeach($response-\u003egetHeaders() as $header =\u003e $values) {\n    header(sprintf(\"%s:%s\\n\", $header, implode(', ', $values)));\n}\n\necho $response-\u003egetBody();\n```\n\n### 3.1 HAL+JSON\n\n```\nHTTP/1.1 200 OK\nCache-Control: private, max-age=0, must-revalidate\nContent-type: application/hal+json\n```\nOutput: \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        \"example:author\": {\n            \"href\": \"http://example.com/users/1\"\n        },\n        \"example:comments\": {\n            \"href\": \"http://example.com/posts/9/comments\"\n        }\n    }\n}\n```\n\n\n### 3.2 HAL+XML\n\nFor XML output use the sample code but using the XML transformer instead: \n\n```\n$transformer = new XmlTransformer($mapper);\n```\n\nOutput:\n\n```\nHTTP/1.1 200 OK\nCache-Control: private, max-age=0, must-revalidate\nContent-type: application/hal+xml\n```\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cresource href=\"http://example.com/posts/9\"\u003e\n  \u003cpost_id\u003e\u003c![CDATA[9]]\u003e\u003c/post_id\u003e\n  \u003cheadline\u003e\u003c![CDATA[Hello World]]\u003e\u003c/headline\u003e\n  \u003cbody\u003e\u003c![CDATA[Your first post]]\u003e\u003c/body\u003e\n  \u003cembedded\u003e\n    \u003cresource href=\"http://example.com/users/1\" rel=\"author\"\u003e\n      \u003cuser_id\u003e\u003c![CDATA[1]]\u003e\u003c/user_id\u003e\n      \u003cname\u003e\u003c![CDATA[Post Author]]\u003e\u003c/name\u003e\n      \u003clinks\u003e\n        \u003clink rel=\"self\" href=\"http://example.com/users/1\"/\u003e\n        \u003clink rel=\"example:friends\" href=\"http://example.com/users/1/friends\"/\u003e\n        \u003clink rel=\"example:comments\" href=\"http://example.com/users/1/comments\"/\u003e\n      \u003c/links\u003e\n    \u003c/resource\u003e\n    \u003ccomments\u003e\n      \u003cresource href=\"http://example.com/comments/1000\"\u003e\n        \u003ccomment_id\u003e\u003c![CDATA[1000]]\u003e\u003c/comment_id\u003e\n        \u003cdates\u003e\n          \u003ccreated_at\u003e\u003c![CDATA[2015-07-18T12:13:00+00:00]]\u003e\u003c/created_at\u003e\n          \u003caccepted_at\u003e\u003c![CDATA[2015-07-19T00:00:00+00:00]]\u003e\u003c/accepted_at\u003e\n        \u003c/dates\u003e\n        \u003ccomment\u003e\u003c![CDATA[Have no fear, sers, your king is safe.]]\u003e\u003c/comment\u003e\n        \u003cembedded\u003e\n          \u003cresource href=\"http://example.com/users/2\" rel=\"user\"\u003e\n            \u003cuser_id\u003e\u003c![CDATA[2]]\u003e\u003c/user_id\u003e\n            \u003cname\u003e\u003c![CDATA[Barristan Selmy]]\u003e\u003c/name\u003e\n            \u003clinks\u003e\n              \u003clink rel=\"self\" href=\"http://example.com/users/2\"/\u003e\n              \u003clink rel=\"example:friends\" href=\"http://example.com/users/2/friends\"/\u003e\n              \u003clink rel=\"example:comments\" href=\"http://example.com/users/2/comments\"/\u003e\n            \u003c/links\u003e\n          \u003c/resource\u003e\n        \u003c/embedded\u003e\n        \u003clinks\u003e\n          \u003clink rel=\"example:user\" href=\"http://example.com/users/2\"/\u003e\n          \u003clink rel=\"self\" href=\"http://example.com/comments/1000\"/\u003e\n        \u003c/links\u003e\n      \u003c/resource\u003e\n    \u003c/comments\u003e\n  \u003c/embedded\u003e\n  \u003clinks\u003e\n    \u003ccuries\u003e\n      \u003clink rel=\"resource\" href=\"http://example.com/docs/rels/{rel}\"\u003e\n        \u003cname\u003e\u003c![CDATA[example]]\u003e\u003c/name\u003e\n        \u003ctemplated\u003e\u003c![CDATA[true]]\u003e\u003c/templated\u003e\n      \u003c/link\u003e\n    \u003c/curies\u003e\n    \u003clink rel=\"self\" href=\"http://example.com/posts/9\"/\u003e\n    \u003clink rel=\"example:author\" href=\"http://example.com/users/1\"/\u003e\n    \u003clink rel=\"example:comments\" href=\"http://example.com/posts/9/comments\"/\u003e\n  \u003c/links\u003e\n\u003c/resource\u003e\n```\n\n## 4. HAL Paginated Resource\n\nA pagination object to easy the usage of this package is provided. \n\nFor both XML and JSON output, use the `HalPagination` object to build your paginated representation of the current resource.\n \nMethods provided by `HalPagination` are as follows: \n\n - `setSelf($self)`\n - `setFirst($first)`\n - `setPrev($prev)`\n - `setNext($next)`\n - `setLast($last)`\n - `setCount($count)`\n - `setTotal($total)`\n - `setEmbedded(array $embedded)`\n \nIn order to use it, create a new HalPagination instance, use the setters and pass the instance to the `serialize($value)` method of the serializer. \n\nEverything else will be handled by serializer itself. Easy as that!\n \n```php\nuse NilPortugues\\Api\\Hal\\HalPagination; \nuse NilPortugues\\Api\\Hal\\HalSerializer; \nuse NilPortugues\\Api\\Hal\\JsonTransformer; \n\n// ...\n//$objects is an array of objects, such as Post::class.\n// ...\n \n$page = new HalPagination();\n\n//set the amounts\n$page-\u003esetTotal(20);\n$page-\u003esetCount(10);\n\n//set the objects\n$page-\u003esetEmbedded($objects);\n\n//set up the pagination links\n$page-\u003esetSelf('/post?page=1');\n$page-\u003esetPrev('/post?page=1');\n$page-\u003esetFirst('/post?page=1');\n$page-\u003esetLast('/post?page=1');\n\n$output = $serializer-\u003eserialize($page);\n\n``` \n\n## 5. Response objects\n\nThe following PSR-7 Response objects providing the right headers and HTTP status codes are available.\n\nIts use is optional and are provided as a starting point.\n\n- `NilPortugues\\Api\\Hal\\Http\\Message\\ErrorResponse($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\ResourceCreatedResponse($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\ResourceDeletedResponse($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\ResourceNotFoundResponse($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\ResourcePatchErrorResponse($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\ResourcePostErrorResponse($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\ResourceProcessingResponse($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\ResourceUpdatedResponse($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\Response($body)`\n- `NilPortugues\\Api\\Hal\\Http\\Message\\UnsupportedActionResponse($body)`\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/hal-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/php-hal/issues/new).\n* You can grab the source code at the package's [Git repository](https://github.com/nilportugues/php-hal).\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/php-hal/issues/new)\n\n## Authors\n\n* [Nil Portugués Calderó](http://nilportugues.com)\n* [The Community Contributors](https://github.com/nilportugues/php-hal/graphs/contributors)\n\n\n## License\nThe code base is licensed under the [MIT license](LICENSE).\n","funding_links":["https://paypal.me/nilportugues"],"categories":["transformer"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Fphp-hal","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnilportugues%2Fphp-hal","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Fphp-hal/lists"}