Completed
Push — master ( 630b4a...fd0077 )
by Joseph
02:27
created

Preview   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 172
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 97.14%

Importance

Changes 10
Bugs 1 Features 4
Metric Value
wmc 19
c 10
b 1
f 4
lcom 1
cbo 7
dl 0
loc 172
ccs 68
cts 70
cp 0.9714
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A fetch() 0 14 1
A title() 0 4 1
A metaKeywords() 0 11 1
B meta() 0 22 5
A images() 0 10 2
B render() 0 27 4
A formatUrl() 0 12 4
1
<?php
2
3
namespace Jclyons52\PagePreview;
4
5
use GuzzleHttp\Client;
6
use Jclyons52\PHPQuery\Document;
7
use League\Plates\Engine;
8
9
class Preview
10
{
11
    /**
12
     * body from guzzle request
13
     * @var string
14
     */
15
    protected $result;
16
17
    /**
18
     * Guzzle client
19
     * @var \GuzzleHttp\Client
20
     */
21
    protected $client;
22
23
    /**
24
     * PHPQuery document object that will be used to select elements
25
     * @var \Jclyons52\PHPQuery\Document
26
     */
27
    public $document;
28
29
    /**
30
     * reference to the url parameter the user passes into the fetch method
31
     * @var string
32
     */
33
    public $url;
34
35
    /**
36
     * destructured array of url components from parse_url
37
     * @var array
38
     */
39
    protected $urlComponents;
40
41 33
    public function __construct(Client $client)
42
    {
43 33
        $this->client = $client;
44 33
    }
45
46
    /**
47
     * @param string $url
48
     * @return Document
49
     */
50 33
    public function fetch($url)
51
    {
52 33
        $this->url = $url;
53
54 33
        $this->urlComponents = parse_url($url);
0 ignored issues
show
Documentation Bug introduced by
It seems like parse_url($url) can also be of type false. However, the property $urlComponents is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
55
56 33
        $this->result = $this->client->request('GET', $url);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->client->request('GET', $url) of type object<Psr\Http\Message\ResponseInterface> is incompatible with the declared type string of property $result.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
57
58 30
        $body = $this->result->getBody()->getContents();
59
60 30
        $this->document = new Document($body);
61
62 30
        return $this->document;
63
    }
64
65
    /**
66
     * @return string
67
     */
68 6
    public function title()
69
    {
70 6
        return $this->document->querySelector('title')->text();
71
    }
72
73
    /**
74
     * @return mixed
75
     */
76 3
    public function metaKeywords()
77
    {
78 3
        $keywordString = $this->document->querySelector('meta[name="keywords"]')->attr('content');
79
80 3
        $keywords = explode(',', $keywordString);
81
82 3
        return array_map(function ($word) {
83 3
            return trim($word);
84
85 3
        }, $keywords);
86
    }
87
88
    /**
89
     * @param string $element
90
     * @return array
91
     */
92 18
    public function meta($element = null)
93
    {
94 18
        $selector = "meta";
95 18
        if ($element) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $element of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
96 15
            $selector .= "[name='{$element}']";
97 15
            $metaTags =  $this->document->querySelector($selector);
98 15
            if ($metaTags === null) {
99 3
                return null;
100
            }
101 12
            return  $metaTags->attr('content');
102
        }
103 3
        $metaTags = $this->document->querySelectorAll($selector);
104
105 3
        if ($metaTags === []) {
106
            return null;
107
        }
108 3
        $values = [];
109 3
        foreach ($metaTags as $meta) {
110 3
            $values[$meta->attr('name')] = $meta->attr('content');
111 3
        }
112 3
        return $values;
113
    }
114
115
    /**
116
     * get source attributes of all image tags on the page
117
     * @return array<String>
118
     */
119 13
    public function images()
120
    {
121 12
        $images = $this->document->querySelectorAll('img');
122 12
        $urls = $images->attr('src');
123 12
        $result = [];
124 12
        foreach ($urls as $url) {
125 12
            $result[] = $this->formatUrl($url);
126 13
        }
127 12
        return $result;
128 2
    }
129
130
    /**
131
     * returns a string of the link preview html
132
     * @param  string $type     template name to be selected
133
     * @param  string $viewPath path to templates folder
134
     * @return string           html for link preview
135
     */
136 9
    public function render($type = 'media', $viewPath = null)
137
    {
138 9
        if ($viewPath === null) {
139 9
            $viewPath = __DIR__ . '/Templates';
140 9
        }
141 9
        $title = $this->meta('title');
142
143 9
        if (!$title) {
144 3
            $title = $this->title();
145 3
        }
146 9
        $images = $this->images();
147 9
        if (count($images) > 0) {
148 9
            $image = $images[0];
149 9
        } else {
150
            $image = '#';
151
        }
152
153 9
        $description = $this->meta('description');
154
155 9
        $templates = new Engine($viewPath);
156
157 9
        return $templates->render($type, [
158 9
            'title' => $title,
159 9
            'image' => $image,
160 9
            'body' => $description, 'url' => $this->url
161 9
        ]);
162
    }
163
164
    /**
165
     * @param string $url
166
     * @return string
167
     */
168 12
    private function formatUrl($url)
169
    {
170 12
        $path = array_key_exists('path', $this->urlComponents) ? $this->urlComponents['path'] : '';
171
172 12
        if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
173 12
            return $url;
174
        }
175 12
        if (substr($url, 0, 1) === '/') {
176 12
            return 'http://' . $this->urlComponents['host'] . $url;
177
        }
178 12
        return 'http://' . $this->urlComponents['host'] .$path . '/' . $url;
179
    }
180
}
181