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

File   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 0
dl 0
loc 61
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A close() 0 6 3
A setOut() 0 11 3
A setupOut() 0 8 3
A write() 0 4 1
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