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; |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
use Pinepain\JsSandbox\Extractors\Definition\ExtractorDefinitionInterface; |
20
|
|
|
use Pinepain\JsSandbox\Extractors\Definition\PlainExtractorDefinitionInterface; |
21
|
|
|
use Pinepain\JsSandbox\Extractors\Definition\VariableExtractorDefinitionInterface; |
22
|
|
|
use V8\Context; |
23
|
|
|
use V8\Value; |
24
|
|
|
|
25
|
|
|
|
26
|
|
|
class Extractor implements ExtractorInterface |
27
|
|
|
{ |
28
|
|
|
/** |
29
|
|
|
* @var ExtractorsCollectionInterface |
30
|
|
|
*/ |
31
|
|
|
private $extractors; |
32
|
|
|
|
33
|
|
|
public function __construct(ExtractorsCollectionInterface $extractors) |
34
|
|
|
{ |
35
|
|
|
$this->extractors = $extractors; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* {@inheritdoc} |
40
|
|
|
*/ |
41
|
|
|
public function extract(Context $context, Value $value, ExtractorDefinitionInterface $definition) |
42
|
|
|
{ |
43
|
|
|
if ($definition instanceof PlainExtractorDefinitionInterface) { |
44
|
|
|
return $this->extractPlain($context, $value, $definition); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
if ($definition instanceof VariableExtractorDefinitionInterface) { |
48
|
|
|
return $this->extractVarying($context, $value, $definition); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
throw new ExtractorException('Unknown extractor definition'); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
protected function extractPlain(Context $context, Value $value, PlainExtractorDefinitionInterface $definition) |
55
|
|
|
{ |
56
|
|
|
$name = $definition->getName(); |
57
|
|
|
assert(null !== $name); |
58
|
|
|
|
59
|
|
|
return $this->extractors->get($name)->extract($context, $value, $definition, $this); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
protected function extractVarying(Context $context, Value $value, VariableExtractorDefinitionInterface $definition) |
63
|
|
|
{ |
64
|
|
|
if (!$definition->getVariations()) { |
65
|
|
|
throw new ExtractorException('Variable extractor definition is empty'); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$e = null; |
69
|
|
|
|
70
|
|
|
foreach ($definition->getVariations() as $variation) { |
71
|
|
|
try { |
72
|
|
|
return $this->extract($context, $value, $variation); |
73
|
|
|
} catch (ExtractorException $e) { |
74
|
|
|
continue; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
throw $e; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|