WebPageHandler   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 23
c 2
b 0
f 0
dl 0
loc 63
rs 10
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A read() 0 24 4
A getDom() 0 3 1
A __construct() 0 5 1
A getHtml() 0 3 1
A setUrl() 0 3 1
A getUrl() 0 3 1
1
<?php
2
3
namespace Coco\SourceWatcher\Watcher\Handler;
4
5
use Coco\SourceWatcher\Core\SourceWatcherException;
6
use DOMDocument;
7
8
/**
9
 * Class WebPageHandler
10
 * @package Coco\SourceWatcher\Watcher\Handler
11
 */
12
class WebPageHandler implements Handler
13
{
14
    protected string $url;
15
16
    protected string $html;
17
18
    protected DOMDocument $dom;
19
20
    public function __construct ( string $url )
21
    {
22
        $this->url = $url;
23
        $this->html = "";
24
        $this->dom = new DOMDocument();
25
    }
26
27
    public function getUrl () : string
28
    {
29
        return $this->url;
30
    }
31
32
    public function setUrl ( string $url ) : void
33
    {
34
        $this->url = $url;
35
    }
36
37
    /**
38
     * @throws SourceWatcherException
39
     */
40
    public function read () : void
41
    {
42
        if ( empty( $this->url ) ) {
43
            throw new SourceWatcherException( "A URL must be set before reading" );
44
        }
45
46
        $ch = curl_init();
47
48
        $timeout = 5;
49
50
        curl_setopt( $ch, CURLOPT_URL, $this->url );
51
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
52
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
53
54
        $this->html = curl_exec( $ch );
55
56
        curl_close( $ch );
57
58
        # Create a DOM parser object
59
        $this->dom = new DOMDocument();
60
61
        if ( isset( $this->html ) && $this->html !== "" ) {
62
            # The @ before the method call suppresses any warnings that loadHTML might throw because of invalid HTML in the page.
63
            @$this->dom->loadHTML( $this->html );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for loadHTML(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

63
            /** @scrutinizer ignore-unhandled */ @$this->dom->loadHTML( $this->html );

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
64
        }
65
    }
66
67
    public function getHtml () : string
68
    {
69
        return $this->html;
70
    }
71
72
    public function getDom () : DOMDocument
73
    {
74
        return $this->dom;
75
    }
76
}
77