FileTrait::createDirectory()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 14
rs 9.4285
cc 3
eloc 8
nc 3
nop 2
1
<?php
2
/*
3
 * This file is part of the Borobudur-Config package.
4
 *
5
 * (c) Hexacodelabs <http://hexacodelabs.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Borobudur\Config\FileLoader;
12
13
use Borobudur\Config\Exception\Exception;
14
15
/**
16
 * @author      Iqbal Maulana <[email protected]>
17
 * @created     8/12/15
18
 */
19
trait FileTrait
20
{
21
    /**
22
     * Create directory recursively.
23
     *
24
     * @param string $directory
25
     * @param int    $perm
26
     *
27
     * @throws Exception
28
     */
29
    protected function createDirectory($directory, $perm = 0777)
30
    {
31
        if (!is_dir($directory)) {
32
            try {
33
                mkdir($directory, $perm, true);
34
            } catch (Exception $e) {
35
                self::assertIsDirectory($directory);
36
            }
37
38
            return;
39
        }
40
41
        self::assertIsDirectoryWritable($directory);
42
    }
43
44
    /**
45
     * Write content to file.
46
     *
47
     * @param string $content
48
     * @param string $target
49
     * @param int    $perm
50
     *
51
     * @throws Exception
52
     */
53
    protected function writeFile($content, $target, $perm = 0666)
54
    {
55
        $dir = pathinfo($target, PATHINFO_DIRNAME);
56
57
        $this->createDirectory($dir);
58
        file_put_contents($target, $content);
59
        $this->chmod($target, $perm);
60
    }
61
62
    /**
63
     * Chmod target file or directory.
64
     *
65
     * @param string $target
66
     * @param int    $perm
67
     */
68
    protected function chmod($target, $perm = 0666)
69
    {
70
        try {
71
            chmod($target, $perm & ~umask());
72
        } catch (Exception $e) {
73
            // do nothing
74
        }
75
    }
76
77
    /**
78
     * Assert if directory is exist.
79
     *
80
     * @param string $directory
81
     *
82
     * @throws Exception
83
     */
84
    private static function assertIsDirectory($directory)
85
    {
86
        if (false === is_dir($directory)) {
87
            throw new Exception(sprintf('Forbidden create directory "%s".', $directory));
88
        }
89
    }
90
91
    /**
92
     * Assert if directory is writable.
93
     *
94
     * @param string $directory
95
     *
96
     * @throws Exception
97
     */
98
    private static function assertIsDirectoryWritable($directory)
99
    {
100
        if (false === is_writable($directory)) {
101
            throw new Exception(sprintf('Forbidden create directory "%s".', $directory));
102
        }
103
    }
104
}
105