/
Fragment.php
119 lines (94 loc) · 2.48 KB
/
Fragment.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
declare(strict_types=1);
namespace Purl;
use function array_merge;
use function parse_url;
use function sprintf;
/**
* Fragment represents the part of a Url after the hashmark (#).
*
* @property Path|string $path
* @property Query|string $query
*/
class Fragment extends AbstractPart
{
/** @var string|null The original fragment string. */
private $fragment;
/** @var mixed[] */
protected $data = [
'path' => null,
'query' => null,
];
/** @var string[] */
protected $partClassMap = [
'path' => 'Purl\Path',
'query' => 'Purl\Query',
];
/**
* @param string|Path|null $fragment
*/
public function __construct($fragment = null, ?Query $query = null)
{
if ($fragment instanceof Path) {
$this->initialized = true;
$this->data['path'] = $fragment;
} else {
$this->fragment = $fragment;
}
$this->data['query'] = $query;
}
/**
* @param mixed $value
*/
public function set(string $key, $value) : AbstractPart
{
$this->initialize();
$this->data[$key] = $this->preparePartValue($key, $value);
return $this;
}
public function getFragment() : string
{
$this->initialize();
return sprintf('%s%s', $this->path, (string) $this->query !== '' ? '?' . (string) $this->query : '');
}
public function setFragment(string $fragment) : AbstractPart
{
$this->initialized = false;
$this->data = [];
$this->fragment = $fragment;
return $this;
}
public function setPath(Path $path) : AbstractPart
{
$this->data['path'] = $path;
return $this;
}
public function getPath() : Path
{
$this->initialize();
return $this->data['path'];
}
public function setQuery(Query $query) : AbstractPart
{
$this->data['query'] = $query;
return $this;
}
public function getQuery() : Query
{
$this->initialize();
return $this->data['query'];
}
public function __toString() : string
{
return $this->getFragment();
}
protected function doInitialize() : void
{
if ($this->fragment !== null) {
$this->data = array_merge($this->data, parse_url($this->fragment));
}
foreach ($this->data as $key => $value) {
$this->data[$key] = $this->preparePartValue($key, $value);
}
}
}