Passed
Push — master ( d2ebdc...958928 )
by Bogdan
05:05
created

InstanceExtractor   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 4
dl 0
loc 40
ccs 0
cts 15
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B extract() 0 24 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\Extractors\PlainExtractors;
17
18
19
use Pinepain\JsSandbox\Extractors\Definition\PlainExtractorDefinitionInterface;
20
use Pinepain\JsSandbox\Extractors\ExtractorException;
21
use Pinepain\JsSandbox\Extractors\ExtractorInterface;
22
use Pinepain\JsSandbox\Extractors\ObjectComponents\ExtractorsObjectStoreInterface;
23
use UnexpectedValueException;
24
use V8\Context;
25
use V8\ObjectValue;
26
use V8\Value;
27
28
29
class InstanceExtractor implements PlainExtractorInterface
30
{
31
    /**
32
     * @var ExtractorsObjectStoreInterface
33
     */
34
    private $object_store;
35
36
    public function __construct(ExtractorsObjectStoreInterface $object_store)
37
    {
38
        $this->object_store = $object_store;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function extract(Context $context, Value $value, PlainExtractorDefinitionInterface $definition, ExtractorInterface $extractor)
45
    {
46
        if ($value instanceof ObjectValue) {
47
            try {
48
                $instance = $this->object_store->get($value);
49
50
                if ($definition->getNext()) {
51
                    foreach ($definition->getNext()->getVariations() as $variation) {
52
                        if (is_a($instance, $variation->getName())) {
53
                            return $instance;
54
                        }
55
                    }
56
57
                    throw new ExtractorException('Instance value constraint failed: value is not an instance of given classes/interfaces');
58
                }
59
60
                return $instance;
61
            } catch (UnexpectedValueException $e) {
62
                throw new ExtractorException('Unable to find instance for the given object');
63
            }
64
        }
65
66
        throw new ExtractorException('Value must be of the type object to be able to find instance, ' . $value->typeOf()->value() . ' given');
67
    }
68
}
69