|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace RealPage\JsonApi; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Http\Request; |
|
6
|
|
|
|
|
7
|
|
|
class MediaTypeGuard |
|
8
|
|
|
{ |
|
9
|
|
|
protected $contentType; |
|
10
|
|
|
|
|
11
|
18 |
|
public function __construct(string $contentType, string $acceptHeaderPolicy) |
|
12
|
|
|
{ |
|
13
|
18 |
|
$this->contentType = $contentType; |
|
14
|
18 |
|
$this->acceptHeaderPolicy = $acceptHeaderPolicy; |
|
|
|
|
|
|
15
|
18 |
|
} |
|
16
|
|
|
|
|
17
|
15 |
|
public function getContentType(): string |
|
18
|
|
|
{ |
|
19
|
15 |
|
return $this->contentType; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
3 |
|
public function getAcceptHeaderPolicy(): string |
|
23
|
|
|
{ |
|
24
|
3 |
|
return $this->acceptHeaderPolicy; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
3 |
|
public function validateExistingContentType(Request $request): bool |
|
28
|
|
|
{ |
|
29
|
3 |
|
return str_is($this->getContentType(), $request->header('Accept')) || str_is('', $request->header('Accept')); |
|
|
|
|
|
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
6 |
|
public function clientRequestMustHaveContentTypeHeader(Request $request) |
|
33
|
|
|
{ |
|
34
|
6 |
|
$method = $request->method(); |
|
35
|
6 |
|
return $method === 'POST' || $method === 'PATCH'; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
6 |
|
public function contentTypeIsValid(string $contentType): bool |
|
39
|
|
|
{ |
|
40
|
6 |
|
return str_is($this->getContentType(), $contentType); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
3 |
|
public function hasCorrectHeadersForData(Request $request): bool |
|
44
|
|
|
{ |
|
45
|
3 |
|
if ($this->clientRequestMustHaveContentTypeHeader($request)) { |
|
46
|
3 |
|
return $request->hasHeader('Content-Type') && $this->contentTypeIsValid($request->header('Content-Type')); |
|
|
|
|
|
|
47
|
|
|
} |
|
48
|
3 |
|
return true; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
3 |
|
public function hasCorrectlySetAcceptHeader(Request $request): bool |
|
52
|
|
|
{ |
|
53
|
3 |
|
if ($this->acceptHeaderPolicy === 'ignore') { |
|
54
|
3 |
|
return true; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
3 |
|
$accept = $request->header('Accept'); |
|
58
|
3 |
|
if (empty($accept)) { |
|
59
|
3 |
|
return $this->acceptHeaderPolicy !== 'require'; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
3 |
|
if ('*/*' === $accept) { |
|
63
|
3 |
|
return true; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
3 |
|
return substr_count($accept, $this->getContentType()) > substr_count($accept, $this->getContentType() . ';'); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: