1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Abacaphiliac\Extractor; |
4
|
|
|
|
5
|
|
|
use Abacaphiliac\Extractor\Exception\UnexpectedValueException; |
6
|
|
|
use Zend\Stdlib\ArrayUtils; |
7
|
|
|
|
8
|
|
|
class ExtractorChain implements ExtractionInterface |
9
|
|
|
{ |
10
|
|
|
/** @var ExtractionInterface[] */ |
11
|
|
|
private $extractors = []; |
12
|
|
|
|
13
|
|
|
/** @var bool */ |
14
|
|
|
private $mergeRecursively; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* PendoOptionsProviderChain constructor. |
18
|
|
|
* @param ExtractionInterface[] $extractors |
19
|
|
|
* @param bool $mergeRecursively |
20
|
|
|
*/ |
21
|
|
|
public function __construct(array $extractors = [], $mergeRecursively = true) |
22
|
|
|
{ |
23
|
|
|
array_walk($extractors, [$this, 'addExtractor']); |
24
|
|
|
$this->mergeRecursively = $mergeRecursively; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param ExtractionInterface $extractor |
29
|
|
|
*/ |
30
|
|
|
private function addExtractor(ExtractionInterface $extractor) |
31
|
|
|
{ |
32
|
|
|
$this->extractors[] = $extractor; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @return mixed[] |
37
|
|
|
* @throws \Abacaphiliac\Extractor\Exception\UnexpectedValueException |
38
|
|
|
*/ |
39
|
|
|
public function extract() |
40
|
|
|
{ |
41
|
|
|
$dataSets = array_map(function (ExtractionInterface $extractor) { |
42
|
|
|
$data = $extractor->extract(); |
43
|
|
|
|
44
|
|
|
if ($data instanceof \Traversable) { |
45
|
|
|
$data = iterator_to_array($data); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if (!is_array($data)) { |
49
|
|
|
throw new UnexpectedValueException(sprintf( |
50
|
|
|
'Extractor type `%s` returned a `%s` instead of an `array`', |
51
|
|
|
get_class($extractor), |
52
|
|
|
is_object($data) ? get_class($data) : gettype($data) |
53
|
|
|
)); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $data; |
57
|
|
|
}, $this->extractors); |
58
|
|
|
|
59
|
|
|
if (!$dataSets) { |
|
|
|
|
60
|
|
|
return []; |
|
|
|
|
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if (!$this->mergeRecursively) { |
64
|
|
|
return array_merge(...$dataSets); |
|
|
|
|
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$result = []; |
68
|
|
|
foreach ($dataSets as $data) { |
69
|
|
|
// Zend's function will overwrite keys with new values upon collision, as opposed to PHP's native |
70
|
|
|
// array_merge_recursive function which will generate a new array of merged values for that key. |
71
|
|
|
$result = ArrayUtils::merge($result, $data); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $result; |
|
|
|
|
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
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.