-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathTimberResponse.php
More file actions
37 lines (30 loc) · 1.31 KB
/
TimberResponse.php
File metadata and controls
37 lines (30 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
namespace Rareloop\Lumberjack\Http\Responses;
use Illuminate\Contracts\Support\Arrayable as CollectionArrayable;
use Rareloop\Lumberjack\Contracts\Arrayable;
use Rareloop\Lumberjack\Exceptions\TwigTemplateNotFoundException;
use Timber\Timber;
use Laminas\Diactoros\Response\HtmlResponse;
class TimberResponse extends HtmlResponse
{
public function __construct($twigTemplate, $context, $status = 200, array $headers = [])
{
$template = Timber::compile($twigTemplate, $this->flattenContextToArrays($context));
if ($template === false) {
throw new TwigTemplateNotFoundException($twigTemplate);
}
parent::__construct($template, $status, $headers);
}
private function flattenContextToArrays(array $context) : array
{
// Recursively walk the array, when we find something that implements the Arrayable interface
// flatten it to an array. Because we're passing by reference by updating what the value of
// $item is will mutate the original data structure passed in.
array_walk_recursive($context, function (&$item, $key) {
if ($item instanceof Arrayable || $item instanceof CollectionArrayable) {
$item = $this->flattenContextToArrays($item->toArray());
}
});
return $context;
}
}