Stream::process()   D
last analyzed

Complexity

Conditions 9
Paths 6

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 9.0294

Importance

Changes 0
Metric Value
cc 9
eloc 13
nc 6
nop 1
dl 0
loc 27
ccs 13
cts 14
cp 0.9286
crap 9.0294
rs 4.909
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Config\Property;
5
6
use Innmind\Config\{
7
    Property,
8
    Properties,
9
    Exception\SchemaNotParseable,
10
    Exception\InvalidArgumentException,
11
};
12
use Innmind\Immutable;
13
14
final class Stream implements Property
15
{
16
    private const PATTERN = '~^stream<(?<type>.+)>\+?$~';
17
18
    private $type;
19
    private $requiresValue = false;
20
21 13
    private function __construct(string $type)
22
    {
23 13
        $this->type = $type;
24 13
    }
25
26 16
    public static function build(Immutable\Str $schema, Properties $properties): Property
27
    {
28 16
        if (!$schema->matches(self::PATTERN)) {
29 3
            throw new SchemaNotParseable((string) $schema);
30
        }
31
32 13
        $self = new self(
33 13
            (string) $schema->capture(self::PATTERN)->get('type')
34
        );
35
36 13
        if ((string) $schema->substring(-1) === '+') {
37 6
            $self->requiresValue = true;
38
        }
39
40 13
        return $self;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 10
    public function process($value)
47
    {
48 10
        if ($value instanceof Immutable\StreamInterface && (string) $value->type() === $this->type) {
49 1
            if ($this->requiresValue && $value->size() === 0) {
50 1
                throw new InvalidArgumentException;
51
            }
52
53
            return $value;
54
        }
55
56 9
        if ($value instanceof Immutable\StreamInterface) {
57 1
            throw new InvalidArgumentException;
58
        }
59
60 8
        $value = $value ?? [];
61
62 8
        if (!is_array($value)) {
63 2
            throw new InvalidArgumentException;
64
        }
65
66 6
        $stream = Immutable\Stream::of($this->type, ...$value);
67
68 6
        if ($this->requiresValue && $stream->size() === 0) {
69 2
            throw new InvalidArgumentException;
70
        }
71
72 4
        return $stream;
73
    }
74
}
75