Completed
Push — dev ( fe3822...8e18b7 )
by Zach
02:29
created

Filesystem::guessNamespace()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 1
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Yarak\Helpers;
4
5
use Yarak\Exceptions\WriteError;
6
7
trait Filesystem
8
{
9
    /**
10
     * Create all directories listed in directories array.
11
     *
12
     * @param array $directories
13
     */
14
    protected function makeDirectoryStructure(array $directories)
15
    {
16
        foreach ($directories as $directory) {
17
            if (!file_exists($directory)) {
18
                mkdir($directory);
19
            }
20
        }
21
    }
22
23
    /**
24
     * Write contents to path.
25
     *
26
     * @param string $path
27
     * @param string $contents
28
     *
29
     * @throws WriteError
30
     */
31
    protected function writeFile($path, $contents)
32
    {
33
        try {
34
            file_put_contents($path, $contents);
35
        } catch (\Exception $e) {
36
            throw WriteError::fileWriteFailed($e, $path);
37
        }
38
    }
39
40
    /**
41
     * Guess a namespace based on a path.
42
     *
43
     * @param string $path
44
     *
45
     * @return string|null
46
     */
47
    protected function guessNamespace($path)
48
    {
49
        if (defined('APP_PATH')) {
50
            $appPathArray = explode('/', APP_PATH);
51
52
            $relativePath = array_diff(explode('/', $path), $appPathArray);
53
54
            array_unshift($relativePath, array_pop($appPathArray));
55
56
            $relativePath = array_map('ucfirst', $relativePath);
57
58
            return implode('\\', $relativePath);
59
        }
60
61
        return;
62
    }
63
}
64