Completed
Pull Request — master (#52)
by Hiraku
02:16
created

OutputFile::setSuccess()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/*
3
 * @author Hiraku NAKANO
4
 * @license MIT https://github.com/hirak/prestissimo
5
 */
6
namespace Hirak\Prestissimo;
7
8
use Composer\Downloader;
9
10
/**
11
 * file pointer wrapper with auto clean
12
 */
13
class OutputFile
14
{
15
    /** @var resource<file>|null */
16
    protected $fp;
17
18
    /** @var string */
19
    protected $fileName;
20
21
    /** @var string */
22
    protected $createdDir;
23
24
    /** @var bool */
25
    private $success = false;
26
27 8
    public function __construct($fileName)
28
    {
29 8
        $this->fileName = $fileName;
30 8
        if (is_dir($fileName)) {
31 1
            throw new Downloader\TransportException(
32 1
                "The file could not be written to $fileName. Directory exists."
33
            );
34
        }
35
36 7
        $this->createDir($fileName);
37
38 6
        $this->fp = fopen($fileName, 'wb');
39 6
        if (!$this->fp) {
40 1
            throw new Downloader\TransportException(
41 1
                "The file could not be written to $fileName."
42
            );
43
        }
44 5
    }
45
46 5
    public function __destruct()
47
    {
48 5
        if ($this->fp) {
49 5
            fclose($this->fp);
50
        }
51
52 5
        if (!$this->success) {
53 4
            unlink($this->fileName);
54 4
            if ($this->createdDir) {
55 4
                rmdir($this->createdDir);
56
            }
57
        }
58 5
    }
59
60 5
    public function getPointer()
61
    {
62 5
        return $this->fp;
63
    }
64
65 1
    public function setSuccess()
66
    {
67 1
        $this->success = true;
68 1
    }
69
70 7
    protected function createDir($fileName)
71
    {
72 7
        $targetdir = dirname($fileName);
73 7
        if (!file_exists($targetdir)) {
74 6
            if (!mkdir($targetdir, 0766, true)) {
75 1
                throw new Downloader\TransportException(
76 1
                    "The file could not be written to $this->fileName."
77
                );
78
            }
79 5
            $this->createdDir = $targetdir;
80
        }
81 6
    }
82
}
83