File: Stream.php Lines 1 to 22 |
| 1 | <?php |
| 2 | namespace Puyo\Psr7; |
| 3 | |
| 4 | /** |
| 5 | * ストリームを抽象化したもの |
| 6 | * |
| 7 | * PSR-7 の StreamInterface の実装。 |
| 8 | * HTTPに限らず利用できるが、現状はバイナリにしか対応していない。 |
| 9 | */ |
| | class Stream implements \Psr\Http\Message\StreamInterface { |
| 11 | /** @var resource */ |
| | protected $fp; |
| 13 | |
| 14 | /** |
| 15 | * ファイルのパスから生成した場合に内部で開くためのStream |
| 16 | * @var resource |
| 17 | */ |
| 18 | protected $tmpFp; |
| 19 | |
| 20 | /** |
| 21 | * ファイルのフルパスもしくはresourceから生成する |
| 22 | * @param resource|string $fileOrStream |
|
File: Stream.php Lines 52 to 79 |
| 52 | |
| 53 | /** |
| 54 | * {@inheritdoc} |
| 55 | */ |
| 56 | public function close() { |
| 57 | if(!$this->fp) { |
| 58 | return; |
| 59 | } |
| 60 | |
| | $fp = $this->detach(); |
| 62 | fclose($fp); |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * @return resource |
| 67 | */ |
| 68 | public function detach() { |
| | $fp = $this->fp; |
| 70 | $this->fp = null; |
| 71 | return $fp; |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * streamもしくはファイルのフルパスからstreamを割り当てる |
| 76 | * @param string|resource $fileOrStream |
| 77 | * @param string $mode |
| 78 | */ |
| 79 | public function attach($fileOrStream, $mode='rb') { |
|
File: Stream.php Lines 275 to 297 |
| 275 | if (!array_key_exists($key, $metadata)) { |
| 276 | return null; |
| 277 | } |
| 278 | |
| 279 | return $metadata[$key]; |
| 280 | } |
| 281 | |
| 282 | private function setStream($fileOrStream, $mode='rb') { |
| 283 | $error = null; |
| | $fp = $tmpFp = null; |
| 285 | |
| 286 | if(is_string($fileOrStream)) { |
| | set_error_handler(function ($e) use (&$error) { |
| 288 | $error = $e; |
| 289 | }, E_WARNING); |
| 290 | $tmpFp = fopen($fileOrStream, $mode); |
| 291 | restore_error_handler(); |
| 292 | |
| 293 | if($error !== null) { |
| 294 | throw new \InvalidArgumentException('Invalid stream reference provided'); |
| 295 | } |
| 296 | } else if($this->isAvailableStream($fileOrStream)) { |
| 297 | $fp = $fileOrStream; |
|
File: Stream.php Lines 301 to 320 |
| 301 | if($tmpFp !== null) { |
| 302 | $this->fp = $this->tmpFp = $tmpFp; |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | /** |
| 307 | * @param resource $fp |
| 308 | * @return bool |
| 309 | */ |
| | private function isAvailableStream($fp) { |
| 311 | if(is_resource($fp) && 'stream' === get_resource_type($fp)) { |
| 312 | return true; |
| 313 | } |
| 314 | return false; |
| 315 | } |
| 316 | |
| 317 | private function closeTmpStream() { |
| 318 | if($this->isAvailableStream($this->tmpFp)) { |
| 319 | fclose($this->tmpFp); |
| 320 | } |
|