Completed
Pull Request — master (#24)
by Hiraku
02:08
created

OutputFile::createDir()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 22
rs 8.9197
cc 4
eloc 16
nc 3
nop 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 = true;
26
27
    public function __construct($fileName)
28
    {
29
        $this->fileName = $fileName;
30
        if (is_dir($fileName)) {
31
            throw new Downloader\TransportException(
32
                "The file could not be written to $fileName. Directory exists."
33
            );
34
        }
35
36
        $this->createDir($fileName);
37
38
        $this->fp = fopen($fileName, 'wb');
39
        if (!$this->fp) {
40
            throw new Downloader\TransportException(
41
                "The file could not be written to $fileName."
42
            );
43
        }
44
    }
45
46
    public function __destruct()
47
    {
48
        if ($this->fp) {
49
            fclose($this->fp);
50
        }
51
52
        if (! $this->success) {
53
            unlink($this->fileName);
54
            foreach ($this->createdDirs as $dir) {
55
                rmdir($dir);
56
            }
57
        }
58
    }
59
60
    public function getPointer()
61
    {
62
        return $this->fp;
63
    }
64
65
    public function setFailure()
66
    {
67
        $this->success = false;
68
    }
69
70
    protected function createDir($fileName)
71
    {
72
        $dir = $fileName;
73
        $createdDirs = array();
74
        do {
75
            $dir = dirname($dir);
76
            $createdDirs[] = $dir;
77
        } while (! file_exists($dir));
78
        array_pop($createdDirs);
79
        $this->createdDirs = array_reverse($createdDirs);
80
81
        $targetdir = dirname($fileName);
82
        if (!file_exists($targetdir)) {
83
            $created = mkdir($targetdir, 0766, true);
84
            if (!$created) {
85
                $this->success = false;
86
                throw new Downloader\TransportException(
87
                    "The file could not be written to $this->fileName."
88
                );
89
            }
90
        }
91
    }
92
}
93