1<?php
2declare(strict_types=1);
3
4namespace ILIAS\Filesystem\Util;
5
6/**
7 * Class PHPFunctions
8 *
9 * The purpose of this class is to wrap all stream handling php functions.
10 *
11 * This allows to mock the functions within unit test which would otherwise require us to redefine the
12 * function in a scope which is scanned before the root scope and somehow call the function on our mocks the verify the
13 * function calls.
14 *
15 * @author  Nicolas Schäfli <ns@studer-raimann.ch>
16 * @since 5.3
17 * @version 1.0.0
18 */
19final class PHPStreamFunctions
20{
21
22    /**
23     * ftell wrapper
24     *
25     * @param $handle
26     *
27     * @return bool|int
28     *
29     * @see ftell()
30     */
31    public static function ftell($handle)
32    {
33        return ftell($handle);
34    }
35
36
37    /**
38     * fclose wrapper
39     *
40     * @param $handle
41     *
42     * @see fclose()
43     */
44    public static function fclose($handle)
45    {
46        fclose($handle);
47    }
48
49
50    /**
51     * fseek wrapper.
52     *
53     * @param $stream
54     * @param $offset
55     * @param $whence
56     *
57     * @return int 0 or -1
58     */
59    public static function fseek($stream, $offset, $whence)
60    {
61        return fseek($stream, $offset, $whence);
62    }
63
64
65    /**
66     * fread wrapper
67     *
68     * @param $handle
69     * @param $length
70     *
71     * @return bool|string
72     *
73     * @see fread()
74     */
75    public static function fread($handle, $length)
76    {
77        return fread($handle, $length);
78    }
79
80
81    /**
82     * stream_get_contents wrapper
83     *
84     * @param $handle
85     * @param $length
86     *
87     * @return bool|string
88     *
89     * @see stream_get_contents()
90     */
91    public static function stream_get_contents($handle, $length = -1)
92    {
93        return stream_get_contents($handle, $length);
94    }
95
96
97    /**
98     * fwrite wrapper
99     *
100     * @param      $handle
101     * @param      $string
102     * @param null $length
103     *
104     * @return bool|int
105     *
106     * @see fwrite()
107     */
108    public static function fwrite($handle, $string, $length = null)
109    {
110
111        //it seems like php juggles the null to 0 and pass it to the function which leads to a write operation of zero length ...
112        if (is_null($length)) {
113            return fwrite($handle, $string);
114        }
115
116        return fwrite($handle, $string, $length);
117    }
118}
119