2017-02-26 16 views
0

我一直在致力於實現PSR-7UriInterface,並且有關何時某個實現應該爲某些組件引發InvalidArgumentException的規範有點令人費解。PSR-7 UriInterface - 編碼百分比無效的組件

例如,UriInterface::withPath specifies throwing such an exception given an invalid path,但非常相同的docblock注意到,「用戶可以提供編碼和解碼的路徑字符」,因爲「實現確保正確的編碼」。

/** 
* ... 
* 
* Users can provide both encoded and decoded path characters. 
* Implementations ensure the correct encoding as outlined in getPath(). 
* 
* @param string $path The path to use with the new instance. 
* @return static A new instance with the specified path. 
* @throws \InvalidArgumentException for invalid paths. 
*/ 

該實現負責管理編碼在整個規範的其餘部分都被證明。

由於實現確保了正確的編碼,所以似乎遵循的是,實現的用戶可以將任意數量的其他無效字符傳遞到函數中,例如withPath,然後該函數將被正確編碼而不是觸發異常。

我能想到的唯一情況是,如果withPath傳遞了非字符串(無論它的值是什麼,似乎是Guzzle's interpretation of the specification),將會發生InvalidArgumentException。

真正嚴格閱讀PHP's brief introduction of InvalidArgumentException似乎可以避免這種「嚴格類型」的解釋,但我不禁想知道PHP-FIG是否有任何其他的想法,特別是考慮到URI語法的複雜性一般來說。

是否有任何情況下,UriInterface方法(如withPath在傳遞字符串時應引發異常?

回答

1

我知道,你的問題有點老:-)

你的假設是完全正確的!

關於部分:

用戶可以提供既編碼和解碼路徑中的字符。
實現確保getPath()中概述的正確編碼。

這與「無效路徑」無關(在@throws標記中描述)。它只是陳述 - 正如您正確地聲稱的那樣,用戶可以提供編碼和解碼字符,這是正確的 - 在的意義上相應地 - 百分比編碼。例如。一些不編碼的字符將被百分比編碼,而另一些則不是。原則上,編碼方案將是:

Percent-encode all URI path characters, except: 

- the unreserved characters, 
- the reserved characters of the subset "gen-delims", 
- the reserved characters of the subset "sub-delims", 
- the already percent-encoded characters. 

在另一方面,一個例外 - InvalidArgumentException - 在以下參數無效的情況下拋出:

  • withScheme:不是字符串,是不屬於允許的 計劃清單的一部分;
  • withHost:不是字符串;
  • withPort:是不是數字(或整數?)並且不在範圍內[1,65535];
  • withPath:不是字符串;
  • withQuery:不是字符串;
  • withFragment:不是字符串;

,最後,經特殊處理接收到的URI字符串($uri)爲(可選null)構造函數參數傳遞:

  • 沒有設置
  • 不是字符串
  • 是空的

...和URI部分數組,因爲在URI字符串參數上調用parse_url(這裏是thr嗷嗷UnexpectedValueException):

$uriParts = parse_url($uri); 

if ($uriParts === FALSE) { 
    throw new \UnexpectedValueException('URI could not be parsed!'); 
} 

請注意,我列出了UriInterface實現內部的所有異常拋出的情況。