FormatNegotiator::getRequest()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 5
cp 0.8
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2.032
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\RestBundle\Negotiation;
13
14
use FOS\RestBundle\Util\StopFormatListenerException;
15
use Negotiation\Accept;
16
use Negotiation\AcceptHeader;
17
use Negotiation\Negotiator as BaseNegotiator;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
20
use Symfony\Component\HttpFoundation\RequestStack;
21
22
/**
23
 * @author Ener-Getick <[email protected]>
24
 */
25
final class FormatNegotiator extends BaseNegotiator
26
{
27
    private $map = [];
28
    private $requestStack;
29
    private $mimeTypes;
30
31 25
    public function __construct(RequestStack $requestStack, array $mimeTypes = array())
32
    {
33 25
        $this->requestStack = $requestStack;
34 25
        $this->mimeTypes = $mimeTypes;
35 25
    }
36
37 23
    public function add(RequestMatcherInterface $requestMatcher, array $options = []): void
38
    {
39 23
        $this->map[] = [$requestMatcher, $options];
40 23
    }
41
42 21
    public function getBest($header, array $priorities = []): ?AcceptHeader
43
    {
44 21
        $request = $this->getRequest();
45 21
        $header = $header ?: $request->headers->get('Accept');
46
47 21
        foreach ($this->map as $elements) {
48
            // Check if the current RequestMatcherInterface matches the current request
49 19
            if (!$elements[0]->matches($request)) {
50 1
                continue;
51
            }
52 19
            $options = &$elements[1]; // Do not reallow memory for this variable
53
54 19
            if (!empty($options['stop'])) {
55 1
                throw new StopFormatListenerException('Stopped format listener');
56
            }
57 18
            if (empty($options['priorities']) && empty($priorities)) {
58 3
                if (!empty($options['fallback_format'])) {
59 3
                    return new Accept($request->getMimeType($options['fallback_format']));
60
                }
61
62 1
                continue;
63
            }
64
65 15
            if (isset($options['prefer_extension']) && $options['prefer_extension'] && !isset($extensionHeader)) {
66 10
                $extension = pathinfo($request->getPathInfo(), PATHINFO_EXTENSION);
67
68 10
                if (!empty($extension)) {
69
                    // $extensionHeader will now be either a non empty string or an empty string
70 5
                    $extensionHeader = $request->getMimeType($extension);
71
72 5
                    if ($extensionHeader) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extensionHeader of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
73 2
                        $header = $extensionHeader.'; q='.$options['prefer_extension'].($header ? ','.$header : '');
74
                    }
75
                }
76
            }
77
78 15
            if ($header) {
79 14
                $mimeTypes = $this->normalizePriorities(
80 14
                    $request,
81 14
                    empty($priorities) ? $options['priorities'] : $priorities
82
                );
83
84 14
                $mimeType = parent::getBest($header, $mimeTypes);
85
86 14
                if (null !== $mimeType) {
87 13
                    return $mimeType;
88
                }
89
            }
90
91 2
            if (isset($options['fallback_format'])) {
92
                // if false === fallback_format then we fail here instead of considering more rules
93 2
                if (false === $options['fallback_format']) {
94
                    return null;
95
                }
96
97
                // stop looking at rules since we have a fallback defined
98 2
                return new Accept($request->getMimeType($options['fallback_format']));
99
            }
100
        }
101
102 4
        return null;
103
    }
104
105 14
    private function sanitize(array $values): array
106
    {
107
        return array_map(function ($value) {
108 14
            return preg_replace('/\s+/', '', strtolower($value));
109 14
        }, $values);
110
    }
111
112
    /**
113
     * @param string[] $priorities
114
     *
115
     * @return string[] formatted priorities
116
     */
117 14
    private function normalizePriorities(Request $request, array $priorities): array
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
118
    {
119 14
        $priorities = $this->sanitize($priorities);
120
121 14
        $mimeTypes = array();
122 14
        foreach ($priorities as $priority) {
123 14
            if (strpos($priority, '/')) {
124 4
                $mimeTypes[] = $priority;
125
126 4
                continue;
127
            }
128
129 11
            $mimeTypes = array_merge($mimeTypes, Request::getMimeTypes($priority));
130
131 11
            if (isset($this->mimeTypes[$priority])) {
132 3
                foreach ($this->mimeTypes[$priority] as $mimeType) {
133 3
                    $mimeTypes[] = $mimeType;
134
                }
135
            }
136
        }
137
138 14
        return $mimeTypes;
139
    }
140
141 21
    private function getRequest(): Request
142
    {
143 21
        $request = $this->requestStack->getCurrentRequest();
144 21
        if (null === $request) {
145
            throw new \RuntimeException('There is no current request.');
146
        }
147
148 21
        return $request;
149
    }
150
}
151