5 use http\
{Header
, Params
, QueryString
, Url
};
6 use seekat\Exception\UnexpectedValueException
;
9 final class Links
implements Serializable
{
11 * Parsed "Link" relations
17 * Parsed "Link" relations
20 private $relations = [];
23 * Parse the hypermedia link header
25 * @param Header $links The Link header
26 * @throws UnexpectedValueException
28 function __construct(Header
$links = null) {
30 if (strcasecmp($links->name
, "Link")) {
31 throw new UnexpectedValueException("Expected 'Link' header, got: '{$links->name}'");
33 $this->unserialize($links->value
);
40 function __toString() : string {
41 return $this->serialize();
47 function serialize() {
48 return (string) $this->params
;
52 * @param string $links
54 function unserialize($links) {
55 $this->params
= new Params($links, ",", ";", "=",
56 Params
::PARSE_RFC5988 | Params
::PARSE_ESCAPED
);
57 if ($this->params
->params
) {
58 foreach ($this->params
->params
as $link => $param) {
59 $this->relations
[$param["arguments"]["rel"]] = new Url($link);
65 * Receive the link header's parsed relations
69 function getRelations() : array {
70 return $this->relations
;
74 * Get the URL of the link's "next" relation
76 * Returns the link's "last" relation if it exists and "next" is not set.
81 if (isset($this->relations
["next"])) {
82 return $this->relations
["next"];
84 if (isset($this->relations
["last"])) {
85 return $this->relations
["last"];
91 * Get the URL of the link's "prev" relation
93 * Returns the link's "first" relation if it exists and "prev" is not set.
98 if (isset($this->relations
["prev"])) {
99 return $this->relations
["prev"];
101 if (isset($this->relations
["first"])) {
102 return $this->relations
["first"];
108 * Get the URL of the link's "last" relation
113 if (isset($this->relations
["last"])) {
114 return $this->relations
["last"];
120 * Get the URL of the link's "first" relation
124 function getFirst() {
125 if (isset($this->relations
["first"])) {
126 return $this->relations
["first"];
132 * Get the page sequence of the current link's relation
134 * @param string $which The relation of which to extract the page
135 * @return int The current page sequence
137 function getPage($which) {
138 if (($link = $this->{"get$which"}())) {
139 $url = new Url($link, null, 0);
140 $qry = new QueryString($url->query
);
141 return $qry->getInt("page", 1);