FieldDescription::getDefaultValue()   C
last analyzed

Complexity

Conditions 13
Paths 40

Size

Total Lines 40
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
c 1
b 0
f 0
dl 0
loc 40
rs 6.6166
cc 13
nc 40
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace TgScraper\Parsers;
4
5
use voku\helper\HtmlDomParser;
6
7
class FieldDescription
8
{
9
10
    private HtmlDomParser $dom;
11
12
    public function __construct(string $description)
13
    {
14
        $this->dom = HtmlDomParser::str_get_html($description);
15
        foreach ($this->dom->find('.emoji') as $emoji) {
16
            $emoji->outerhtml .= $emoji->getAttribute('alt');
17
        }
18
    }
19
20
    public function __toString()
21
    {
22
        return htmlspecialchars_decode($this->dom->text(), ENT_QUOTES);
23
    }
24
25
    public function getDefaultValue(): mixed
26
    {
27
        $description = (string)$this;
28
        if (stripos($description, 'must be') !== false) {
29
            $text = explode('must be ', $this->dom->html())[1] ?? '';
30
            if (!empty($text)) {
31
                $text = explode(' ', $text)[0];
32
                $dom = HtmlDomParser::str_get_html($text);
33
                $element = $dom->findOneOrFalse('em');
34
                if ($element !== false) {
35
                    return $element->text();
36
                }
37
            }
38
        }
39
        $offset = stripos($description, 'defaults to');
40
        if ($offset === false) {
41
            return null;
42
        }
43
        $description = substr($description, $offset + 12);
44
        $parts = explode(' ', $description, 2);
45
        $value = $parts[0];
46
        if (str_ends_with($value, '.') or str_ends_with($value, ',')) {
47
            $value = substr($value, 0, -1);
48
        }
49
        if (str_starts_with($value, '“') and str_ends_with($value, '”')) {
50
            return str_replace(['“', '”'], ['', ''], $value);
51
        }
52
        if (is_numeric($value)) {
53
            return (int)$value;
54
        }
55
        if (strtolower($value) == 'true') {
56
            return true;
57
        }
58
        if (strtolower($value) == 'false') {
59
            return false;
60
        }
61
        if ($value === ucfirst($value)) {
62
            return $value;
63
        }
64
        return null;
65
    }
66
67
}