Completed
Pull Request — master (#24)
by Hiraku
04:03
created

OutputFile::setFailure()   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 1
Metric Value
c 1
b 0
f 1
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 $createdDirs = array();
23
24
    /** @var bool */
25
    private $success = true;
26
27 4
    public function __construct($fileName)
28
    {
29 4
        $this->fileName = $fileName;
30 4
        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 3
        $this->createDir($fileName);
37
38 2
        $this->fp = fopen($fileName, 'wb');
39 2
        if (!$this->fp) {
40 1
            throw new Downloader\TransportException(
41 1
                "The file could not be written to $fileName."
42 1
            );
43
        }
44 1
    }
45
46 1
    public function __destruct()
47
    {
48 1
        if ($this->fp) {
49 1
            fclose($this->fp);
50 1
        }
51
52 1
        if (! $this->success) {
53 1
            unlink($this->fileName);
54 1
            foreach ($this->createdDirs as $dir) {
55 1
                rmdir($dir);
56 1
            }
57 1
        }
58 1
    }
59
60 1
    public function getPointer()
61
    {
62 1
        return $this->fp;
63
    }
64
65 1
    public function setFailure()
66
    {
67 1
        $this->success = false;
68 1
    }
69
70 3
    protected function createDir($fileName)
71
    {
72 3
        $dir = $fileName;
73 3
        $createdDirs = array();
74
        do {
75 3
            $dir = dirname($dir);
76 3
            $createdDirs[] = $dir;
77 3
        } while (! file_exists($dir));
78 3
        array_pop($createdDirs);
79 3
        $this->createdDirs = array_reverse($createdDirs);
80
81 3
        $targetdir = dirname($fileName);
82 3
        if (!file_exists($targetdir)) {
83 2
            $created = mkdir($targetdir, 0766, true);
84 2
            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 1
        }
91 2
    }
92
}
93