1<?php 2 3declare(strict_types=1); 4 5/* 6 * This file is part of the TYPO3 CMS project. 7 * 8 * It is free software; you can redistribute it and/or modify it under 9 * the terms of the GNU General Public License, either version 2 10 * of the License, or any later version. 11 * 12 * For the full copyright and license information, please read the 13 * LICENSE.txt file that was distributed with this source code. 14 * 15 * The TYPO3 project - inspiring people to share! 16 */ 17 18namespace TYPO3\CMS\Core\Http; 19 20use Psr\Http\Message\StreamFactoryInterface; 21use Psr\Http\Message\StreamInterface; 22 23/** 24 * @internal Note that this is not public API, use PSR-17 interfaces instead. 25 */ 26class StreamFactory implements StreamFactoryInterface 27{ 28 /** 29 * Create a new stream from a string. 30 * 31 * @param string $content String content with which to populate the stream. 32 * @return StreamInterface 33 */ 34 public function createStream(string $content = ''): StreamInterface 35 { 36 $stream = new Stream('php://temp', 'r+'); 37 if ($content !== '') { 38 $stream->write($content); 39 } 40 return $stream; 41 } 42 43 /** 44 * Create a stream from an existing file. 45 * 46 * The `$filename` MAY be any string supported by `fopen()`. 47 * 48 * @param string $filename Filename or stream URI to use as basis of stream. 49 * @param string $mode Mode with which to open the underlying filename/stream. 50 * @return StreamInterface 51 * @throws \RuntimeException If the file cannot be opened. 52 * @throws \InvalidArgumentException If the mode is invalid. 53 */ 54 public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface 55 { 56 $resource = @fopen($filename, $mode); 57 if ($resource === false) { 58 if ($mode === '' || in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], true) === false) { 59 throw new \InvalidArgumentException('The mode ' . $mode . ' is invalid.', 1566823434); 60 } 61 62 throw new \RuntimeException('The file ' . $filename . ' cannot be opened.', 1566823435); 63 } 64 65 return new Stream($resource); 66 } 67 68 /** 69 * Create a new stream from an existing resource. 70 * 71 * The stream MUST be readable and may be writable. 72 * 73 * @param resource $resource PHP resource to use as basis of stream. 74 * @return StreamInterface 75 * @throws \InvalidArgumentException 76 */ 77 public function createStreamFromResource($resource): StreamInterface 78 { 79 if (!is_resource($resource) || get_resource_type($resource) !== 'stream') { 80 throw new \InvalidArgumentException('Invalid stream provided; must be a stream resource', 1566853697); 81 } 82 return new Stream($resource); 83 } 84} 85