Completed
Push — master ( c5de01...c9c19d )
by
unknown
07:34 queued 05:10
created

Parser::extractPlaceholders()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 15
nc 5
nop 2
1
<?php
2
3
namespace Coduo\TuTu\Request\Path;
4
5
use Symfony\Component\HttpFoundation\Request;
6
7
class Parser
8
{
9
    public function extractPlaceholders(Request $request, $pathPattern)
10
    {
11
        preg_match_all('#\{\w+\}#', $pathPattern, $placeholders, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
12
13
        if (!count($placeholders)) {
14
            return array();
15
        }
16
17
        $placeholderNames = array();
18
        foreach ($placeholders as $placeholderMatch) {
0 ignored issues
show
Bug introduced by
The expression $placeholders of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
19
            $placeholder = $placeholderMatch[0][0];
20
            $placeholderNames[] = substr($placeholder, 1, -1);
21
            $pathPattern = str_replace($placeholder, '__PLACEHOLDER__', $pathPattern);
22
        }
23
24
        $pathPattern = '/^' . str_replace('__PLACEHOLDER__', '([^\/]*)', preg_quote($pathPattern, '/')) . '$/i';
25
26
        if (0 === preg_match($pathPattern, $request->getPathInfo(), $matches)) {
27
            return array();
28
        }
29
30
        return array_combine(
31
            $placeholderNames,
32
            array_slice($matches, 1, count($placeholders))
33
        );
34
    }
35
}
36