Completed
Pull Request — 1.x (#5)
by Akihito
15:19 queued 05:44
created

Ssr::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * This file is part of the BEAR.SsrModule package.
6
 *
7
 * @license http://opensource.org/licenses/MIT MIT
8
 */
9
namespace BEAR\SsrModule;
10
11
use BEAR\Resource\RenderInterface;
12
use BEAR\Resource\ResourceObject;
13
use BEAR\SsrModule\Exception\MetaKeyNotExistsException;
14
use BEAR\SsrModule\Exception\StatusKeyNotExistsException;
15
use Koriym\Baracoa\BaracoaInterface;
16
17
final class Ssr implements RenderInterface
18
{
19
    /**
20
     * @var BaracoaInterface
21
     */
22
    private $baracoa;
23
24
    /**
25
     * @var string
26
     */
27
    private $appName;
28
29
    /**
30
     * @var array
31
     */
32
    private $stateKeys;
33
34
    /**
35
     * @var array
36
     */
37
    private $metaKeys;
38
39
    /**
40
     * @param BaracoaInterface $baracoa
41
     */
42
    public function __construct(BaracoaInterface $baracoa, string $appName, array $stateKeys = [], array $metasKeys = [])
43
    {
44
        $this->baracoa = $baracoa;
45
        $this->appName = $appName;
46
        $this->stateKeys = $stateKeys;
47
        $this->metaKeys = $metasKeys;
48
    }
49
50
    public function render(ResourceObject $ro)
51
    {
52
        $state = $this->filter($this->stateKeys, (array) $ro->body, StatusKeyNotExistsException::class);
53
        $metas = $this->filter($this->metaKeys, (array) $ro->body, MetaKeyNotExistsException::class);
54
        $html = $this->baracoa->render($this->appName, $state, $metas);
55
        $ro->view = $html;
56
57
        return $html;
58
    }
59
60
    private function filter(array $keys, array $body, string $exception) : array
61
    {
62
        if ($keys === ['*']) {
63
            return $body;
64
        }
65
        $errorKeys = array_diff(array_values($keys), array_keys($body));
66
        if ($errorKeys) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errorKeys of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
67
            throw new $exception(implode(',', $errorKeys));
68
        }
69
        $filterd = array_filter((array) $body, function ($key) use ($keys) {
70
            return in_array($key, $keys, true);
71
        }, ARRAY_FILTER_USE_KEY);
72
73
        return $filterd;
74
    }
75
}
76