RequireCallback::handleNativeModule()   A
last analyzed

Complexity

Conditions 2
Paths 3

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 12
cp 0
rs 9.3142
c 0
b 0
f 0
cc 2
eloc 13
nc 3
nop 4
crap 6
1
<?php declare(strict_types=1);
2
3
/*
4
 * This file is part of the pinepain/js-sandbox PHP library.
5
 *
6
 * Copyright (c) 2016-2017 Bogdan Padalko <[email protected]>
7
 *
8
 * Licensed under the MIT license: http://opensource.org/licenses/MIT
9
 *
10
 * For the full copyright and license information, please view the
11
 * LICENSE file that was distributed with this source or visit
12
 * http://opensource.org/licenses/MIT
13
 */
14
15
16
namespace Pinepain\JsSandbox\Modules;
17
18
19
use League\Flysystem\Util;
20
use Pinepain\JsSandbox\Exceptions\NativeException;
21
use Pinepain\JsSandbox\Modules\Repositories\NativeModulesRepositoryInterface;
22
use Pinepain\JsSandbox\Modules\Repositories\SourceModulesRepositoryInterface;
23
use Pinepain\JsSandbox\Wrappers\FunctionComponents\Runtime\ExecutionContextInterface;
24
use Throwable;
25
use V8\ObjectValue;
26
use function strlen;
27
28
29
class RequireCallback implements RequireCallbackInterface
30
{
31
    /**
32
     * @var ModulesCacheInterface
33
     */
34
    private $cache;
35
    /**
36
     * @var ModulesStackInterface
37
     */
38
    private $stack;
39
    /**
40
     * @var NativeModulesRepositoryInterface
41
     */
42
    private $native;
43
    /**
44
     * @var SourceModulesRepositoryInterface
45
     */
46
    private $source;
47
48
    public function __construct(ModulesCacheInterface $cache, ModulesStackInterface $stack, NativeModulesRepositoryInterface $native, SourceModulesRepositoryInterface $source)
49
    {
50
        $this->cache  = $cache;
51
        $this->stack  = $stack;
52
        $this->native = $native;
53
        $this->source = $source;
54
    }
55
56
    public function callback(ExecutionContextInterface $execution, string $id)
57
    {
58
        $id = $this->resolve($id);
59
60
        if ($this->cache->has($id)) {
61
            return $this->cache->get($id)->getExports();
62
        }
63
64
        // TODO: should we freeze export if it's an object?
65
        //https://codereview.chromium.org/1889903003/diff/1/include/v8.h
66
67
        if ($this->native->has($id)) {
68
            return $this->handleNativeModule($execution, $id, $this->native->get($id), $this->stack->top());
69
        }
70
71
        if ($this->source->has($id)) {
72
            return $this->handleSourceModule($execution, $id, $this->source->get($id), $this->stack->top());
73
        }
74
75
        throw new NativeException("Cannot find module '{$id}'");
76
    }
77
78
    public function resolve(string $id)
79
    {
80
        $id = trim($id);
81
82
        if (strlen($id) && ('/' != $id[0]) && $top = $this->stack->top()) {
83
            assert(null !== $top);
84
            // relative path, try to append directory from current top module, if available
85
            $id = $top->getDirname() . '/' . $id;
86
        }
87
88
        return Util::normalizePath($id);
89
    }
90
91
    public function getMain(): ?ModuleInterface
92
    {
93
        return $this->stack->bottom();
94
    }
95
96
    protected function buildNativeModule(string $filename, ?ModuleInterface $top): ModuleInterface
97
    {
98
        $id     = $filename;
99
        $module = new Module($id, $filename, Util::dirname($filename), $top);
100
101
        return $module;
102
    }
103
104
    protected function buildModule(string $filename, ?ModuleInterface $top): ModuleInterface
105
    {
106
        $id = $filename;
107
108
        if (null === $top) {
109
            $id = '.';
110
        }
111
112
        $module = new Module($id, $filename, Util::dirname($filename), $top);
113
114
        if ($top) {
115
            if ($top->isLoaded()) {
116
                // UNLIKELY
117
                // this should never happens, but just in case
118
                throw new NativeException('Modifying loaded module is not allowed');
119
            }
120
121
            // add current module as top one child
122
            $top->addChild($module);
123
        }
124
125
        return $module;
126
    }
127
128
    protected function handleNativeModule(ExecutionContextInterface $execution, string $id, NativeModulePrototypeInterface $prototype, ?ModuleInterface $top)
129
    {
130
        $context = $execution->getContext();
131
132
        $module = $this->buildNativeModule($id, $top);
133
134
        $exports = new ObjectValue($context);
135
        $module->setExports($exports);
136
137
        $this->cache->put($id, $module);
138
139
        try {
140
            $prototype->compile($execution->getIsolate(), $context, $module);
141
            $module->setLoaded();
142
        } catch (Throwable $e) {
143
            $this->cache->remove($id);
144
            throw $e;
145
        }
146
147
        return $module->getExports();
148
    }
149
150
    protected function handleSourceModule(ExecutionContextInterface $execution, string $id, SourceModuleBuilderInterface $builder, ?ModuleInterface $top)
151
    {
152
        $module = $this->buildModule($id, $top);
153
154
        $this->stack->push($module); // put current module at the top
155
156
        $context = $execution->getContext();
157
158
        $exports = new ObjectValue($context);
159
        $module->setExports($exports);
160
161
        $this->cache->put($id, $module);
162
163
        try {
164
            $function = $builder->build($execution->getIsolate(), $context, $module);
165
166
            // Alternatively:
167
            //$native = new NativeFunctionWrapper($context, $exports, $function, $execution->getWrapper());
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
168
            //$native->call($exports, $execution->getFunctionObject(), $module, $module->getFilename(), $module->getDirname())
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
169
170
            // Even shorter alternative
171
            //$native = $execution->wrapNativeFunction($exports, $function);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
172
            //$native->call($exports, $execution->getFunctionObject(), $module, $module->getFilename(), $module->getDirname())
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
173
174
            // NOTE: we need to wrap all this values as we will manually call V8 FunctionObject
175
            $require    = $execution->getFunctionObject();
176
            $js_module  = $execution->wrap($module);
177
            $__filename = $execution->wrap($module->getFilename());
178
            $__dirname  = $execution->wrap($module->getDirname());
179
180
            // exports, require, module, __filename, __dirname
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
181
            $args = [$exports, $require, $js_module, $__filename, $__dirname];
182
183
            $function->call($context, $exports, $args);
184
            //$function->Call($context, $execution->getThis(), $args);
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
185
            $module->setLoaded();
186
        } catch (Throwable $e) {
187
            $this->cache->remove($id);
188
            throw $e;
189
        } finally {
190
            $this->stack->pop(); // remove current module from the top
191
        }
192
193
        return $module->getExports();
194
    }
195
}
196