Completed
Pull Request — master (#42)
by Hiraku
02:19
created

OutputFile::getPointer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
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 $createdDirs = array();
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 1
            );
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 1
            );
43
        }
44 5
    }
45
46 5
    public function __destruct()
47
    {
48 5
        if ($this->fp) {
49 5
            fclose($this->fp);
50 5
        }
51
52 5
        if (!$this->success) {
53 4
            unlink($this->fileName);
54 4
            foreach ($this->createdDirs as $dir) {
55 4
                rmdir($dir);
56 4
            }
57 4
        }
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
        $dir = $fileName;
73 7
        $createdDirs = array();
74
        do {
75 7
            $dir = dirname($dir);
76 7
            $createdDirs[] = $dir;
77 7
        } while (!file_exists($dir));
78 7
        array_pop($createdDirs);
79 7
        $this->createdDirs = array_reverse($createdDirs);
80
81 7
        $targetdir = dirname($fileName);
82 7
        if (!file_exists($targetdir)) {
83 6
            $created = mkdir($targetdir, 0766, true);
84 6
            if (!$created) {
85 1
                $this->success = false;
86 1
                throw new Downloader\TransportException(
87 1
                    "The file could not be written to $this->fileName."
88 1
                );
89
            }
90 5
        }
91 6
    }
92
}
93