1<?php
2
3/**
4 * Hoa
5 *
6 *
7 * @license
8 *
9 * New BSD License
10 *
11 * Copyright © 2007-2017, Hoa community. All rights reserved.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions are met:
15 *     * Redistributions of source code must retain the above copyright
16 *       notice, this list of conditions and the following disclaimer.
17 *     * Redistributions in binary form must reproduce the above copyright
18 *       notice, this list of conditions and the following disclaimer in the
19 *       documentation and/or other materials provided with the distribution.
20 *     * Neither the name of the Hoa nor the names of its contributors may be
21 *       used to endorse or promote products derived from this software without
22 *       specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
35 */
36
37namespace Hoa\File\Temporary;
38
39use Hoa\File;
40use Hoa\Stream;
41
42/**
43 * Class \Hoa\File\Temporary\Write.
44 *
45 * Write into a temporary file.
46 *
47 * @copyright  Copyright © 2007-2017 Hoa community
48 * @license    New BSD License
49 */
50class Write extends Temporary implements Stream\IStream\Out
51{
52    /**
53     * Open a file.
54     *
55     * @param   string  $streamName    Stream name.
56     * @param   string  $mode          Open mode, see the parent::MODE_* constants.
57     * @param   string  $context       Context ID (please, see the
58     *                                 \Hoa\Stream\Context class).
59     * @param   bool    $wait          Differ opening or not.
60     */
61    public function __construct(
62        $streamName,
63        $mode    = parent::MODE_APPEND_WRITE,
64        $context = null,
65        $wait    = false
66    ) {
67        parent::__construct($streamName, $mode, $context, $wait);
68
69        return;
70    }
71
72    /**
73     * Open the stream and return the associated resource.
74     *
75     * @param   string               $streamName    Stream name (e.g. path or URL).
76     * @param   \Hoa\Stream\Context  $context       Context.
77     * @return  resource
78     * @throws  \Hoa\File\Exception\FileDoesNotExist
79     * @throws  \Hoa\File\Exception
80     */
81    protected function &_open($streamName, Stream\Context $context = null)
82    {
83        static $createModes = [
84            parent::MODE_TRUNCATE_WRITE,
85            parent::MODE_APPEND_WRITE,
86            parent::MODE_CREATE_WRITE
87        ];
88
89        if (!in_array($this->getMode(), $createModes)) {
90            throw new File\Exception(
91                'Open mode are not supported; given %d. Only %s are supported.',
92                0,
93                [$this->getMode(), implode(', ', $createModes)]
94            );
95        }
96
97        preg_match('#^(\w+)://#', $streamName, $match);
98
99        if (((isset($match[1]) && $match[1] == 'file') || !isset($match[1])) &&
100            !file_exists($streamName)) {
101            throw new File\Exception\FileDoesNotExist(
102                'File %s does not exist.',
103                1,
104                $streamName
105            );
106        }
107
108        $out = parent::_open($streamName, $context);
109
110        return $out;
111    }
112
113    /**
114     * Write n characters.
115     *
116     * @param   string  $string    String.
117     * @param   int     $length    Length.
118     * @return  mixed
119     * @throws  \Hoa\File\Exception
120     */
121    public function write($string, $length)
122    {
123        if (0 > $length) {
124            throw new File\Exception(
125                'Length must be greater than 0, given %d.',
126                2,
127                $length
128            );
129        }
130
131        return fwrite($this->getStream(), $string, $length);
132    }
133
134    /**
135     * Write a string.
136     *
137     * @param   string  $string    String.
138     * @return  mixed
139     */
140    public function writeString($string)
141    {
142        $string = (string) $string;
143
144        return $this->write($string, strlen($string));
145    }
146
147    /**
148     * Write a character.
149     *
150     * @param   string  $char    Character.
151     * @return  mixed
152     */
153    public function writeCharacter($char)
154    {
155        return $this->write((string) $char[0], 1);
156    }
157
158    /**
159     * Write a boolean.
160     *
161     * @param   bool    $boolean    Boolean.
162     * @return  mixed
163     */
164    public function writeBoolean($boolean)
165    {
166        return $this->write((string) (bool) $boolean, 1);
167    }
168
169    /**
170     * Write an integer.
171     *
172     * @param   int     $integer    Integer.
173     * @return  mixed
174     */
175    public function writeInteger($integer)
176    {
177        $integer = (string) (int) $integer;
178
179        return $this->write($integer, strlen($integer));
180    }
181
182    /**
183     * Write a float.
184     *
185     * @param   float   $float    Float.
186     * @return  mixed
187     */
188    public function writeFloat($float)
189    {
190        $float = (string) (float) $float;
191
192        return $this->write($float, strlen($float));
193    }
194
195    /**
196     * Write an array.
197     *
198     * @param   array   $array    Array.
199     * @return  mixed
200     */
201    public function writeArray(array $array)
202    {
203        $array = var_export($array, true);
204
205        return $this->write($array, strlen($array));
206    }
207
208    /**
209     * Write a line.
210     *
211     * @param   string  $line    Line.
212     * @return  mixed
213     */
214    public function writeLine($line)
215    {
216        if (false === $n = strpos($line, "\n")) {
217            return $this->write($line . "\n", strlen($line) + 1);
218        }
219
220        ++$n;
221
222        return $this->write(substr($line, 0, $n), $n);
223    }
224
225    /**
226     * Write all, i.e. as much as possible.
227     *
228     * @param   string  $string    String.
229     * @return  mixed
230     */
231    public function writeAll($string)
232    {
233        return $this->write($string, strlen($string));
234    }
235
236    /**
237     * Truncate a file to a given length.
238     *
239     * @param   int     $size    Size.
240     * @return  bool
241     */
242    public function truncate($size)
243    {
244        return ftruncate($this->getStream(), $size);
245    }
246}
247