1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Jclyons52\PagePreview; |
4
|
|
|
|
5
|
|
|
class Url |
6
|
|
|
{ |
7
|
|
|
public $original; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* destructured array of url components from parse_url |
11
|
|
|
* @var array |
12
|
|
|
*/ |
13
|
|
|
public $components; |
14
|
|
|
|
15
|
69 |
|
public function __construct($url) |
16
|
|
|
{ |
17
|
69 |
|
$this->original = $url; |
18
|
69 |
|
$this->components = $this->parse($url); |
|
|
|
|
19
|
63 |
|
} |
20
|
|
|
|
21
|
12 |
|
public static function findFirst($text) |
22
|
|
|
{ |
23
|
12 |
|
if ($urls = self::extract($text)) { |
24
|
9 |
|
return new self($urls[0]); |
25
|
|
|
} |
26
|
|
|
|
27
|
3 |
|
return null; |
28
|
|
|
} |
29
|
|
|
|
30
|
6 |
|
public static function findAll($text) |
31
|
|
|
{ |
32
|
6 |
|
if ($urls = self::extract($text)) { |
33
|
3 |
|
return array_map(function ($url) { |
34
|
3 |
|
return new self($url); |
35
|
3 |
|
}, $urls); |
36
|
|
|
} |
37
|
3 |
|
return null; |
38
|
|
|
} |
39
|
|
|
|
40
|
15 |
|
public static function extract($text) |
41
|
|
|
{ |
42
|
15 |
|
if (preg_match_all('!https?://\S+!', $text, $matches) === 0) { |
43
|
3 |
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
12 |
|
return $matches[0]; |
47
|
|
|
} |
48
|
|
|
|
49
|
69 |
|
public function parse($url) |
50
|
|
|
{ |
51
|
69 |
|
$urlComponents = parse_url($url); |
52
|
|
|
|
53
|
69 |
|
if (filter_var($url, FILTER_VALIDATE_URL) === false) { |
54
|
6 |
|
throw new \Exception("url {$url} is invalid"); |
55
|
|
|
} |
56
|
|
|
|
57
|
63 |
|
return $urlComponents; |
58
|
|
|
} |
59
|
|
|
|
60
|
48 |
|
public function formatRelativeToAbsolute($url) |
61
|
|
|
{ |
62
|
48 |
|
if (substr($url, 0, 5) === "data:") { |
63
|
39 |
|
return $url; |
64
|
|
|
} |
65
|
|
|
|
66
|
48 |
|
$path = array_key_exists('path', $this->components) ? $this->components['path'] : ''; |
67
|
|
|
|
68
|
48 |
|
if (filter_var($url, FILTER_VALIDATE_URL) !== false) { |
69
|
48 |
|
return $url; |
70
|
|
|
} |
71
|
48 |
|
if (substr($url, 0, 1) === '/') { |
72
|
48 |
|
return 'http://' . $this->components['host'] . $url; |
73
|
|
|
} |
74
|
|
|
|
75
|
48 |
|
$host = trim($this->components['host'], '/') . '/'; |
76
|
48 |
|
$path = trim($path, '/') . '/'; |
77
|
|
|
|
78
|
48 |
|
return 'http://' . $host . $path . $url; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
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 theid
property of an instance of theAccount
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.