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

ArrayOffsetHttpFields::format()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Bdf\Form\Child\Http;
4
5
/**
6
 * Extract HTTP fields value using a simple array offset
7
 * This is the default http fields implementation
8
 *
9
 * <code>
10
 * $fields = new ArrayOffsetHttpFields('child');
11
 *
12
 * $fields->extract(['child' => 'value'], 'not found'); // => 'value'
13
 * $fields->extract(['other' => 'value'], 'not found'); // => 'not found'
14
 * </code>
15
 */
16
final class ArrayOffsetHttpFields implements HttpFieldsInterface
17
{
18
    /**
19
     * @var string
20
     */
21
    private $offset;
22
23
24
    /**
25
     * ArrayOffsetHttpFields constructor.
26
     *
27
     * @param string $offset The field name
28
     */
29 281
    public function __construct(string $offset)
30
    {
31 281
        $this->offset = $offset;
32 281
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37 101
    public function extract($httpFields, $defaultValue)
38
    {
39 101
        if (!is_array($httpFields) || !isset($httpFields[$this->offset])) {
40 23
            return $defaultValue;
41
        }
42
43 82
        $value = $httpFields[$this->offset];
44
45
        // No default value : return the real submitted value
46 82
        if ($defaultValue === null) {
47 77
            return $value;
48
        }
49
50 5
        return $value !== '' && $value !== null && $value !== [] ? $value : $defaultValue;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 11
    public function contains($httpFields): bool
57
    {
58 11
        return isset($httpFields[$this->offset]);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64 6
    public function format($value)
65
    {
66 6
        return [$this->offset => $value];
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 14
    public function get(?HttpFieldPath $path = null): HttpFieldPath
73
    {
74 14
        return $path === null ? HttpFieldPath::named($this->offset) : $path->add($this->offset);
75
    }
76
}
77