Passed
Branch master (3daac1)
by Vincent
07:53
created

PrefixedHttpFields   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 19
c 1
b 0
f 0
dl 0
loc 70
ccs 22
cts 22
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 9 2
A contains() 0 3 1
A get() 0 3 2
A __construct() 0 3 1
A extract() 0 19 6
1
<?php
2
3
namespace Bdf\Form\Child\Http;
4
5
/**
6
 * Extract HTTP fields value prefixed by a given string
7
 *
8
 * Note: Supports only array values
9
 *
10
 * <code>
11
 * $fields = new PrefixedHttpFields('child');
12
 *
13
 * $fields->extract(['child_foo' => 'bar', 'other_foo' => 'baz'], 'not found'); // => ['foo' => 'bar']
14
 * $fields->extract(['other' => 'value'], ['not found']); // => ['not found']
15
 * </code>
16
 */
17
final class PrefixedHttpFields implements HttpFieldsInterface
18
{
19
    /**
20
     * @var string
21
     */
22
    private $prefix;
23
24
25
    /**
26
     * ArrayOffsetHttpFields constructor.
27
     *
28
     * @param string $prefix The http fields prefix
29
     */
30 17
    public function __construct(string $prefix)
31
    {
32 17
        $this->prefix = $prefix;
33 17
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 13
    public function extract($httpFields, $defaultValue)
39
    {
40 13
        $data = (array) $httpFields;
41 13
        $prefixLen = strlen($this->prefix);
42
43 13
        if ($prefixLen > 0) {
44 12
            $value = [];
45
46 12
            foreach ($data as $name => $datum) {
47 8
                if (strpos($name, $this->prefix) === 0) {
48 6
                    $value[substr($name, $prefixLen)] = $datum;
49
                }
50
            }
51
        } else {
52 1
            $value = $data;
53
        }
54
55
        // Return default value only if provided
56 13
        return $defaultValue !== null && empty($value) ? $defaultValue : $value;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 1
    public function contains($httpFields): bool
63
    {
64 1
        return true; // Always true ?
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70 1
    public function format($value)
71
    {
72 1
        $http = [];
73
74 1
        foreach ($value as $field => $fieldValue) {
75 1
            $http[$this->prefix.$field] = $fieldValue;
76
        }
77
78 1
        return $http;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84 2
    public function get(?HttpFieldPath $path = null): HttpFieldPath
85
    {
86 2
        return $path === null ? HttpFieldPath::prefixed($this->prefix) : $path->prefix($this->prefix);
87
    }
88
}
89