Skip to content

Commit 2a5a904

Browse files
committed
Added JsonSerializable to Layout (frontend serialization)
1 parent 3b2fcb8 commit 2a5a904

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/Layout.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,14 @@
33
namespace Whitecube\LaravelFlexibleContent;
44

55
use ArrayAccess;
6+
use JsonSerializable;
67
use Illuminate\Support\Str;
78
use Illuminate\Contracts\Support\Arrayable;
89
use Illuminate\Database\Eloquent\Concerns\HasAttributes;
910
use Illuminate\Database\Eloquent\Concerns\HidesAttributes;
1011
use Whitecube\LaravelFlexibleContent\Contracts\Layout as LayoutInterface;
1112

12-
class Layout implements LayoutInterface, ArrayAccess, Arrayable
13+
class Layout implements LayoutInterface, ArrayAccess, JsonSerializable, Arrayable
1314
{
1415
use HasAttributes;
1516
use HidesAttributes;
@@ -268,4 +269,19 @@ public function toArray()
268269
{
269270
return $this->attributesToArray();
270271
}
272+
273+
/**
274+
* Transform layout for front-end serialization (AJAX requests usage).
275+
* This method should most probably be extended for proper exploitation.
276+
*
277+
* @return array
278+
*/
279+
public function jsonSerialize()
280+
{
281+
return [
282+
'key' => $this->getKey(),
283+
'id' => $this->getId(),
284+
'limit' => $this->getLimit(),
285+
];
286+
}
271287
}

tests/Unit/LayoutManipulationTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,19 @@
5858
expect($converted['test'])->toBeTrue();
5959
expect($converted['something'])->toBeFalse();
6060
});
61+
62+
it('can convert layout to a JSON response object (for its frontend use)', function() {
63+
$layout = (new Layout())->key('foo')->make(null, ['test' => true, 'something' => false]);
64+
65+
$converted = json_decode(json_encode($layout), true);
66+
67+
expect($converted)->toBeArray();
68+
expect($converted['key'])->toBe('foo');
69+
expect(array_key_exists('id', $converted))->toBeTrue();
70+
expect(array_key_exists('limit', $converted))->toBeTrue();
71+
72+
// In this package, we do not include the layout's attributes in its JSON structure
73+
// since they should probably be manipulated by the extending flexible container. It is
74+
// up to the developer to decide if attributes should be sent to the view.
75+
expect(array_key_exists('attributes', $converted))->toBeFalse();
76+
});

0 commit comments

Comments
 (0)