/
Parser.php
133 lines (111 loc) · 2.5 KB
/
Parser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<?php
/**
* This file is part of the QA-Tools library.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @copyright Alexander Obuhovich <aik.bold@gmail.com>
* @link https://github.com/qa-tools/qa-tools
*/
namespace QATools\QATools\PageObject\Url;
use QATools\QATools\PageObject\Exception\UrlException;
/**
* Parses url and returns components.
*
* @method \Mockery\Expectation shouldReceive(string $name)
*/
class Parser
{
/**
* The url components.
*
* @var array
*/
protected $components = array();
/**
* Constructor for Parser.
*
* @param string $url The url to parse.
*
* @throws UrlException When url is invalid.
*/
public function __construct($url)
{
$components = parse_url($url);
if ( $components === false ) {
throw new UrlException($url . ' is not a valid url', UrlException::TYPE_INVALID_URL);
}
$this->components = $components;
}
/**
* Get url component.
*
* @param string $name The name of the component.
* @param string $default The default value.
*
* @return string
*/
public function getComponent($name, $default = '')
{
return !empty($this->components[$name]) ? $this->components[$name] : $default;
}
/**
* Gets the url components.
*
* @return array
*/
public function getComponents()
{
return $this->components;
}
/**
* Gets parsed query.
*
* @return array
*/
public function getParams()
{
$ret = array();
$query = $this->getComponent('query');
if ( $query ) {
parse_str($query, $ret);
}
return $ret;
}
/**
* Sets parsed query.
*
* @param array $params GET params.
*
* @return static
*/
public function setParams(array $params)
{
$this->components['query'] = http_build_query($params);
return $this;
}
/**
* Merge both url parsers.
*
* @param Parser $parser The url parser to merge.
*
* @return static
*/
public function merge(Parser $parser)
{
$left_path = $this->getComponent('path');
$right_path = $parser->getComponent('path');
$left_params = $this->getParams();
$right_params = $parser->getParams();
$this->components = array_merge($this->components, $parser->components);
if ( $left_path && $right_path ) {
$this->components['path'] = rtrim($left_path, '/') . '/' . ltrim($right_path, '/');
}
if ( $left_params && $right_params ) {
$this->components['query'] = http_build_query(
array_replace_recursive($left_params, $right_params)
);
}
return $this;
}
}