| 1 |
<?php |
| 2 |
|
| 3 |
namespace Intervention\HttpAuth; |
| 4 |
|
| 5 |
class Directive |
| 6 |
{ |
| 7 |
/** |
| 8 |
* Type of directive (basic|digest) |
| 9 |
* |
| 10 |
* @var string |
| 11 |
*/ |
| 12 |
protected $type; |
| 13 |
|
| 14 |
/** |
| 15 |
* Array of parameters |
| 16 |
* |
| 17 |
* @var array |
| 18 |
*/ |
| 19 |
protected $parameters = []; |
| 20 |
|
| 21 |
/** |
| 22 |
* Create new instance |
| 23 |
* |
| 24 |
* @param string $type |
| 25 |
* @param array $parameters |
| 26 |
*/ |
| 27 |
public function __construct($type, $parameters = []) |
| 28 |
{ |
| 29 |
$this->type = $type; |
| 30 |
$this->parameters = $parameters; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Format current instance |
| 35 |
* |
| 36 |
* @return string |
| 37 |
*/ |
| 38 |
public function format(): string |
| 39 |
{ |
| 40 |
return sprintf( |
| 41 |
'%s %s', |
| 42 |
ucfirst(strtolower($this->type)), |
| 43 |
$this->getParametersString() |
| 44 |
); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Return current type |
| 49 |
* |
| 50 |
* @return string |
| 51 |
*/ |
| 52 |
public function getType() |
| 53 |
{ |
| 54 |
return $this->type; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Return value of given key from all parameters, if existing |
| 59 |
* |
| 60 |
* @param mixed $key |
| 61 |
* @return mixed |
| 62 |
*/ |
| 63 |
public function getParameter($key) |
| 64 |
{ |
| 65 |
return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : null; |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Format current parameters as string |
| 70 |
* |
| 71 |
* @return string |
| 72 |
*/ |
| 73 |
private function getParametersString(): string |
| 74 |
{ |
| 75 |
return implode(', ', array_map(function ($key, $value) { |
| 76 |
return sprintf('%s="%s"', $key, $value); |
| 77 |
}, array_keys($this->parameters), $this->parameters)); |
| 78 |
} |
| 79 |
|
| 80 |
/** |
| 81 |
* Cast object to string |
| 82 |
* |
| 83 |
* @return string |
| 84 |
*/ |
| 85 |
public function __toString(): string |
| 86 |
{ |
| 87 |
return $this->format(); |
| 88 |
} |
| 89 |
} |
| 90 |
|