Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.35% covered (warning)
82.35%
28 / 34
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Render
82.35% covered (warning)
82.35%
28 / 34
0.00% covered (danger)
0.00%
0 / 2
7.27
0.00% covered (danger)
0.00%
0 / 1
 __construct
92.86% covered (success)
92.86%
26 / 28
0.00% covered (danger)
0.00%
0 / 1
4.01
 __toString
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
5.67
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Finder;
6
7use Celema\Core\Exception\HttpBadRequest;
8use Cosray\Bootstrap;
9use Cosray\Cms;
10use Cosray\Context;
11use Cosray\Exception\RuntimeException;
12use Cosray\Node\Factory;
13use Cosray\Node\Types;
14use Cosray\Node\View;
15use Throwable;
16
17class Render
18{
19    protected object $node;
20
21    public function __construct(
22        private readonly Context $context,
23        private readonly Cms $cms,
24        private readonly Factory $nodeFactory,
25        private readonly Types $types,
26        string $id,
27        private readonly array $templateContext = [],
28        ?bool $deleted = false,
29        ?bool $published = true,
30    ) {
31        $data = $this->context
32            ->db
33            ->nodes
34            ->find([
35                'handle' => $id,
36                'published' => $published,
37                'deleted' => $deleted,
38            ])
39            ->first() ?: $this->context
40            ->db
41            ->nodes
42            ->find([
43                'uid' => $id,
44                'published' => $published,
45                'deleted' => $deleted,
46            ])
47            ->first();
48
49        if (!$data) {
50            throw new RuntimeException('Renderable node not found: ' . $id);
51        }
52        $class = $this->context
53            ->container
54            ->tag(Bootstrap::NODE_TAG)
55            ->entry($data['type_handle'])
56            ->definition();
57
58        if (!(bool) $this->types->get($class, 'renderable', false)) {
59            throw new RuntimeException('Invalid renderable node class ' . $class);
60        }
61
62        $data['content'] = json_decode($data['content'], true);
63        $this->node = $this->nodeFactory->create($class, $context, $cms, $data);
64    }
65
66    public function __toString(): string
67    {
68        try {
69            return new View($this->node, $this->cms, $this->context, $this->types)
70                ->output($this->templateContext);
71        } catch (Throwable $e) {
72            if ($this->context->config->debug()) {
73                throw $e;
74            }
75
76            throw new HttpBadRequest($this->context->request, previous: $e);
77        }
78    }
79}