Completed
Push — master ( 3eed6d...7635b2 )
by Sebastian
04:09 queued 01:07
created

File::setupOut()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 2
nop 1
crap 3
1
<?php
2
namespace phpbu\App\Log;
3
4
use InvalidArgumentException;
5
6
/**
7
 * Class that can write to a file or a socket.
8
 *
9
 *
10
 * @package    phpbu
11
 * @subpackage Log
12
 * @author     Sebastian Feldmann <[email protected]>
13
 * @copyright  Sebastian Feldmann <[email protected]>
14
 * @license    https://opensource.org/licenses/MIT The MIT License (MIT)
15
 * @link       http://phpbu.de/
16
 */
17
class File
18
{
19
    /**
20
     * @var resource
21
     */
22
    protected $out;
23
24
    /**
25
     * @var string
26
     */
27
    protected $outTarget;
28
29
    /**
30
     * Set output target.
31
     *
32
     * @param mixed $out
33
     */
34 6
    public function setOut($out)
35
    {
36 6
        if (empty($out)) {
37 1
            throw new InvalidArgumentException('Out can\'t be empty');
38
        }
39 5
        if (is_string($out)) {
40 4
            $this->setupOut($out);
41
        } else {
42 1
            $this->out = $out;
43
        }
44 5
    }
45
46
    /**
47
     * Setup the out resource
48
     *
49
     * @param string $out
50
     */
51 4
    protected function setupOut(string $out)
52
    {
53 4
        if (strpos($out, 'php://') === false && !is_dir(dirname($out))) {
54 1
            mkdir(dirname($out), 0777, true);
55
        }
56 4
        $this->out       = fopen($out, 'wt');
57 4
        $this->outTarget = $out;
58 4
    }
59
60
    /**
61
     * @param string $buffer
62
     */
63 5
    public function write($buffer)
64
    {
65 5
        fwrite($this->out, $buffer);
66 5
    }
67
68
    /**
69
     * Close output if it's not to a php stream.
70
     */
71 3
    public function close()
72
    {
73 3
        if ($this->out && strncmp($this->outTarget, 'php://', 6) !== 0) {
74 1
            fclose($this->out);
75
        }
76 3
    }
77
}
78