Completed
Push — master ( d6a82f...065486 )
by Zach
13s
created

Filesystem::makeDirectoryStructure()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 6
nop 2
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Yarak\Helpers;
4
5
use Yarak\Console\Output\Output;
6
use Yarak\Exceptions\WriteError;
7
8
trait Filesystem
9
{
10
    /**
11
     * Create all directories listed in directories array.
12
     * Return the number of created directories.
13
     *
14
     * @param array  $directories
15
     * @param Output $output
16
     *
17
     * @return int
18
     */
19
    protected function makeDirectoryStructure(array $directories, Output $output = null)
20
    {
21
        $createdDirs = 0;
22
23
        foreach ($directories as $key => $directory) {
24
            if (!file_exists($directory)) {
25
                if (mkdir($directory)) {
26
                    $createdDirs++;
27
                }
28
29
                if ($output) {
30
                    $output->writeInfo("Created {$key} directory.");
31
                }
32
            }
33
        }
34
35
        return $createdDirs;
36
    }
37
38
    /**
39
     * Write contents to path.
40
     *
41
     * @param string $path
42
     * @param string $contents
43
     *
44
     * @throws WriteError
45
     */
46
    protected function writeFile($path, $contents)
47
    {
48
        try {
49
            file_put_contents($path, $contents);
50
        } catch (\Exception $e) {
51
            throw WriteError::fileWriteFailed($e, $path);
52
        }
53
    }
54
}
55