StreamFactory::createZendDiactorosStream()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Schnittstabil\Psr7\Csrf\Helpers;
4
5
use Psr\Http\Message\StreamInterface;
6
7
/**
8
 * The stream factory service locator.
9
 */
10
class StreamFactory
11
{
12
    protected static $factory;
13
14
    /**
15
     * Create a Stream.
16
     *
17
     * @throws \RuntimeException if no factory is set
18
     *
19
     * @return StreamInterface
20
     */
21
    public function __invoke()
22
    {
23
        return $this->create();
24
    }
25
26
    /**
27
     * Set the stream factory.
28
     *
29
     * @param callable $factory the new stream factory
30
     *
31
     * @return callable
32
     */
33
    public static function set(callable $factory)
34
    {
35
        return static::$factory = $factory;
36
    }
37
38
    /**
39
     * Get a stream factory.
40
     *
41
     * @throws \RuntimeException if no factory is set
42
     *
43
     * @return callable
44
     */
45
    public static function get()
46
    {
47
        if (static::$factory === null) {
48
            static::$factory = static::autodetectFactory();
49
        }
50
51
        return static::$factory;
52
    }
53
54
    /**
55
     * Create a Stream.
56
     *
57
     * @throws \RuntimeException if no factory is set
58
     *
59
     * @return StreamInterface
60
     */
61
    public static function create()
62
    {
63
        return call_user_func(static::get());
64
    }
65
66
    /**
67
     * Get a \Slim\Http\Stream factory.
68
     *
69
     * @return StreamInterface
70
     */
71
    public static function createSlimHttpStream()
72
    {
73
        return new \Slim\Http\Stream(fopen('php://temp', 'r+'));
74
    }
75
76
    /**
77
     * Get \Zend\Diactoros\Stream factory.
78
     *
79
     * @return StreamInterface
80
     */
81
    public static function createZendDiactorosStream()
82
    {
83
        return new \Zend\Diactoros\Stream('php://temp', 'r+');
84
    }
85
86
    /**
87
     * Try to autodetect a stream factory.
88
     *
89
     * @throws \RuntimeException if no factory is found
90
     *
91
     * @return StreamInterface
92
     */
93
    protected static function autodetectFactory()
94
    {
95
        if (class_exists('Slim\\Http\\Stream')) {
96
            return [static::class, 'createSlimHttpStream'];
97
        }
98
99
        // @codeCoverageIgnoreStart
100
        if (class_exists('Zend\\Diactoros\\Stream')) {
101
            return [static::class, 'createZendDiactorosStream'];
102
        }
103
104
        throw new \RuntimeException('No stream factory found');
105
        // @codeCoverageIgnoreEnd
106
    }
107
}
108