8000 [Feature] Add global helpers · startupengine/laravel-json-api@60a64a2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 60a64a2

Browse files
committed
[Feature] Add global helpers
1 parent cc12581 commit 60a64a2

File tree

17 files changed

+445
-110
lines changed

17 files changed

+445
-110
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ All notable changes to this project will be documented in this file. This projec
77
### Added
88
- The resource registrar now automatically adds a JSON API's route prefix.
99
- Can now send JSON API requests using a Guzzle client.
10+
- Can now obtain a JSON API instance using the `json_api()` global helper.
11+
- Can now obtain the JSON API request instance using the `json_api_request()` global helper.
1012

1113
### Changed
1214
- Tests helpers are no longer in the Browser Kit testing style, and instead use a `TestResponse` class that extends

composer.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@
4343
"autoload": {
4444
"psr-4": {
4545
"CloudCreativity\\LaravelJsonApi\\": "src/"
46-
}
46+
},
47+
"files": [
48+
"helpers.php"
49+
]
4750
},
4851
"autoload-dev": {
4952
"psr-4": {

docs/features/helpers.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Helpers
2+
3+
## Introduction
4+
5+
Laravel provides a number of global [helper PHP functions](https://laravel.com/docs/helpers). This package
6+
provides some additional helpers that allow you to manually use capabilities within the package.
7+
8+
## Global Helpers
9+
10+
### `json_api()`
11+
12+
Called without any arguments, this return the JSON API instance that is handling the inbound HTTP request. An API
13+
is registered as handling an inbound request within any JSON API registered route.
14+
15+
If there is no API handling the inbound request, then an exception will be thrown if this helper is called
16+
without any arguments. If you are using this helper outside of a JSON API route, you will need to provide the
17+
name of the API to use. Generally you will need to do this if using the helper within any queued jobs.
18+
19+
For example:
20+
21+
```php
22+
// the API handling the inbound HTTP request...
23+
$api = json_api();
24+
// the API named 'v1'
25+
$api = json_api('v1');
26+
```
27+
28+
See [below](#api-helpers) for helper methods on API instances.
29+
30+
### `json_api_request()`
31+
32+
This will return the JSON API request instance, or `null` if there is no inbound HTTP request.
33+
34+
## API Helpers
35+
36+
The following helpers methods are available on the API instances.
37+
38+
### `encoder()`
39+
40+
Gets an encoder that is configured with the API's details. This can be used to manually serialize data to arrays, or
41+
encode data to strings. For example:
42+
43+
```php
44+
// ['data' => ['type' => 'posts', 'id' => '1', 'attributes' => ['content' => 'Hello World']]]
45+
$data = json_api('v1')->encoder()->serializeData($post);
46+
// {"data": {"type": "posts", "id": "1", "attributes": {"content": "Hello World"}}}
47+
echo json_api('v1')->encoder()->encodeData($post);
48+
```
49+
50+
The `encoder()` method takes two arguments - options and depth. Both of these are identical to the options and
51+
depth arguments in PHP's native `json_encode()` method.
52+
53+
```php
54+
// output a pretty-printed JSON string...
55+
echo json_api('v1')->encoder(JSON_PRETTY_PRINT)->encodeData($post);
56+
```
57+
58+
### `client()`
59+
60+
This helper returns a HTTP client for [sending JSON API requests](./sending-requests/) to remote servers. You
61+
must provide a Guzzle client as the first argument:
62+
63+
```php
64+
$guzzleClient = new GuzzleHttp\Client(['base_uri' => 'http://example.com/api/']);
65+
$client = json_api('v1')->client($guzzleClient);
66+
```

docs/features/sending-requests.md

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,15 @@ within your own application. You can fully control where requests are sent using
3535

3636
## Creating Clients
3737

38-
You can create a JSON API client using the `client()` method as follows:
38+
You can create a JSON API client using via the `json_api()` helper method as follows:
3939

4040
```php
4141
$guzzleClient = new GuzzleHttp\Client(['base_uri' => 'http://example.com/api/']);
42-
$client = JsonApi::client($guzzleClient);
42+
$client = json_api('v1')->client($guzzleClient);
4343
```
4444

45-
This will create a client for the `default` API. You can create a client for a specific API using:
46-
47-
```php
48-
$client = JsonApi::client($guzzleClient, 'external');
49-
```
50-
51-
The Guzzle client **must** be provided with a `base_uri` option, as the JSON API client submits requests relative to
52-
the base URI.
45+
This creates a client based on the configuration for your `v1` JSON API. The Guzzle client **must** be provided
46+
with a `base_uri` option, as the JSON API client submits requests relative to the base URI.
5347

5448
## Resource Requests
5549

docs/features/views.md

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Encoding in Views
2+
3+
## Introduction
4+
5+
Sometimes it is necessary to encode JSON API resources into an HTML document. For example, you might want to
6+
pre-load data into a page for your Javascript components to use. This package provides Blade helpers to do this,
7+
plus there are also instructions below on how to do this in regular PHP view files.
8+
9+
## Blade
10+
11+
### Choosing An Encoder
12+
13+
You can set the encoder to use with the `@jsonapi` directive. For example, `@jsonapi('v1')` will use an encoder
14+
from your JSON API named `v1`.
15+
16+
You can also configure the encoding options using the second argument, and the encoding depth using the third.
17+
The options and depth are identical to the options and depth passed to the native PHP `json_encode()` function.
18+
For example:
19+
20+
```html
21+
@jsonapi('v1', JSON_PRETTY_PRINT, 250)
22+
```
23+
24+
Note that if you do not call the `@jsonapi` directive in your templates, then the JSON API named `default` will be
25+
used.
26+
27+
### Encoding Data
28+
29+
To encode in Blade templates, use the `@encode` directive. For example:
30+
31+
```html
32+
@jsonapi('v1', JSON_PRETTY_PRINT)
33+
<script type="application/vnd.api+json">
34+
@encode($post)
35+
</script>
36+
```
37+
38+
This will output:
39+
40+
```html
41+
<script type="application/vnd.api+json">
42+
{
43+
"data": {
44+
"type": "posts",
45+
"id": "1",
46+
"attributes": {
47+
"content": "Hello World"
48+
},
49+
"relationships": {
50+
"author": {
51+
"data": {
52+
"type": "users",
53+
"id": "2"
54+
}
55+
}
56+
}
57+
}
58+
}
59+
</script>
60+
```
61+
62+
The `@encode` directive takes two additional arguments - the `include` paths and the `fields` to encode. The
63+
include paths can be a string or an array of strings. The fields must be an array keyed by resource type, with the
64+
value being an array of fields to encode.
65+
66+
```html
67+
@jsonapi('v1', JSON_PRETTY_PRINT)
68+
<script type="application/vnd.api+json">
69+
@encode($post, 'author', ['author' => ['name']])
70+
</script>
71+
```
72+
73+
This will output:
74+
75+
```html
76+
<script type="application/vnd.api+json">
77+
{
78+
"data": {
79+
"type": "posts",
80+
"id": "1",
81+
"attributes": {
82+
"content": "Hello World"
83+
},
84+
"relationships": {
85+
"author": {
86+
"data": {
87+
"type": "users",
88+
"id": "2"
89+
}
90+
}
91+
}
92+
},
93+
"include": [
94+
{
95+
"type": "users",
96+
"id": "2",
97+
"attributes": {
98+
"name": "Frankie Manning"
99+
}
100+
}
101+
]
102+
}
103+
</script>
104+
```
105+
106+
## Non-Blade
107+
108+
If you are not using Blade, you can still use the same functionality in your PHP view scripts. To choose an
109+
encoder:
110+
111+
```php
112+
<?php app('json-api.renderer')->with('v1', JSON_PRETTY_PRINT); ?>
113+
```
114+
115+
And then to encode data:
116+
117+
```php
118+
<?php echo app('json-api.renderer')->encode($post, 'author'); ?>
119+
```

helpers.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
/**
4+
* Copyright 2017 Cloud Creativity Limited
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
if (!function_exists('json_api')) {
20+
/**
21+
* Get the API handling the inbound request, or a named API.
22+
*
23+
* @param string|null $apiName
24+
* the API name, or null to get the API handling the inbound request.
25+
* @return \CloudCreativity\LaravelJsonApi\Api\Api
26+
* @throws \CloudCreativity\JsonApi\Exceptions\RuntimeException
27+
*/
28+
function json_api($apiName = null) {
29+
/** @var \CloudCreativity\LaravelJsonApi\Services\JsonApiService $service */
30+
$service = app('json-api');
31+
32+
return $apiName ? $service->api($apiName) : $service->requestApiOrFail();
33+
}
34+
35+
/**
36+
* Get the inbound JSON API request.
37+
*
38+
* @return \CloudCreativity\JsonApi\Contracts\Http\Requests\RequestInterface|null
39+
*/
40+
function json_api_request() {
41+
/** @var \CloudCreativity\LaravelJsonApi\Services\JsonApiService $service */
42+
$service = app('json-api');
43+
44+
return $service->request();
45+
}
46+
}

mkdocs.yml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,6 @@ pages:
1616
- Non-Eloquent:
1717
- Controllers: custom/controllers.md
1818
- Digging Deeper:
19-
- Sending Requests: features/sending-requests.md
19+
- Helpers: features/helpers.md
20+
- HTTP Clients: features/sending-requests.md
21+
- Views: features/views.md

src/Api/Api.php

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
* Class Api
3838
*
3939
* @package CloudCreativity\LaravelJsonApi
40-
* @todo make this final as it is not intended to be overwritten.
4140
*/
4241
class Api
4342
{
@@ -288,7 +287,7 @@ public function getEncoder()
288287
return $encoder;
289288
}
290289

291-
$this->getCodecMatcher()->setEncoder($encoder = $this->createEncoder());
290+
$this->getCodecMatcher()->setEncoder($encoder = $this->encoder());
292291

293292
return $encoder;
294293
}
@@ -298,32 +297,21 @@ public function getEncoder()
298297
* @param int $depth
299298
* @return SerializerInterface
300299
*/
301-
public function createEncoder($options = 0, $depth = 512)
300+
public function encoder($options = 0, $depth = 512)
302301
{
303302
$options = new EncoderOptions($options, (string) $this->getUrl(), $depth);
304303

305304
return $this->factory->createEncoder($this->getSchemas(), $options);
306305
}
307306

308-
/**
309-
* @return ValidatorFactoryInterface
310-
*/
311-
public function createValidators()
312-
{
313-
return $this->factory->createValidatorFactory(
314-
$this->getErrors(),
315-
$this->getStore()
316-
);
317-
}
318-
319307
/**
320308
* Create a responses helper for this API.
321309
*
322310
* @param EncodingParametersInterface|null $parameters
323311
* @param SupportedExtensionsInterface|null $extensions
324312
* @return Responses
325313
*/
326-
public function createResponse(
314+
public function response(
327315
EncodingParametersInterface $parameters = null,
328316
SupportedExtensionsInterface $extensions = null
329317
) {
@@ -341,9 +329,20 @@ public function createResponse(
341329
* @param $httpClient
342330
* @return ClientInterface
343331
*/
344-
public function createClient($httpClient)
332+
public function client($httpClient)
345333
{
346-
return $this->factory->createClient($httpClient, $this->getSchemas(), $this->createEncoder());
334+
return $this->factory->createClient($httpClient, $this->getSchemas(), $this->encoder());
335+
}
336+
337+
/**
338+
* @return ValidatorFactoryInterface
339+
*/
340+
public function validators()
341+
{
342+
return $this->factory->createValidatorFactory(
343+
$this->getErrors(),
344+
$this->getStore()
345+
);
347346
}
348347

349348
/**

src/Broadcasting/BroadcastsData.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,15 @@ trait BroadcastsData
3434
*/
3535
protected function broadcastApi()
3636
{
37-
return property_exists($this, 'broadcastApi') ? $this->broadCastApi : 'default';
37+
return property_exists($this, 'broadcastApi') ? $this->broadcastApi : 'default';
3838
}
3939

4040
/**
4141
* @return SerializerInterface
4242
*/
4343
protected function broadcastEncoder()
4444
{
45-
return app('json-api')->encoder($this->broadcastApi());
45+
return json_api($this->broadcastApi())->encoder();
4646
}
4747

4848
/**

src/Exceptions/HandlesErrors.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ public function renderJsonApi(Request $request, Exception $e)
6565

6666
return $service
6767
->requestApi()
68-
->createResponse()
68+
->response()
6969
->errors($response);
7070
}
7171

0 commit comments

Comments
 (0)
0