class StreamEncoder in Replication 8
Same name and namespace in other branches
- 8.2 src/Encoder/StreamEncoder.php \Drupal\replication\Encoder\StreamEncoder
Hierarchy
- class \Drupal\replication\Encoder\StreamEncoder implements \Symfony\Component\Serializer\Encoder\EncoderInterface, \Symfony\Component\Serializer\Encoder\DecoderInterface
Expanded class hierarchy of StreamEncoder
1 file declares its use of StreamEncoder
- StreamEncoderTest.php in tests/
src/ Kernel/ Encoder/ StreamEncoderTest.php
1 string reference to 'StreamEncoder'
2 services use StreamEncoder
File
- src/
Encoder/ StreamEncoder.php, line 9
Namespace
Drupal\replication\EncoderView source
class StreamEncoder implements EncoderInterface, DecoderInterface {
/**
* @var array
*/
protected $formats = [
'stream',
'base64_stream',
];
/**
* @param \Drupal\Component\Utility\Random $random
*/
protected $random;
public function __construct(Random $random = NULL) {
$this->random = $random ?: new Random();
}
/**
* {@inheritdoc}
*/
public function encode($data, $format, array $context = []) {
if (!is_resource($data)) {
throw new \InvalidArgumentException(sprintf('Data argument is not a resource.'));
}
$contents = stream_get_contents($data);
return $format == 'base64_stream' ? base64_encode($contents) : $contents;
}
/**
* {@inheritdoc}
*/
public function decode($data, $format, array $context = []) {
if (!is_scalar($data)) {
throw new \InvalidArgumentException(sprintf('Data argument is not a scalar.'));
}
$uri = !empty($context['uri']) ? $context['uri'] : 'temporary://' . $this->random
->name();
$mode = !empty($context['mode']) ? $context['mode'] : 'w+b';
$stream = fopen($uri, $mode);
$data = $format == 'base64_stream' ? base64_decode($data) : $data;
fwrite($stream, $data);
// Put the file pointer back to the beginning.
rewind($stream);
return $stream;
}
/**
* {@inheritdoc}
*/
public function supportsEncoding($format) {
return in_array($format, $this->formats);
}
/**
* {@inheritdoc}
*/
public function supportsDecoding($format) {
return in_array($format, $this->formats);
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
StreamEncoder:: |
protected | property | ||
StreamEncoder:: |
protected | property | ||
StreamEncoder:: |
public | function | Decodes a string into PHP data. | |
StreamEncoder:: |
public | function | Encodes data into the given format. | |
StreamEncoder:: |
public | function | Checks whether the deserializer can decode from given format. | |
StreamEncoder:: |
public | function | Checks whether the serializer can encode to given format. | |
StreamEncoder:: |
public | function |