1 | <?php |
||
18 | class UrlParser |
||
19 | { |
||
20 | |||
21 | /** |
||
22 | * Parse a URI into a Url |
||
23 | * |
||
24 | * @param string $url |
||
25 | * @throws InvalidUrlException |
||
26 | * @return \Generics\Socket\Url |
||
27 | */ |
||
28 | 21 | public static function parseUrl($url) |
|
29 | { |
||
30 | 21 | $parts = parse_url($url); |
|
31 | |||
32 | 21 | if (! Arrays::hasElement($parts, 'host') ) { |
|
|
|||
33 | 17 | throw new InvalidUrlException('This URL does not contain a host part'); |
|
34 | } |
||
35 | 14 | if (! Arrays::hasElement($parts, 'scheme') ) { |
|
36 | 1 | throw new InvalidUrlException('This URL does not contain a scheme part'); |
|
37 | } |
||
38 | |||
39 | 13 | $address = $parts['host']; |
|
40 | 13 | $scheme = $parts['scheme']; |
|
41 | 13 | $port = 0; |
|
42 | 13 | $path = "/"; |
|
43 | |||
44 | 13 | if (isset($parts['port'])) { |
|
45 | 2 | $port = intval($parts['port']); |
|
46 | } |
||
47 | |||
48 | 13 | if ($port == 0) { |
|
49 | 11 | $port = self::getPortByScheme($scheme); |
|
50 | } |
||
51 | |||
52 | 11 | if (isset($parts['path'])) { |
|
53 | 10 | $path = $parts['path']; |
|
54 | } |
||
55 | |||
56 | 11 | return new Url($address, $port, $path, $scheme); |
|
57 | } |
||
58 | |||
59 | /** |
||
60 | * Get port number by scheme name. |
||
61 | * The port will be the default which is defined by |
||
62 | * http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers |
||
63 | * |
||
64 | * @param string $scheme The scheme. |
||
65 | * @throws InvalidUrlException |
||
66 | * @return int |
||
67 | */ |
||
68 | 11 | public static function getPortByScheme($scheme) |
|
86 | } |
||
87 |
This check looks for type mismatches where the missing type is
false
. This is usually indicative of an error condtion.Consider the follow example
This function either returns a new
DateTime
object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returnedfalse
before passing on the value to another function or method that may not be able to handle afalse
.