Completed
Pull Request — master (#13)
by Victor
01:05
created

FileSystemWriter::validate()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 8
cts 8
cp 1
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 7
nc 4
nop 0
crap 6
1
<?php
2
3
namespace LazyEight\DiTesto\FileSystem;
4
5
use LazyEight\DiTesto\Interfaces\FileSystem\FileSystemPathInterface;
6
use LazyEight\DiTesto\Interfaces\FileSystem\FileSystemWriterInterface;
7
use LazyEight\DiTesto\FileSystem\Exceptions\FileSystemException;
8
use LazyEight\DiTesto\FileSystem\Exceptions\InvalidPathException;
9
10
class FileSystemWriter implements FileSystemWriterInterface
11
{
12
    /**
13
     * @var FileSystemPathInterface
14
     */
15
    private $path;
16
17
    /**
18
     * FileSystemWriter constructor.
19
     * @param FileSystemPathInterface $path
20
     */
21 2
    public function __construct(FileSystemPathInterface $path)
22
    {
23 2
        $this->path = $path;
24 2
    }
25
26
    /**
27
     * @inheritDoc
28
     */
29 1
    public function isWritable(): bool
30
    {
31 1
        return is_writable($this->path->rawPath());
32
    }
33
34
    /**
35
     * @inheritDoc
36
     */
37 1
    public function write(string $content)
38
    {
39 1
        $this->validate();
40 1
        file_put_contents($this->path->rawPath(), $content);
41 1
    }
42
43
    /**
44
     * @return bool
45
     */
46 1
    private function isWritablePath()
47
    {
48 1
        return is_writable($this->path->pathName());
49
    }
50
51
    /**
52
     * @throws FileSystemException
53
     * @throws InvalidPathException
54
     */
55 4
    private function validate()
56
    {
57 4
        if ($this->path->isDirectory()) {
58 1
            throw new InvalidPathException("Error, can't write file content to a directory.");
59
        }
60
61 3
        if (!file_exists($this->path->rawPath()) && !$this->isWritablePath()) {
62 1
            throw new FileSystemException("Error, can't write to the file. The path must be writable.");
63
        }
64
65 2
        if (file_exists($this->path->rawPath()) && !$this->isWritable()) {
66 1
            throw new FileSystemException("Error, can't write to the file. The file must be writable.");
67
        }
68 1
    }
69
70
71
}
72