File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -133,6 +133,15 @@ function getQuery () : string {
133133 return (string ) ($ this ->query ?? '' );
134134 }
135135
136+ /**
137+ * Allows accessing the query data as object
138+ *
139+ * @return Query
140+ */
141+ function getQueryData () : Query {
142+ return $ this ->query ?? new Query ();
143+ }
144+
136145 /**
137146 * @return string
138147 */
@@ -142,20 +151,16 @@ function getScheme () : string {
142151
143152 /**
144153 * @throws InvalidArgumentException
145- * @param string $query
154+ * @param string|Query $query
146155 * @return static
147156 */
148157 function withQuery ($ query ) : static {
149- if (!is_string ($ query )) {
158+ if (!is_string ($ query ) && ! $ query instanceof Query ) {
150159 throw new InvalidArgumentException ("Invalid URI query type: expected `string` but got ` " . gettype ($ query ) . "` instead " );
151160 }
152161
153162 $ instance = clone $ this ;
154- if ($ query === '' ) {
155- unset($ instance ->query );
156- } else {
157- $ instance ->query = UriParser::parseQuery ($ query );
158- }
163+ $ instance ->query = ($ query === '' ) ? null : (($ query instanceof Query) ? $ query : UriParser::parseQuery ($ query ));
159164
160165 return $ instance ;
161166 }
Original file line number Diff line number Diff line change @@ -89,6 +89,19 @@ function testExpectsQueryToBeReset () {
8989 $ this ->assertSame ('http://www.example.com ' , (string ) $ uriWithoutQuery );
9090 }
9191
92+ function testExpectsQueryToBeSetFromQueryObject () {
93+ $ uri = new Uri ('http://www.example.com?foo=bar&baz=boo ' );
94+ $ query = $ uri ->getQueryData ();
95+
96+ $ queryModified = $ query ->withParameterKeyAndValue ('bar ' , 'boo ' );
97+ $ uriWithModifiedQuery = $ uri ->withQuery ($ queryModified );
98+
99+ $ this ->assertNotSame ($ uri ->getQueryData (), $ uriWithModifiedQuery ->getQueryData ());
100+ $ this ->assertNotSame ($ uri , $ uriWithModifiedQuery , 'Expected immutability to be kept ' );
101+ $ this ->assertSame ('foo=bar&baz=boo&bar=boo ' , $ uriWithModifiedQuery ->getQuery ());
102+ $ this ->assertSame ('http://www.example.com?foo=bar&baz=boo&bar=boo ' , (string ) $ uriWithModifiedQuery );
103+ }
104+
92105 function testExpectsPortToBeReset () {
93106 $ uri = new Uri ('http://www.example.com:1234 ' );
94107 $ uriWithoutPort = $ uri ->withPort (null );
You can’t perform that action at this time.
0 commit comments