AbstractStreamFactory::create()   C
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
ccs 20
cts 20
cp 1
rs 6.9811
cc 7
eloc 17
nc 7
nop 1
crap 7
1
<?php
2
3
namespace Yuloh\Stream;
4
5
abstract class AbstractStreamFactory implements StreamFactoryInterface
6
{
7
    /**
8
     * {@inheritdoc}
9
     */
10 26
    public function create($resource = null)
11
    {
12 26
        switch (gettype($resource)) {
13 26
            case 'NULL':
14 4
                return $this->forNull();
15 24
            case 'integer':
16 24
            case 'double':
17 24
            case 'string':
18 8
                return $this->forString($resource);
19 16
            case 'object':
20 6
                return $this->forObject($resource);
21 10
            case 'resource':
22 8
                return $this->forResource($resource);
23 2
            default:
24 2
                throw new \InvalidArgumentException(
25 2
                    sprintf(
26 2
                        'Unable to create stream for type "%s"',
27 2
                        gettype($resource)
28 2
                    )
29 2
                );
30 2
        }
31
    }
32
33
    /**
34
     * @param resource $resource
35
     *
36
     * @return \Yuloh\Stream\Stream
37
     */
38
    abstract protected function forResource($resource);
39
40
    /**
41
     * @param object $object
42
     *
43
     * @return \Yuloh\Stream\Stream
44
     */
45 6
    protected function forObject($object)
46
    {
47 6
        if (method_exists($object, '__toString')) {
48 2
            return $this->forString((string) $object);
49
        }
50
51 4
        if ($object instanceof \JsonSerializable) {
52 2
            return $this->forString(json_encode($object));
53
        }
54
55 2
        throw new \InvalidArgumentException(sprintf('Unable to create stream for "%s"', get_class($object)));
56
    }
57
58
    /**
59
     * @param string $string
60
     *
61
     * @return \Yuloh\Stream\Stream
62
     */
63 12
    protected function forString($string)
64
    {
65 12
        $fp = fopen('php://temp', 'r+');
66 12
        if ($string !== '') {
67 10
            fwrite($fp, $string);
68 10
            rewind($fp);
69 10
        }
70 12
        return $this->forResource($fp);
71
    }
72
73
    /**
74
     * @return \Yuloh\Stream\Stream
75
     */
76 2
    protected function forNull()
77
    {
78 2
        return $this->forResource(fopen('php://temp', 'r+'));
79
    }
80
}
81