5 use seekat\Exception\UnexpectedValueException
;
14 final class Links
implements Serializable
17 * Parsed "Link" relations
23 * Parsed "Link" relations
26 private $relations = [];
29 * Parse the hypermedia link header
31 * @param Header $links The Link header
32 * @throws UnexpectedValueException
34 function __construct(Header
$links = null) {
36 if (strcasecmp($links->name
, "Link")) {
37 throw new UnexpectedValueException("Expected 'Link' header, got: '{$links->name}'");
39 $this->unserialize($links->value
);
46 function __toString() : string {
47 return $this->serialize();
53 function serialize() {
54 return (string) $this->params
;
58 * @param string $links
60 function unserialize($links) {
61 $this->params
= new Params($links, ",", ";", "=",
62 Params
::PARSE_RFC5988 | Params
::PARSE_ESCAPED
);
63 if ($this->params
->params
) {
64 foreach ($this->params
->params
as $link => $param) {
65 $this->relations
[$param["arguments"]["rel"]] = new Url($link);
71 * Receive the link header's parsed relations
75 function getRelations() : array {
76 return $this->relations
;
80 * Get the URL of the link's "next" relation
82 * Returns the link's "last" relation if it exists and "next" is not set.
87 if (isset($this->relations
["next"])) {
88 return $this->relations
["next"];
90 if (isset($this->relations
["last"])) {
91 return $this->relations
["last"];
97 * Get the URL of the link's "prev" relation
99 * Returns the link's "first" relation if it exists and "prev" is not set.
104 if (isset($this->relations
["prev"])) {
105 return $this->relations
["prev"];
107 if (isset($this->relations
["first"])) {
108 return $this->relations
["first"];
114 * Get the URL of the link's "last" relation
119 if (isset($this->relations
["last"])) {
120 return $this->relations
["last"];
126 * Get the URL of the link's "first" relation
130 function getFirst() {
131 if (isset($this->relations
["first"])) {
132 return $this->relations
["first"];
138 * Get the page sequence of the current link's relation
140 * @param string $which The relation of which to extract the page
141 * @return int The current page sequence
143 function getPage($which) {
144 if (($link = $this->{"get$which"}())) {
145 $url = new Url($link, null, 0);
146 $qry = new QueryString($url->query
);
147 return $qry->getInt("page", 1);