Update http bestChoice to support the priority
Add unittests git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@5802 bf3deb0d-5f1a-0410-827f-c0cc1f45334c
This commit is contained in:
38
http.php
38
http.php
@@ -17,9 +17,11 @@ class http
|
||||
* If available is empty, then return the best priority defined by user,
|
||||
* and throw an exception if nothing is provided for by the user.
|
||||
* If nothing match, return $default
|
||||
* Defined in https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
|
||||
* @param string $uservar The parameter provided by the user
|
||||
* @param array|null $available The list of available choices in the soft
|
||||
* @param string|null $default The choice if nothing match
|
||||
* @return string The prefered choice
|
||||
*/
|
||||
function bestChoice ($uservar, $available=array(), $default=FALSE)
|
||||
// {{{
|
||||
@@ -32,20 +34,40 @@ class http
|
||||
throw new \Exception ("No user choice provided to bestChoice", 500);
|
||||
return $default;
|
||||
}
|
||||
// Remove weights (provided by the order of the user)
|
||||
// TODO : Reorganise the order if the weights are not in the right order
|
||||
foreach ($userchoices as $key=>$val)
|
||||
|
||||
// If the priority is not set, must be used in priority
|
||||
// If the priority is set, use it if it is valid
|
||||
$choicesPrio = array ();
|
||||
foreach ($userchoices as $choice)
|
||||
{
|
||||
$vals = @explode (";q", $val);
|
||||
$userchoices[$key] = $vals[0];
|
||||
@list ($choice, $prio) = explode (";q=", $choice);
|
||||
if (trim ($choice) === "")
|
||||
continue;
|
||||
if ($prio === null)
|
||||
$prio = 1.0;
|
||||
else
|
||||
{
|
||||
$nums = explode (".", $prio);
|
||||
if (count ($nums) > 2)
|
||||
$prio = 0.0;
|
||||
elseif ($nums[0] !== "0")
|
||||
$prio = 0.0;
|
||||
elseif ($nums[0] < 0 || $nums[0] > 9)
|
||||
$prio = 0.0;
|
||||
}
|
||||
$choicesPrio[$choice] = $prio;
|
||||
}
|
||||
// Sort by priority
|
||||
arsort ($choicesPrio, SORT_NATURAL);
|
||||
|
||||
if (count ($available) === 0)
|
||||
return $userchoices[0];
|
||||
|
||||
// Look at the best existing solution
|
||||
foreach ($userchoices as $choice)
|
||||
foreach ($choicesPrio as $choice => $priority)
|
||||
{
|
||||
if ($choice === "*/*")
|
||||
return $default;
|
||||
foreach ($available as $avail)
|
||||
{
|
||||
if (strtolower ($avail) === strtolower ($choice))
|
||||
@@ -54,10 +76,6 @@ class http
|
||||
$availTmp = str_replace ("_", "-", $avail);
|
||||
if (strtolower ($availTmp) === strtolower ($choice))
|
||||
return $avail;
|
||||
// Case text/xml, application/csv (just compare xml or csv)
|
||||
$mimes = explode ("/", $choice);
|
||||
if (isset ($mimes[1]) && strtolower ($availTmp) === $mimes[1])
|
||||
return $avail;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user