xref: /PHP-8.2/ext/standard/tests/file/bug38450.phpt (revision 902d6439)
1--TEST--
2Bug #38450 (constructor is not called for classes used in userspace stream wrappers)
3--FILE--
4<?php
5
6class VariableStream {
7    var $context;
8    var $position;
9    var $varname;
10
11    function __construct($var=null) {
12        var_dump("constructor!");
13    }
14
15    function stream_open($path, $mode, $options, &$opened_path)
16    {
17        $url = parse_url($path);
18        $this->varname = $url["host"];
19        $this->position = 0;
20
21        return true;
22    }
23
24    function stream_read($count)
25    {
26        $ret = substr($GLOBALS[$this->varname], $this->position, $count);
27        $this->position += strlen($ret);
28        return $ret;
29    }
30
31    function stream_write($data)
32    {
33        $left = substr($GLOBALS[$this->varname], 0, $this->position);
34        $right = substr($GLOBALS[$this->varname], $this->position + strlen($data));
35        $GLOBALS[$this->varname] = $left . $data . $right;
36        $this->position += strlen($data);
37        return strlen($data);
38    }
39
40    function stream_tell()
41    {
42        return $this->position;
43    }
44
45    function stream_eof()
46    {
47        return $this->position >= strlen($GLOBALS[$this->varname]);
48    }
49    function stream_seek($offset, $whence)
50    {
51        switch ($whence) {
52        case SEEK_SET:
53            if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) {
54                $this->position = $offset;
55                return true;
56            } else {
57                return false;
58            }
59            break;
60
61        case SEEK_CUR:
62            if ($offset >= 0) {
63                $this->position += $offset;
64                return true;
65            } else {
66                return false;
67            }
68            break;
69
70        case SEEK_END:
71            if (strlen($GLOBALS[$this->varname]) + $offset >= 0) {
72                $this->position = strlen($GLOBALS[$this->varname]) + $offset;
73                return true;
74            } else {
75                return false;
76            }
77            break;
78
79        default:
80            return false;
81        }
82    }
83}
84
85stream_wrapper_register("var", "VariableStream")
86    or die("Failed to register protocol");
87
88$myvar = "";
89
90$fp = fopen("var://myvar", "r+");
91
92fwrite($fp, "line1\n");
93fwrite($fp, "line2\n");
94fwrite($fp, "line3\n");
95
96rewind($fp);
97while (!feof($fp)) {
98    echo fgets($fp);
99}
100fclose($fp);
101var_dump($myvar);
102
103echo "Done\n";
104?>
105--EXPECT--
106string(12) "constructor!"
107line1
108line2
109line3
110string(18) "line1
111line2
112line3
113"
114Done
115