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

Filesystem::writeFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 8
rs 9.4285
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