Test Failed
Pull Request — master (#128)
by Lucas
02:55
created

HtmlSplitter::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * This file is part of Scout Extended.
7
 *
8
 * (c) Algolia Team <[email protected]>
9
 *
10
 *  For the full copyright and license information, please view the LICENSE
11
 *  file that was distributed with this source code.
12
 */
13
14
namespace Algolia\ScoutExtended\Splitters;
15
16
use DOMDocument;
17
use Algolia\ScoutExtended\Contracts\SplitterContract;
18
19
class HtmlSplitter implements SplitterContract
20
{
21
    /**
22
     * The list of html tags.
23
     *
24
     * @var string[]
25
     */
26
    protected $tags = [
27
        'h1',
28
        'h2',
29
        'h3',
30
        'h4',
31
        'h5',
32
        'p',
33
    ];
34
35
    /**
36
     * Creates a new instance of the class.
37
     *
38
     * @param array $tags
39
     *
40
     * @return void
41
     */
42
    public function __construct(array $tags = null)
43
    {
44
        if ($tags !== null) {
45
            $this->tags = $tags;
46
        }
47
    }
48
49
    /**
50
     * Acts a static factory.
51
     *
52
     * @param  string|array $tags
53
     *
54
     * @return static
55
     */
56
    public static function by($tags)
57
    {
58
        return new static((array) $tags);
59
    }
60
61
    /**
62
     * Splits the given value.
63
     *
64
     * @param  object $searchable
65
     * @param  string $value
66
     *
67
     * @return array
68
     */
69
    public function split($searchable, $value): array
70
    {
71
        $dom = new DOMDocument();
72
        $dom->loadHTML($value);
73
        $values = [];
74
75
        foreach ($this->tags as $tag) {
76
            foreach ($dom->getElementsByTagName($tag) as $node) {
77
                $values[] = $node->textContent;
78
79
                while (($node = $node->nextSibling) && $node->nodeName !== $tag) {
80
                    $values[] = $node->textContent;
81
                }
82
            }
83
        }
84
85
        return $values;
86
    }
87
}
88