Completed
Push — master ( fd0077...fe83dd )
by Joseph
02:18
created

Preview::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 1
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 42
    public function __construct(Client $client)
42
    {
43 42
        $this->client = $client;
44 42
    }
45
46 3
    public static function create()
47
    {
48 3
        $client = new Client();
49
50 3
        return new static($client);
51
    }
52
53
    /**
54
     * @param string $url
55
     * @return Document
56
     */
57 39
    public function fetch($url)
58 3
    {
59 39
        $this->url = $url;
60
61 39
        $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...
62
63 39
        $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...
64
65 36
        $body = $this->result->getBody()->getContents();
66
67 36
        $this->document = new Document($body);
68
69 36
        return $this->document;
70
    }
71
72
    /**
73
     * @return string
74
     */
75 6
    public function title()
76
    {
77 6
        return $this->document->querySelector('title')->text();
78
    }
79
80
    /**
81
     * @return mixed
82
     */
83 3
    public function metaKeywords()
84
    {
85 3
        $keywordString = $this->document->querySelector('meta[name="keywords"]')->attr('content');
86
87 3
        $keywords = explode(',', $keywordString);
88
89 3
        return array_map(function ($word) {
90 3
            return trim($word);
91
92 3
        }, $keywords);
93
    }
94
95
    /**
96
     * @param string $element
97
     * @return array
98
     */
99 24
    public function meta($element = null)
100
    {
101 24
        $selector = "meta";
102 24
        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...
103 18
            $selector .= "[name='{$element}']";
104 18
            $metaTags =  $this->document->querySelector($selector);
105 18
            if ($metaTags === null) {
106 3
                return null;
107
            }
108 15
            return  $metaTags->attr('content');
109
        }
110 6
        $metaTags = $this->document->querySelectorAll($selector);
111
112 6
        return $this->metaTagsToArray($metaTags);
113
    }
114
115
    /**
116
     * get source attributes of all image tags on the page
117
     * @return array<String>
118
     */
119 15
    public function images()
120
    {
121 15
        $images = $this->document->querySelectorAll('img');
122
123 15
        if ($images === []) {
124 3
            return [];
125
        }
126
127 12
        $urls = $images->attr('src');
128 14
        $result = [];
129 12
        foreach ($urls as $url) {
130 12
            $result[] = $this->formatUrl($url);
131 12
        }
132 12
        return $result;
133
    }
134
135
    /**
136
     * returns a string of the link preview html
137
     * @param  string $type     template name to be selected
138
     * @param  string $viewPath path to templates folder
139
     * @return string           html for link preview
140
     */
141 12
    public function render($type = 'media', $viewPath = null)
142
    {
143 12
        if ($viewPath === null) {
144 12
            $viewPath = __DIR__ . '/Templates';
145 12
        }
146 12
        $title = $this->meta('title');
147
148 12
        if (!$title) {
149 3
            $title = $this->title();
150 3
        }
151 12
        $images = $this->images();
152 12
        if (count($images) > 0) {
153 9
            $image = $images[0];
154 9
        } else {
155 3
            $image = null;
156
        }
157
158 12
        $description = $this->meta('description');
159
160 12
        $templates = new Engine($viewPath);
161
162 12
        return $templates->render($type, [
163 12
            'title' => $title,
164 12
            'image' => $image,
165 12
            'body' => $description, 'url' => $this->url
166 12
        ]);
167
    }
168
169
    /**
170
     * @param string $url
171
     * @return string
172
     */
173 12
    private function formatUrl($url)
174
    {
175 12
        $path = array_key_exists('path', $this->urlComponents) ? $this->urlComponents['path'] : '';
176
177 12
        if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
178 12
            return $url;
179
        }
180 12
        if (substr($url, 0, 1) === '/') {
181 12
            return 'http://' . $this->urlComponents['host'] . $url;
182
        }
183 12
        return 'http://' . $this->urlComponents['host'] .$path . '/' . $url;
184
    }
185
186
    /**
187
     * @param $metaTags
188
     * @return array
189
     */
190 6
    private function metaTagsToArray($metaTags)
191
    {
192 6
        $values = [];
193 6
        foreach ($metaTags as $meta) {
194 6
            $name = $meta->attr('name');
195 6
            if ($name === '') {
196 6
                $name = $meta->attr('property');
197 6
            }
198 6
            $content = $meta->attr('content');
199 6
            if ($name === '' || $content == '') {
200 6
                continue;
201
            }
202 3
            $values[$name] = $content;
203 6
        }
204
205 6
        return $values;
206
    }
207
}
208