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\Link;
38
39use Hoa\File;
40use Hoa\Stream;
41
42/**
43 * Class \Hoa\File\Link\Write.
44 *
45 * File handler.
46 *
47 * @license    New BSD License
48 */
49class Write extends Link implements Stream\IStream\Out
50{
51    /**
52     * Open a file.
53     *
54     * @param   string  $streamName    Stream name.
55     * @param   string  $mode          Open mode, see the parent::MODE_* constants.
56     * @param   string  $context       Context ID (please, see the
57     *                                 \Hoa\Stream\Context class).
58     * @param   bool    $wait          Differ opening or not.
59     */
60    public function __construct(
61        $streamName,
62        $mode    = parent::MODE_APPEND_WRITE,
63        $context = null,
64        $wait    = false
65    ) {
66        parent::__construct($streamName, $mode, $context, $wait);
67
68        return;
69    }
70
71    /**
72     * Open the stream and return the associated resource.
73     *
74     * @param   string               $streamName    Stream name (e.g. path or URL).
75     * @param   \Hoa\Stream\Context  $context       Context.
76     * @return  resource
77     * @throws  \Hoa\File\Exception\FileDoesNotExist
78     * @throws  \Hoa\File\Exception
79     */
80    protected function &_open($streamName, Stream\Context $context = null)
81    {
82        static $createModes = [
83            parent::MODE_TRUNCATE_WRITE,
84            parent::MODE_APPEND_WRITE,
85            parent::MODE_CREATE_WRITE
86        ];
87
88        if (!in_array($this->getMode(), $createModes)) {
89            throw new File\Exception(
90                'Open mode are not supported; given %d. Only %s are supported.',
91                0,
92                [$this->getMode(), implode(', ', $createModes)]
93            );
94        }
95
96        preg_match('#^(\w+)://#', $streamName, $match);
97
98        if (((isset($match[1]) && $match[1] == 'file') || !isset($match[1])) &&
99            !file_exists($streamName)) {
100            throw new File\Exception\FileDoesNotExist(
101                'File %s does not exist.',
102                1,
103                $streamName
104            );
105        }
106
107        $out = parent::_open($streamName, $context);
108
109        return $out;
110    }
111
112    /**
113     * Write n characters.
114     *
115     * @param   string  $string    String.
116     * @param   int     $length    Length.
117     * @return  mixed
118     * @throws  \Hoa\File\Exception
119     */
120    public function write($string, $length)
121    {
122        if (0 > $length) {
123            throw new File\Exception(
124                'Length must be greater than 0, given %d.',
125                2,
126                $length
127            );
128        }
129
130        return fwrite($this->getStream(), $string, $length);
131    }
132
133    /**
134     * Write a string.
135     *
136     * @param   string  $string    String.
137     * @return  mixed
138     */
139    public function writeString($string)
140    {
141        $string = (string) $string;
142
143        return $this->write($string, strlen($string));
144    }
145
146    /**
147     * Write a character.
148     *
149     * @param   string  $char    Character.
150     * @return  mixed
151     */
152    public function writeCharacter($char)
153    {
154        return $this->write((string) $char[0], 1);
155    }
156
157    /**
158     * Write a boolean.
159     *
160     * @param   bool    $boolean    Boolean.
161     * @return  mixed
162     */
163    public function writeBoolean($boolean)
164    {
165        return $this->write((string) (bool) $boolean, 1);
166    }
167
168    /**
169     * Write an integer.
170     *
171     * @param   int     $integer    Integer.
172     * @return  mixed
173     */
174    public function writeInteger($integer)
175    {
176        $integer = (string) (int) $integer;
177
178        return $this->write($integer, strlen($integer));
179    }
180
181    /**
182     * Write a float.
183     *
184     * @param   float   $float    Float.
185     * @return  mixed
186     */
187    public function writeFloat($float)
188    {
189        $float = (string) (float) $float;
190
191        return $this->write($float, strlen($float));
192    }
193
194    /**
195     * Write an array.
196     *
197     * @param   array   $array    Array.
198     * @return  mixed
199     */
200    public function writeArray(array $array)
201    {
202        $array = var_export($array, true);
203
204        return $this->write($array, strlen($array));
205    }
206
207    /**
208     * Write a line.
209     *
210     * @param   string  $line    Line.
211     * @return  mixed
212     */
213    public function writeLine($line)
214    {
215        if (false === $n = strpos($line, "\n")) {
216            return $this->write($line . "\n", strlen($line) + 1);
217        }
218
219        ++$n;
220
221        return $this->write(substr($line, 0, $n), $n);
222    }
223
224    /**
225     * Write all, i.e. as much as possible.
226     *
227     * @param   string  $string    String.
228     * @return  mixed
229     */
230    public function writeAll($string)
231    {
232        return $this->write($string, strlen($string));
233    }
234
235    /**
236     * Truncate a file to a given length.
237     *
238     * @param   int     $size    Size.
239     * @return  bool
240     */
241    public function truncate($size)
242    {
243        return ftruncate($this->getStream(), $size);
244    }
245}
246