1 | <?php |
||||
2 | |||||
3 | namespace AloiaCms; |
||||
4 | |||||
5 | class HtmlParser |
||||
6 | { |
||||
7 | /** |
||||
8 | * @param string $string |
||||
9 | * @param string $tagname |
||||
10 | * @param string $attribute |
||||
11 | * @return array |
||||
12 | */ |
||||
13 | 3 | public static function getTextBetweenTags(string $string, string $tagname, string $attribute = null): array |
|||
14 | { |
||||
15 | 3 | $attribute = $attribute ?? 'textContent'; |
|||
16 | |||||
17 | 3 | $dom_document = new \DOMDocument(); |
|||
18 | 3 | $dom_document->loadHTML($string); |
|||
19 | |||||
20 | 3 | return collect($dom_document->getElementsByTagName($tagname)) |
|||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||||
21 | 3 | ->filter(function ($dom_element) { |
|||
22 | 2 | return self::hasSingleChildNode($dom_element); |
|||
23 | 3 | }) |
|||
24 | 3 | ->map(function ($dom_element) use ($attribute) { |
|||
25 | 2 | return $dom_element->$attribute; |
|||
26 | 3 | }) |
|||
27 | 3 | ->toArray(); |
|||
28 | } |
||||
29 | |||||
30 | /** |
||||
31 | * @param string $string |
||||
32 | * @param string $tagname |
||||
33 | * @param string $source |
||||
34 | * @return array |
||||
35 | */ |
||||
36 | 4 | public static function getTagAttribute(string $string, string $tagname, string $source): array |
|||
37 | { |
||||
38 | 4 | $dom_document = new \DOMDocument(); |
|||
39 | 4 | $dom_document->loadHTML($string); |
|||
40 | |||||
41 | 4 | return collect($dom_document->getElementsByTagName($tagname)) |
|||
0 ignored issues
–
show
$dom_document->getElementsByTagName($tagname) of type DOMNodeList is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect() .
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||
42 | 4 | ->map(function ($dom_element) use ($source) { |
|||
43 | 3 | return $dom_element->getAttribute($source); |
|||
44 | 4 | }) |
|||
45 | 4 | ->toArray(); |
|||
46 | } |
||||
47 | |||||
48 | /** |
||||
49 | * Determine whether the given DomElement has a single child node |
||||
50 | * |
||||
51 | * @param \DOMElement $dom_element |
||||
52 | * @return bool |
||||
53 | */ |
||||
54 | 2 | private static function hasSingleChildNode(\DOMElement $dom_element): bool |
|||
55 | { |
||||
56 | 2 | return $dom_element->childNodes->length === 1; |
|||
57 | } |
||||
58 | } |
||||
59 |