CacheBaracoa::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
/**
3
 * This file is part of the Koriym.Baracoa package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace Koriym\Baracoa;
8
9
use Koriym\Baracoa\Exception\JsFileNotExistsException;
10
use Psr\SimpleCache\CacheInterface;
11
use V8Js;
12
13
final class CacheBaracoa implements BaracoaInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    private $bundleSrcBasePath;
19
20
    /**
21
     * @var CacheInterface
22
     */
23
    private $cache;
24
25
    /**
26
     * @var ExceptionHandlerInterface
27
     */
28
    private $handler;
29
30 5
    public function __construct(string $bundleSrcBasePath, ExceptionHandlerInterface $handler, CacheInterface $cache)
31
    {
32 5
        $this->bundleSrcBasePath = $bundleSrcBasePath;
33 5
        $this->handler = $handler;
34 5
        $this->cache = $cache;
35 5
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 4
    public function render(string $appName, array $store, array $metas = []) : string
41
    {
42 4
        if (! $this->cache->has($appName)) {
43 4
            $this->saveSnapshot($appName);
44
        }
45 2
        $snapShot = $this->cache->get($appName);
46 2
        $v8 = new V8Js('PHP', [], [], true, $snapShot);
47
        try {
48 2
            $html = $v8->executeString($this->getSsrCode($store, $metas));
49
        } catch (\V8JsScriptException $e) {
50
            $handler = $this->handler;
51
            $html = $handler($e);
52
        }
53
54 2
        return $html;
55
    }
56
57
    /**
58
     * @param string $appName
59
     */
60 4
    private function saveSnapshot(string $appName) : void
61
    {
62 4
        $bundleSrcPath = sprintf('%s/%s.bundle.js', $this->bundleSrcBasePath, $appName);
63 4
        if (! file_exists($bundleSrcPath)) {
64 1
            throw new JsFileNotExistsException($bundleSrcPath);
65
        }
66 3
        $bundleSrc = file_get_contents($bundleSrcPath);
67 3
        $snapShot = \V8Js::createSnapshot($bundleSrc);
68 2
        $this->cache->set($appName, $snapShot);
69 2
    }
70
71 2
    private function getSsrCode(array $store, array $metas) : string
72
    {
73 2
        $storeJson = json_encode($store);
74 2
        $metasJson = json_encode($metas);
75
        $code = <<< "EOT"
76
var console = {warn: function(){}, error: function(){}};
77
var global = global || this, self = self || this, window = window || this;
78 2
render($storeJson, $metasJson);
79
EOT;
80
81 2
        return $code;
82
    }
83
}
84