Completed
Pull Request — 2.x (#2227)
by
unknown
08:36
created

FormatNegotiator   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 90.32%

Importance

Changes 0
Metric Value
wmc 29
lcom 1
cbo 6
dl 0
loc 126
ccs 56
cts 62
cp 0.9032
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A add() 0 4 1
D getBest() 0 62 19
A sanitize() 0 6 1
A normalizePriorities() 0 23 5
A getRequest() 0 9 2
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
    public function __construct(RequestStack $requestStack, array $mimeTypes = array())
32 29
    {
33
        $this->requestStack = $requestStack;
34 29
        $this->mimeTypes = $mimeTypes;
35 29
    }
36 29
37
    public function add(RequestMatcherInterface $requestMatcher, array $options = []): void
38 27
    {
39
        $this->map[] = [$requestMatcher, $options];
40 27
    }
41 27
42
    public function getBest($header, array $priorities = []): ?AcceptHeader
43 24
    {
44
        $request = $this->getRequest();
45 24
        $header = $header ?: $request->headers->get('Accept');
46 24
47
        foreach ($this->map as $elements) {
48 24
            // Check if the current RequestMatcherInterface matches the current request
49
            if (!$elements[0]->matches($request)) {
50 22
                continue;
51 1
            }
52
            $options = &$elements[1]; // Do not reallow memory for this variable
53 22
54
            if (!empty($options['stop'])) {
55 22
                throw new StopFormatListenerException('Stopped format listener');
56 1
            }
57
            if (empty($options['priorities']) && empty($priorities)) {
58 21
                if (!empty($options['fallback_format'])) {
59 4
                    return new Accept($request->getMimeType($options['fallback_format']));
60 4
                }
61
62
                continue;
63 1
            }
64
65
            if (isset($options['prefer_extension']) && $options['prefer_extension'] && !isset($extensionHeader)) {
66 17
                $extension = pathinfo($request->getPathInfo(), PATHINFO_EXTENSION);
67 12
68
                if (!empty($extension)) {
69 12
                    // $extensionHeader will now be either a non empty string or an empty string
70
                    $extensionHeader = $request->getMimeType($extension);
71 6
72
                    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 6
                        $header = $extensionHeader.'; q='.$options['prefer_extension'].($header ? ','.$header : '');
74 3
                    }
75
                }
76
            }
77
78
            if ($header) {
79 17
                $mimeTypes = $this->normalizePriorities(
80 16
                    $request,
81 16
                    empty($priorities) ? $options['priorities'] : $priorities
82 16
                );
83
84
                $mimeType = parent::getBest($header, $mimeTypes);
85 16
86
                if (null !== $mimeType) {
87 16
                    return $mimeType;
88 15
                }
89
            }
90
91
            if (isset($options['fallback_format'])) {
92 2
                // if false === fallback_format then we fail here instead of considering more rules
93
                if (false === $options['fallback_format']) {
94 2
                    return null;
95
                }
96
97
                // stop looking at rules since we have a fallback defined
98
                return new Accept($request->getMimeType($options['fallback_format']));
99 2
            }
100
        }
101
102 4
        return null;
103
    }
104 16
105
    private function sanitize(array $values): array
106
    {
107 16
        return array_map(function ($value) {
108 16
            return preg_replace('/\s+/', '', strtolower($value));
109
        }, $values);
110
    }
111
112
    /**
113
     * @param string[] $priorities
114
     *
115
     * @return string[] formatted priorities
116 16
     */
117
    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 16
    {
119
        $priorities = $this->sanitize($priorities);
120 16
121 16
        $mimeTypes = array();
122 16
        foreach ($priorities as $priority) {
123 4
            if (strpos($priority, '/')) {
124
                $mimeTypes[] = $priority;
125 4
126
                continue;
127
            }
128 13
129 13
            $mimeTypes = array_merge($mimeTypes, Request::getMimeTypes($priority));
130
131
            if (isset($this->mimeTypes[$priority])) {
132
                foreach ($this->mimeTypes[$priority] as $mimeType) {
133
                    $mimeTypes[] = $mimeType;
134
                }
135
            }
136 13
        }
137 3
138 3
        return $mimeTypes;
139
    }
140
141
    private function getRequest(): Request
142
    {
143 16
        $request = $this->requestStack->getCurrentRequest();
144
        if (null === $request) {
145
            throw new \RuntimeException('There is no current request.');
146 24
        }
147
148 24
        return $request;
149 24
    }
150
}
151