Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add response() method #75

Merged
merged 11 commits into from
Jan 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 43 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use League\Fractal\Manager;
use League\Fractal\Resource\Collection;

$books = [
['id'=>1, 'title'=>'Hogfather', 'characters' => [...]],
['id'=>1, 'title'=>'Hogfather', 'characters' => [...]],
['id'=>2, 'title'=>'Game Of Kill Everyone', 'characters' => [...]]
];

Expand Down Expand Up @@ -52,7 +52,7 @@ There's also a very short syntax available to quickly transform data:
fractal($books, new BookTransformer())->toArray();
```

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all
our open source projects [on our website](https://spatie.be/opensource).

## Postcardware
Expand Down Expand Up @@ -91,7 +91,7 @@ If you want to make use of the facade you must install it as well:
];
```

If you want to [change the default serializer](https://github.com/spatie/laravel-fractal#changing-the-default-serializer),
If you want to [change the default serializer](https://github.com/spatie/laravel-fractal#changing-the-default-serializer),
you must publish the config file:

```bash
Expand Down Expand Up @@ -125,6 +125,46 @@ Refer to [the documentation of `spatie/fractalistic`](https://github.com/spatie/

In all code examples you may use `fractal()` instead of `Fractal::create()`.

## Send a response with transformed data

To return a response with json data you can to this in a Laravel app.

```php

$books = fractal($books, new BookTransformer())->toArray();

return response()->json($books);
```

The `response()` method on the Fractal class can make this process a bit more streamlined.

```php
return fractal($books, new BookTransformer())->respond();
```

You can pass a response code as the first parameter and optional some headers as the second

```php
return fractal($books, new BookTransformer())->respond(403, [
'a-header' => 'a value',
'another-header => 'another value',
]);
```

You can also set the status code and the headers useing a callback:

```php
return fractal($books, new BookTransformer())->respond(function(Reponse $response) {
$response
->setStatusCode(433)
->header('a-header', 'a value')
->headers([
'another-header => 'another value',
'yet-another-header => 'yet another value',
]);
});
```

## Quickly creating a transformer

You can run the `make:transformer` command to quickly generate a dummy transformer. By default it will be stored in the `app\Transformers` directory.
Expand Down
52 changes: 52 additions & 0 deletions src/Fractal.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace Spatie\Fractal;

use League\Fractal\Manager;
use Spatie\Fractalistic\Fractal as Fractalistic;

class Fractal extends Fractalistic
{
/** @param \League\Fractal\Manager $manager */
public function __construct(Manager $manager)
{
parent::__construct($manager);
}

/**
* Return a new JSON response.
*
* @param callable|int $statusCode
* @param callabel|array $headers
*
* @return \Illuminate\Http\JsonResponse
*/
public function respond($statusCode = 200, $headers = [])
{
$response = new Response();

$response->setData($this->createData()->toArray());

if (is_int($statusCode)) {
$statusCode = function (Response $response) use ($statusCode) {
return $response->setStatusCode($statusCode);
};
}

if (is_array($headers)) {
$headers = function (Response $response) use ($headers) {
return $response->headers($headers);
};
}

if (is_callable($statusCode)) {
$statusCode($response);
}

if (is_callable($headers)) {
$headers($response);
}

return $response;
}
}
1 change: 0 additions & 1 deletion src/FractalServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Spatie\Fractal;

use Spatie\Fractalistic\Fractal;
use Illuminate\Support\ServiceProvider;
use League\Fractal\Serializer\SerializerAbstract;
use Spatie\Fractal\Console\Commands\TransformerMakeCommand;
Expand Down
24 changes: 24 additions & 0 deletions src/Response.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace Spatie\Fractal;

use Illuminate\Http\JsonResponse;

class Response extends JsonResponse
{
/**
* Set multiple headers at once.
*
* @param array $headers
*
* @return self
*/
public function headers($headers)
{
foreach ($headers as $key => $value) {
$this->header($key, $value);
}

return $this;
}
}
4 changes: 2 additions & 2 deletions src/helpers.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

use Spatie\Fractalistic\Fractal;
use Spatie\Fractal\Fractal;
use League\Fractal\Serializer\SerializerAbstract;

if (! function_exists('fractal')) {
Expand All @@ -9,7 +9,7 @@
* @param null|callable|\League\Fractal\TransformerAbstract $transformer
* @param null|\League\Fractal\Serializer\SerializerAbstract $serializer
*
* @return \Spatie\Fractalistic\Fractal
* @return \Spatie\Fractal\Fractal
*/
function fractal($data = null, $transformer = null, $serializer = null)
{
Expand Down
131 changes: 131 additions & 0 deletions tests/ResponseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?php

namespace Spatie\Fractal\Test;

use Spatie\Fractal\Response;
use Illuminate\Http\JsonResponse;

class ResponseTest extends TestCase
{
/** @var \Spatie\Fractal\Fractal */
protected $fractal;

public function setUp($defaultSerializer = '')
{
parent::setUp();

$this->fractal = fractal()
->collection(['item', 'item2'])
->transformWith(function ($item) {
return $item.'-transformed';
});
}

/** @test */
public function it_can_return_a_json_response()
{
$response = $this->fractal->respond();

$this->assertInstanceOf(JsonResponse::class, $response);
$this->assertEquals('{"data":["item-transformed","item2-transformed"]}', json_encode($response->getData()));
$this->assertEquals(200, $response->status());
}

/** @test */
public function it_uses_the_given_response_code()
{
$response = $this->fractal->respond(404);

$this->assertEquals(404, $response->status());
}

/** @test */
public function it_uses_the_given_headers()
{
$response = $this->fractal
->respond(404, [
'test' => 'test-value',
'test2' => 'test2-value',
]);

$this->assertArraySubset([
'test' => ['test-value'],
'test2' => ['test2-value'],
], $response->headers->all());
}

/** @test */
public function it_accepts_a_status_code_in_the_given_closure()
{
$response = $this->fractal
->respond(function (Response $response) {
$response->setStatusCode(404);
});

$this->assertEquals(404, $response->status());
}

/** @test */
public function it_accepts_a_headers_in_the_given_closure()
{
$response = $this->fractal
->respond(function (Response $response) {
$response->header('test', 'test-value');
$response->headers(['test2' => 'test2-value']);
});

$this->assertArraySubset([
'test' => ['test-value'],
'test2' => ['test2-value'],
], $response->headers->all());
}

/** @test */
public function it_accept_a_response_code_and_a_callback()
{
$response = $this->fractal
->respond(404, function (Response $response) {
$response->header('test', 'test-value');
});

$this->assertEquals(404, $response->status());
$this->assertArraySubset([
'test' => ['test-value'],
], $response->headers->all());
}

/** @test */
public function all_allowed_methods_in_the_callback_are_chainable()
{
$response = $this->fractal
->respond(function (Response $response) {
$response
->header('test', 'test-value')
->setStatusCode(404)
->headers([
'test3' => 'test3-value',
'test4' => 'test4-value',
])
->header('test2', 'test2-value');
});

$this->assertArraySubset([
'test' => ['test-value'],
'test2' => ['test2-value'],
'test3' => ['test3-value'],
'test4' => ['test4-value'],
], $response->headers->all());

$this->assertEquals(404, $response->status());
}

/** @test */
public function the_status_code_set_in_the_closure_will_be_used_event_when_passing_a_status_code_to_the_respond_method()
{
$response = $this->fractal->respond(200, function (Response $response) {
$response->setStatusCode(300);
});

$this->assertEquals(300, $response->getStatusCode());
}
}
1 change: 0 additions & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Spatie\Fractal\Test;

use Spatie\Fractal\Fractal;
use Spatie\Fractal\FractalServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;

Expand Down