1<?php
2namespace GuzzleHttp\Tests\Stream;
3
4use GuzzleHttp\Stream\LazyOpenStream;
5use PHPUnit\Framework\TestCase;
6
7class LazyOpenStreamTest extends TestCase
8{
9    private $fname;
10
11    public function setup(): void
12    {
13        $this->fname = tempnam('/tmp', 'tfile');
14
15        if (file_exists($this->fname)) {
16            unlink($this->fname);
17        }
18    }
19
20    public function tearDown(): void
21    {
22        if (file_exists($this->fname)) {
23            unlink($this->fname);
24        }
25    }
26
27    public function testOpensLazily()
28    {
29        $l = new LazyOpenStream($this->fname, 'w+');
30        $l->write('foo');
31        $this->assertIsArray($l->getMetadata());
32        $this->assertFileExists($this->fname);
33        $this->assertEquals('foo', file_get_contents($this->fname));
34        $this->assertEquals('foo', (string) $l);
35    }
36
37    public function testProxiesToFile()
38    {
39        file_put_contents($this->fname, 'foo');
40        $l = new LazyOpenStream($this->fname, 'r');
41        $this->assertEquals('foo', $l->read(4));
42        $this->assertTrue($l->eof());
43        $this->assertEquals(3, $l->tell());
44        $this->assertTrue($l->isReadable());
45        $this->assertTrue($l->isSeekable());
46        $this->assertFalse($l->isWritable());
47        $l->seek(1);
48        $this->assertEquals('oo', $l->getContents());
49        $this->assertEquals('foo', (string) $l);
50        $this->assertEquals(3, $l->getSize());
51        $this->assertIsArray($l->getMetadata());
52        $l->close();
53    }
54
55    public function testDetachesUnderlyingStream()
56    {
57        file_put_contents($this->fname, 'foo');
58        $l = new LazyOpenStream($this->fname, 'r');
59        $r = $l->detach();
60        $this->assertIsResource($r);
61        fseek($r, 0);
62        $this->assertEquals('foo', stream_get_contents($r));
63        fclose($r);
64    }
65}
66