/**
* Create a new stream from an existing resource.
*
* The stream MUST be readable and may be writable.
*
* @param resource $resource The PHP resource to use as the basis for the stream.
*/
public function createStreamFromResource($resource): StreamInterface;
$resource = fopen(tempnam(sys_get_temp_dir(), 'psr17'), 'w');
fwrite($resource, 'Foobar');
$stream = $factory->createFromResource($resource);
Thanks for bringing this up, Martijn. I agree that bit is rather
awkward and should be clarified and tested better.
I think the docblock was intended to read:
> The resource MUST be readable and may be writable.
However, even if that was the case, how would it be enforced? I don't
know of a way to check if a resource is readable.
if (false === is_resource($resource) ||
'stream' !== get_resource_type($resource) ||
true === array_key_exists('stream_type', $metadata = stream_get_meta_data($resource)) && $metadata['stream_type'] === 'dir' ||
false === array_key_exists('mode', $metadata) ||
in_array($metadata['mode'], ['r', 'r+', 'w+', 'a+', 'x+', 'c+'])
) {
throw new \InvalidArgumentException('resource must be readable and of type stream.');
}
This may require an errata to PSR-17.
I think the docblock was intended to read:
> The resource MUST be readable and may be writable.
However, even if that was the case, how would it be enforced? I don't
know of a way to check if a resource is readable.
This may require an errata to PSR-17.