Completed
Push — master ( 822e25...eb7464 )
by Joseph
02:21
created

Preview::meta()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.0061

Importance

Changes 3
Bugs 0 Features 2
Metric Value
c 3
b 0
f 2
dl 0
loc 22
ccs 15
cts 16
cp 0.9375
rs 8.6737
cc 5
eloc 15
nc 5
nop 1
crap 5.0061
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 mixed
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
     * @return array
90
     */
91 18
    public function meta($element = null)
92
    {
93 18
        $selector = "meta";
94 18
        if ($element) {
95 15
            $selector .= "[name='{$element}']";
96 15
            $metaTags =  $this->document->querySelector($selector);
97 15
            if ($metaTags === null) {
98 3
                return null;
99
            }
100 12
            return  $metaTags->attr('content');
101
        }
102 3
        $metaTags = $this->document->querySelectorAll($selector);
103
104 3
        if ($metaTags === []) {
105
            return null;
106
        }
107 3
        $values = [];
108 3
        foreach ($metaTags as $meta) {
109 3
            $values[$meta->attr('name')] = $meta->attr('content');
110 3
        }
111 3
        return $values;
112
    }
113
114
    /**
115
     * get source attributes of all image tags on the page
116
     * @return array<String>
117
     */
118 13
    public function images()
119
    {
120 12
        $images = $this->document->querySelectorAll('img');
121 12
        $urls = $images->attr('src');
122 12
        $result = [];
123 12
        foreach ($urls as $url) {
124 12
            $result[] = $this->formatUrl($url);
125 12
        }
126 13
        return $result;
127
    }
128
129
    /**
130
     * returns a string of the link preview html
131
     * @param  string $type     template name to be selected
132
     * @param  string $viewPath path to templates folder
133
     * @return string           html for link preview
134
     */
135 9
    public function render($type = 'media', $viewPath = null)
136
    {
137 9
        if ($viewPath === null) {
138 9
            $viewPath = __DIR__ . '/Templates';
139 9
        }
140 9
        $title = $this->meta('title');
141
142 9
        if (!$title) {
143 3
            $title = $this->title();
144 3
        }
145 9
        $images = $this->images();
146 9
        if (count($images) > 0) {
147 9
            $image = $images[0];
148 9
        } else {
149
            $image = '#';
150
        }
151
152 9
        $description = $this->meta('description');
153
154 9
        $templates = new Engine($viewPath);
155
156 9
        return $templates->render($type, [
157 9
            'title' => $title,
158 9
            'image' => $image,
159 9
            'body' => $description, 'url' => $this->url
160 9
        ]);
161
    }
162
163
    /**
164
     * @param string $url
165
     * @return array
166
     */
167 12
    private function formatUrl($url)
168
    {
169 12
        $path = array_key_exists('path', $this->urlComponents) ? $this->urlComponents['path'] : '';
170
171 12
        if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
172 12
            return $url;
173
        }
174 12
        if (substr($url, 0, 1) === '/') {
175 12
            return 'http://' . $this->urlComponents['host'] . $url;
176
        }
177 12
        return 'http://' . $this->urlComponents['host'] .$path . '/' . $url;
178
    }
179
}
180