1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the runopencode/sax, an RunOpenCode project. |
4
|
|
|
* |
5
|
|
|
* (c) 2017 RunOpenCode |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
namespace RunOpenCode\Sax\StreamAdapter; |
11
|
|
|
|
12
|
|
|
use RunOpenCode\Sax\Contract\StreamAdapterInterface; |
13
|
|
|
use RunOpenCode\Sax\Exception\StreamAdapterException; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class StringAdapter |
17
|
|
|
* |
18
|
|
|
* String adapter |
19
|
|
|
* |
20
|
|
|
* @package RunOpenCode\Sax\StreamAdapter |
21
|
|
|
*/ |
22
|
|
|
class StringAdapter implements StreamAdapterInterface |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
private $streamClass; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var array |
31
|
|
|
*/ |
32
|
|
|
private $options; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* StringAdapter constructor. |
36
|
|
|
* |
37
|
|
|
* @param string $streamClass FQCN of StreamInterface implementation, GuzzleHttp\Psr7\Stream is used by default. |
38
|
|
|
* @param array $options Adapter options. |
39
|
|
|
*/ |
40
|
2 |
|
public function __construct($streamClass = 'GuzzleHttp\\Psr7\\Stream', array $options = array()) |
41
|
|
|
{ |
42
|
2 |
|
$this->streamClass = $streamClass; |
43
|
2 |
|
$this->options = array_merge(array( |
44
|
2 |
|
'stream' => 'php://memory', |
45
|
2 |
|
), $options); |
46
|
2 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* {@inheritdoc} |
50
|
|
|
*/ |
51
|
2 |
|
public function supports($xmlDocument) |
52
|
|
|
{ |
53
|
2 |
|
return is_string($xmlDocument) && 0 === stripos($xmlDocument, '<?xml'); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* {@inheritdoc} |
58
|
|
|
*/ |
59
|
1 |
View Code Duplication |
public function convert($xmlDocument) |
|
|
|
|
60
|
|
|
{ |
61
|
1 |
|
$stream = @fopen($this->options['stream'], 'r+b'); |
62
|
|
|
|
63
|
1 |
|
if (false === $stream) { |
64
|
|
|
throw new StreamAdapterException(sprintf('Unable to acquire resource handler on "%s".', $this->options['stream'])); |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
fwrite($stream, $xmlDocument); |
68
|
|
|
|
69
|
1 |
|
if (false === @rewind($stream)) { |
70
|
|
|
throw new StreamAdapterException('Unable to to rewind stream.'); |
71
|
|
|
} |
72
|
|
|
|
73
|
1 |
|
return new $this->streamClass($stream); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.